source: trunk/macosx/Controller.m @ 1047

Last change on this file since 1047 was 1047, checked in by livings124, 15 years ago

use full path for autoimport check

  • Property svn:keywords set to Date Rev Author Id
File size: 86.3 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 1047 2006-10-31 21:01:12Z livings124 $
3 *
4 * Copyright (c) 2005-2006 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import <IOKit/IOMessage.h>
26
27#import "Controller.h"
28#import "Torrent.h"
29#import "TorrentCell.h"
30#import "TorrentTableView.h"
31#import "StringAdditions.h"
32#import "UKKQueue.h"
33#import "ActionMenuSpeedToDisplayLimitTransformer.h"
34#import "ActionMenuRatioToDisplayRatioTransformer.h"
35#import "ExpandedPathToPathTransformer.h"
36#import "ExpandedPathToIconTransformer.h"
37
38#import <Sparkle/Sparkle.h>
39
40#define TOOLBAR_OPEN            @"Toolbar Open"
41#define TOOLBAR_REMOVE          @"Toolbar Remove"
42#define TOOLBAR_INFO            @"Toolbar Info"
43#define TOOLBAR_PAUSE_ALL       @"Toolbar Pause All"
44#define TOOLBAR_RESUME_ALL      @"Toolbar Resume All"
45#define TOOLBAR_PAUSE_SELECTED  @"Toolbar Pause Selected"
46#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected"
47#define TOOLBAR_FILTER          @"Toolbar Toggle Filter"
48
49#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
50#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
51#define GROWL_AUTO_ADD          @"Torrent Auto Added"
52#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
53
54#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
55
56#define ROW_HEIGHT_REGULAR      65.0
57#define ROW_HEIGHT_SMALL        40.0
58#define WINDOW_REGULAR_WIDTH    468.0
59
60#define UPDATE_UI_SECONDS           1.0
61#define AUTO_SPEED_LIMIT_SECONDS    5.0
62
63#define WEBSITE_URL @"http://transmission.m0k.org/"
64#define FORUM_URL   @"http://transmission.m0k.org/forum/"
65
66static void sleepCallBack(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
67{
68    Controller * c = controller;
69    [c sleepCallBack: messageType argument: messageArgument];
70}
71
72@implementation Controller
73
74+ (void) initialize
75{
76    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
77        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
78   
79    //set custom value transformers
80    ActionMenuSpeedToDisplayLimitTransformer * limitTransformer =
81                        [[[ActionMenuSpeedToDisplayLimitTransformer alloc] init] autorelease];
82    [NSValueTransformer setValueTransformer: limitTransformer forName: @"ActionMenuSpeedToDisplayLimitTransformer"];
83   
84    ActionMenuRatioToDisplayRatioTransformer * ratioTransformer =
85                        [[[ActionMenuRatioToDisplayRatioTransformer alloc] init] autorelease];
86    [NSValueTransformer setValueTransformer: ratioTransformer forName: @"ActionMenuRatioToDisplayRatioTransformer"];
87   
88    ExpandedPathToPathTransformer * pathTransformer =
89                        [[[ExpandedPathToPathTransformer alloc] init] autorelease];
90    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
91   
92    ExpandedPathToIconTransformer * iconTransformer =
93                        [[[ExpandedPathToIconTransformer alloc] init] autorelease];
94    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
95}
96
97- (id) init
98{
99    if ((self = [super init]))
100    {
101        fLib = tr_init();
102       
103        fTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
104        fDisplayedTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
105       
106        fDefaults = [NSUserDefaults standardUserDefaults];
107       
108        fMessageController = [[MessageWindowController alloc] initWithWindowNibName: @"MessageWindow"];
109        fInfoController = [[InfoWindowController alloc] initWithWindowNibName: @"InfoWindow"];
110        fPrefsController = [[PrefsController alloc] initWithWindowNibName: @"PrefsWindow" handle: fLib];
111       
112        fBadger = [[Badger alloc] init];
113       
114        [GrowlApplicationBridge setGrowlDelegate: self];
115       
116        [[UKKQueue sharedFileWatcher] setDelegate: self];
117    }
118    return self;
119}
120
121- (void) dealloc
122{
123    [[NSNotificationCenter defaultCenter] removeObserver: self];
124   
125    [fInfoController release];
126    [fMessageController release];
127    [fPrefsController release];
128   
129    [fToolbar release];
130    [fTorrents release];
131    [fDisplayedTorrents release];
132    [fBadger release];
133   
134    [fSortType release];
135    [fFilterType release];
136   
137    [fAutoImportedNames release];
138   
139    tr_close(fLib);
140    [super dealloc];
141}
142
143- (void) awakeFromNib
144{
145    [fStatusBar setBackgroundImage: [NSImage imageNamed: @"StatusBarBackground.png"]];
146    [fFilterBar setBackgroundImage: [NSImage imageNamed: @"FilterBarBackground.png"]];
147   
148    [fWindow setAcceptsMouseMovedEvents: YES]; //ensure filter buttons display correctly
149
150    fToolbar = [[NSToolbar alloc] initWithIdentifier: @"Transmission Toolbar"];
151    [fToolbar setDelegate: self];
152    [fToolbar setAllowsUserCustomization: YES];
153    [fToolbar setAutosavesConfiguration: YES];
154    [fWindow setToolbar: fToolbar];
155    [fWindow setDelegate: self];
156   
157    [fWindow makeFirstResponder: fTableView];
158    [fWindow setExcludedFromWindowsMenu: YES];
159   
160    //set table size
161    if ([fDefaults boolForKey: @"SmallView"])
162        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
163   
164    //window min height
165    NSSize contentMinSize = [fWindow contentMinSize];
166    contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
167                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
168    [fWindow setContentMinSize: contentMinSize];
169   
170    //set info and filter keyboard shortcuts
171    unichar rightChar = NSRightArrowFunctionKey, leftChar = NSLeftArrowFunctionKey;
172    [fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & rightChar length: 1]];
173    [fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & leftChar length: 1]];
174   
175    [fNextFilterItem setKeyEquivalent: [NSString stringWithCharacters: & rightChar length: 1]];
176    [fNextFilterItem setKeyEquivalentModifierMask: NSCommandKeyMask + NSAlternateKeyMask];
177    [fPrevFilterItem setKeyEquivalent: [NSString stringWithCharacters: & leftChar length: 1]];
178    [fPrevFilterItem setKeyEquivalentModifierMask: NSCommandKeyMask + NSAlternateKeyMask];
179   
180    //set up filter bar
181    NSView * contentView = [fWindow contentView];
182    [fFilterBar setHidden: YES];
183   
184    NSRect filterBarFrame = [fFilterBar frame];
185    filterBarFrame.size.width = [fWindow frame].size.width;
186    [fFilterBar setFrame: filterBarFrame];
187   
188    [contentView addSubview: fFilterBar];
189    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
190   
191    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
192   
193    //set up status bar
194    [fStatusBar setHidden: YES];
195   
196    NSRect statusBarFrame = [fStatusBar frame];
197    statusBarFrame.size.width = [fWindow frame].size.width;
198    [fStatusBar setFrame: statusBarFrame];
199   
200    [contentView addSubview: fStatusBar];
201    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
202    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
203   
204    //set speed limit
205    fSpeedLimitNormalImage = [fSpeedLimitButton image];
206    fSpeedLimitBlueImage = [NSImage imageNamed: @"SpeedLimitButtonBlue.png"];
207    fSpeedLimitGraphiteImage = [NSImage imageNamed: @"SpeedLimitButtonGraphite.png"];
208   
209    [self updateControlTint: nil];
210   
211    if ([fDefaults boolForKey: @"SpeedLimit"])
212    {
213        #warning get rid of
214        [fSpeedLimitItem setState: NSOnState];
215        [fSpeedLimitDockItem setState: NSOnState];
216       
217        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
218                                        ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage];
219    }
220
221    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
222                                "Main window -> 1st bottom left button (action) tooltip")];
223    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
224                                "Main window -> 2nd bottom left button (turtle) tooltip")];
225   
226    [fPrefsController setUpdater: fUpdater];
227   
228    [fTableView setTorrents: fDisplayedTorrents];
229    [[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell: [[TorrentCell alloc] init]];
230
231    [fTableView registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType,
232                                                        TORRENT_TABLE_VIEW_DATA_TYPE, nil]];
233
234    //register for sleep notifications
235    IONotificationPortRef notify;
236    io_object_t iterator;
237    if (fRootPort = IORegisterForSystemPower(self, & notify, sleepCallBack, & iterator))
238        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
239    else
240        NSLog(@"Could not IORegisterForSystemPower");
241
242    //load torrents from history
243    Torrent * torrent;
244    NSDictionary * historyItem;
245    NSEnumerator * enumerator = [[fDefaults arrayForKey: @"History"] objectEnumerator];
246    while ((historyItem = [enumerator nextObject]))
247        if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
248        {
249            [fTorrents addObject: torrent];
250            [torrent release];
251        }
252   
253    //set sort
254    fSortType = [[fDefaults stringForKey: @"Sort"] retain];
255   
256    NSMenuItem * currentSortItem, * currentSortActionItem;
257    if ([fSortType isEqualToString: @"Name"])
258    {
259        currentSortItem = fNameSortItem;
260        currentSortActionItem = fNameSortActionItem;
261    }
262    else if ([fSortType isEqualToString: @"State"])
263    {
264        currentSortItem = fStateSortItem;
265        currentSortActionItem = fStateSortActionItem;
266    }
267    else if ([fSortType isEqualToString: @"Progress"])
268    {
269        currentSortItem = fProgressSortItem;
270        currentSortActionItem = fProgressSortActionItem;
271    }
272    else if ([fSortType isEqualToString: @"Date"])
273    {
274        currentSortItem = fDateSortItem;
275        currentSortActionItem = fDateSortActionItem;
276    }
277    else
278    {
279        currentSortItem = fOrderSortItem;
280        currentSortActionItem = fOrderSortActionItem;
281    }
282    [currentSortItem setState: NSOnState];
283    [currentSortActionItem setState: NSOnState];
284   
285    //set filter
286    fFilterType = [[fDefaults stringForKey: @"Filter"] retain];
287
288    BarButton * currentFilterButton;
289    if ([fFilterType isEqualToString: @"Pause"])
290        currentFilterButton = fPauseFilterButton;
291    else if ([fFilterType isEqualToString: @"Seed"])
292        currentFilterButton = fSeedFilterButton;
293    else if ([fFilterType isEqualToString: @"Download"])
294        currentFilterButton = fDownloadFilterButton;
295    else
296        currentFilterButton = fNoFilterButton;
297
298    [currentFilterButton setEnabled: YES];
299   
300    //observe notifications
301    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
302   
303    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
304                    name: @"TorrentFinishedDownloading" object: nil];
305   
306    [nc addObserver: self selector: @selector(updateControlTint:)
307                    name: NSControlTintDidChangeNotification object: nil];
308   
309    [nc addObserver: self selector: @selector(prepareForUpdate:)
310                    name: SUUpdaterWillRestartNotification object: nil];
311    fUpdateInProgress = NO;
312   
313    [nc addObserver: self selector: @selector(autoSpeedLimitChange:)
314                    name: @"AutoSpeedLimitChange" object: nil];
315   
316    [nc addObserver: self selector: @selector(changeAutoImport)
317                    name: @"AutoImportSettingChange" object: nil];
318   
319    [nc addObserver: self selector: @selector(setWindowSizeToFit)
320                    name: @"AutoSizeSettingChange" object: nil];
321   
322    //check to start another because of stopped torrent
323    [nc addObserver: self selector: @selector(checkWaitingForStopped:)
324                    name: @"StoppedDownloading" object: nil];
325   
326    //check all torrents for starting
327    [nc addObserver: self selector: @selector(globalStartSettingChange:)
328                    name: @"GlobalStartSettingChange" object: nil];
329   
330    //check if torrent should now start
331    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
332                    name: @"TorrentStoppedForRatio" object: nil];
333   
334    //change that just impacts the dock badge
335    [nc addObserver: self selector: @selector(resetDockBadge:)
336                    name: @"DockBadgeChange" object: nil];
337
338    //timer to update the interface every second
339    fCompleted = 0;
340    [self updateUI: nil];
341    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
342        selector: @selector(updateUI:) userInfo: nil repeats: YES];
343    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
344    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
345   
346    [self applyFilter: nil];
347   
348    [fWindow makeKeyAndOrderFront: nil];
349
350    if ([fDefaults boolForKey: @"InfoVisible"])
351        [self showInfo: nil];
352   
353    //timer to auto toggle speed limit
354    [self autoSpeedLimitChange: nil];
355    fSpeedLimitTimer = [NSTimer scheduledTimerWithTimeInterval: AUTO_SPEED_LIMIT_SECONDS target: self
356        selector: @selector(autoSpeedLimit:) userInfo: nil repeats: YES];
357   
358    //auto importing
359    fAutoImportedNames = [[NSMutableArray alloc] init];
360    [self checkAutoImportDirectory];
361}
362
363- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
364{
365    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
366        [fWindow makeKeyAndOrderFront: nil];
367    return NO;
368}
369
370- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
371{
372    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
373    {
374        int active = 0, downloading = 0;
375        Torrent * torrent;
376        NSEnumerator * enumerator = [fTorrents objectEnumerator];
377        while ((torrent = [enumerator nextObject]))
378            if ([torrent isActive])
379            {
380                active++;
381                if (![torrent isSeeding])
382                    downloading++;
383            }
384
385        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
386        {
387            NSString * message = active == 1
388                ? NSLocalizedString(@"There is an active transfer. Do you really want to quit?",
389                    "Confirm Quit panel -> message")
390                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers. Do you really want to quit?",
391                    "Confirm Quit panel -> message"), active];
392
393            NSBeginAlertSheet(NSLocalizedString(@"Confirm Quit", "Confirm Quit panel -> title"),
394                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
395                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
396                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
397            return NSTerminateLater;
398        }
399    }
400
401    return NSTerminateNow;
402}
403
404- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
405{
406    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
407}
408
409- (void) applicationWillTerminate: (NSNotification *) notification
410{
411    //stop timers
412    [fSpeedLimitTimer invalidate];
413    [fTimer invalidate];
414   
415    //save history and stop running torrents
416    [self updateTorrentHistory];
417    [fTorrents makeObjectsPerformSelector: @selector(stopTransferForQuit)];
418   
419    //disable NAT traversal
420    tr_natTraversalDisable(fLib);
421   
422    //remember window states and close all windows
423    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
424    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
425    [self showStatusBar: NO animate: NO];
426    [self showFilterBar: NO animate: NO];
427   
428    //clear badge
429    [fBadger clearBadge];
430
431    //end quickly if the app is updating
432    if (fUpdateInProgress)
433        return;
434
435    //wait for running transfers to stop (5 second timeout) and for NAT to be disabled
436    NSDate * start = [NSDate date];
437    BOOL timeUp = NO;
438   
439    NSEnumerator * enumerator = [fTorrents objectEnumerator];
440    Torrent * torrent;
441    while (!timeUp && ((torrent = [enumerator nextObject]) || tr_natTraversalStatus(fLib) != TR_NAT_TRAVERSAL_DISABLED))
442        while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
443        {
444            usleep(100000);
445            [torrent update];
446        }
447}
448
449- (NSArray *) torrentsAtIndexes: (NSIndexSet *) indexSet
450{
451    if ([fDisplayedTorrents respondsToSelector: @selector(objectsAtIndexes:)])
452        return [fDisplayedTorrents objectsAtIndexes: indexSet];
453    else
454    {
455        NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [indexSet count]];
456        unsigned int i;
457        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
458            [torrents addObject: [fDisplayedTorrents objectAtIndex: i]];
459
460        return torrents;
461    }
462}
463
464- (void) application: (NSApplication *) sender openFiles: (NSArray *) filenames
465{
466    [self openFiles: filenames ignoreDownloadFolder: NO];
467}
468
469- (void) openFiles: (NSArray *) filenames ignoreDownloadFolder: (BOOL) ignore
470{
471    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"], * torrentPath;
472   
473    if (ignore || [downloadChoice isEqualToString: @"Ask"])
474    {
475        [self openFilesAsk: [filenames mutableCopy]];
476        return;
477    }
478   
479    Torrent * torrent;
480    NSEnumerator * enumerator = [filenames objectEnumerator];
481    while ((torrentPath = [enumerator nextObject]))
482    {
483        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
484            continue;
485
486        //add it to the "File > Open Recent" menu
487        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
488
489        NSString * folder = [downloadChoice isEqualToString: @"Constant"]
490            ? [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]
491            : [torrentPath stringByDeletingLastPathComponent];
492       
493        [torrent setDownloadFolder: folder];
494        [torrent update];
495        [self attemptToStartAuto: torrent];
496       
497        [fTorrents addObject: torrent];
498        [torrent release];
499    }
500
501    [self updateUI: nil];
502    [self applyFilter: nil];
503   
504    [self updateTorrentHistory];
505}
506
507//called by the main open method to show sheet for choosing download location
508- (void) openFilesAsk: (NSMutableArray *) files
509{
510    NSString * torrentPath;
511    Torrent * torrent;
512    do
513    {
514        if ([files count] == 0) //recursive base case
515        {
516            [files release];
517           
518            [self updateTorrentHistory];
519            return;
520        }
521   
522        torrentPath = [files objectAtIndex: 0];
523        torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib];
524       
525        [files removeObjectAtIndex: 0];
526    } while (!torrent);
527
528    //add it to the "File > Open Recent" menu
529    [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
530
531    NSOpenPanel * panel = [NSOpenPanel openPanel];
532
533    [panel setPrompt: @"Select"];
534    [panel setAllowsMultipleSelection: NO];
535    [panel setCanChooseFiles: NO];
536    [panel setCanChooseDirectories: YES];
537
538    [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
539                        "Open torrent -> select destination folder"), [torrent name]]];
540   
541    NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: torrent, @"Torrent", files, @"Files", nil];
542
543    [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
544            didEndSelector: @selector(folderChoiceClosed:returnCode:contextInfo:) contextInfo: dictionary];
545}
546
547- (void) folderChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code
548    contextInfo: (NSDictionary *) dictionary
549{
550    Torrent * torrent = [dictionary objectForKey: @"Torrent"];
551
552    if (code == NSOKButton)
553    {
554        [torrent setDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
555        [torrent update];
556        [self attemptToStartAuto: torrent];
557       
558        [fTorrents addObject: torrent];
559       
560        [self updateUI: nil];
561        [self applyFilter: nil];
562    }
563   
564    [self performSelectorOnMainThread: @selector(openFilesAsk:) withObject: [dictionary objectForKey: @"Files"]
565                        waitUntilDone: NO];
566   
567    [torrent release];
568    [dictionary release];
569}
570
571//called on by applescript
572- (void) open: (NSArray *) files
573{
574    [self performSelectorOnMainThread: @selector(openFiles:) withObject: files waitUntilDone: NO];
575}
576
577- (void) openFiles: (NSArray *) filenames
578{
579    [self openFiles: filenames ignoreDownloadFolder: NO];
580}
581
582- (void) openShowSheet: (id) sender
583{
584    NSOpenPanel * panel = [NSOpenPanel openPanel];
585
586    [panel setAllowsMultipleSelection: YES];
587    [panel setCanChooseFiles: YES];
588    [panel setCanChooseDirectories: NO];
589
590    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
591        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
592        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
593}
594
595- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSNumber *) ignore
596{
597    if (code == NSOKButton)
598    {
599        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
600                                        [panel filenames], @"Files", ignore, @"Ignore", nil];
601        [self performSelectorOnMainThread: @selector(openFromSheet:) withObject: dictionary waitUntilDone: NO];
602    }
603}
604
605- (void) openFromSheet: (NSDictionary *) dictionary
606{
607    [self openFiles: [dictionary objectForKey: @"Files"]
608        ignoreDownloadFolder: [[dictionary objectForKey: @"Ignore"] boolValue]];
609   
610    [dictionary release];
611}
612
613- (void) resumeSelectedTorrents: (id) sender
614{
615    [self resumeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
616}
617
618- (void) resumeAllTorrents: (id) sender
619{
620    [self resumeTorrents: fTorrents];
621}
622
623- (void) resumeTorrents: (NSArray *) torrents
624{
625    NSEnumerator * enumerator = [torrents objectEnumerator];
626    Torrent * torrent;
627    while ((torrent = [enumerator nextObject]))
628        [torrent setWaitToStart: YES];
629   
630    [self attemptToStartMultipleAuto: torrents];
631   
632    [self updateUI: nil];
633    [self applyFilter: nil];
634    [self updateTorrentHistory];
635}
636
637- (void) resumeSelectedTorrentsNoWait:  (id) sender
638{
639    [self resumeTorrentsNoWait: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
640}
641
642- (void) resumeWaitingTorrents: (id) sender
643{
644    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
645   
646    NSEnumerator * enumerator = [fTorrents objectEnumerator];
647    Torrent * torrent;
648    while ((torrent = [enumerator nextObject]))
649        if ([torrent waitingToStart])
650            [torrents addObject: torrent];
651   
652    [self resumeTorrentsNoWait: torrents];
653}
654
655- (void) resumeTorrentsNoWait: (NSArray *) torrents
656{
657    //iterate through instead of all at once to ensure no conflicts
658    NSEnumerator * enumerator = [torrents objectEnumerator];
659    Torrent * torrent;
660    while ((torrent = [enumerator nextObject]))
661        [torrent startTransfer];
662   
663    [self updateUI: nil];
664    [self applyFilter: nil];
665    [self updateTorrentHistory];
666}
667
668- (void) stopSelectedTorrents: (id) sender
669{
670    [self stopTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
671}
672
673- (void) stopAllTorrents: (id) sender
674{
675    [self stopTorrents: fTorrents];
676}
677
678- (void) stopTorrents: (NSArray *) torrents
679{
680    //don't want any of these starting then stopping
681    NSEnumerator * enumerator = [torrents objectEnumerator];
682    Torrent * torrent;
683    while ((torrent = [enumerator nextObject]))
684        [torrent setWaitToStart: NO];
685
686    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
687   
688    [self updateUI: nil];
689    [self applyFilter: nil];
690    [self updateTorrentHistory];
691}
692
693- (void) removeTorrents: (NSArray *) torrents
694        deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
695{
696    [torrents retain];
697    int active = 0, downloading = 0;
698
699    if ([fDefaults boolForKey: @"CheckRemove"])
700    {
701        Torrent * torrent;
702        NSEnumerator * enumerator = [torrents objectEnumerator];
703        while ((torrent = [enumerator nextObject]))
704            if ([torrent isActive])
705            {
706                active++;
707                if (![torrent isSeeding])
708                    downloading++;
709            }
710
711        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
712        {
713            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
714                torrents, @"Torrents",
715                [NSNumber numberWithBool: deleteData], @"DeleteData",
716                [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
717
718            NSString * title, * message;
719           
720            int selected = [fTableView numberOfSelectedRows];
721            if (selected == 1)
722            {
723                title = [NSString stringWithFormat: NSLocalizedString(@"Confirm Removal of \"%@\"",
724                            "Removal confirm panel -> title"),
725                            [[fDisplayedTorrents objectAtIndex: [fTableView selectedRow]] name]];
726                message = NSLocalizedString(@"This transfer is active."
727                            " Once removed, continuing the transfer will require the torrent file."
728                            " Do you really want to remove it?", "Removal confirm panel -> message");
729            }
730            else
731            {
732                title = [NSString stringWithFormat: NSLocalizedString(@"Confirm Removal of %d Transfers",
733                            "Removal confirm panel -> title"), selected];
734                if (selected == active)
735                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
736                                "Removal confirm panel -> message part 1"), active];
737                else
738                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
739                                "Removal confirm panel -> message part 1"), selected, active];
740                message = [message stringByAppendingString:
741                    NSLocalizedString(@" Once removed, continuing the transfers will require the torrent files."
742                    " Do you really want to remove them?", "Removal confirm panel -> message part 2")];
743            }
744
745            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
746                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
747                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
748            return;
749        }
750    }
751   
752    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
753}
754
755- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (NSDictionary *) dict
756{
757    NSArray * torrents = [dict objectForKey: @"Torrents"];
758    BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue],
759        deleteTorrent = [[dict objectForKey: @"DeleteTorrent"] boolValue];
760    [dict release];
761   
762    if (returnCode == NSAlertDefaultReturn)
763        [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
764    else
765        [torrents release];
766}
767
768- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
769{
770    //don't want any of these starting then stopping
771    NSEnumerator * enumerator = [torrents objectEnumerator];
772    Torrent * torrent;
773    while ((torrent = [enumerator nextObject]))
774        [torrent setWaitToStart: NO];
775
776    NSNumber * lowestOrderValue = [NSNumber numberWithInt: [torrents count]], * currentOrderValue;
777
778    enumerator = [torrents objectEnumerator];
779    while ((torrent = [enumerator nextObject]))
780    {
781        [torrent stopTransfer];
782
783        if (deleteData)
784            [torrent trashData];
785        if (deleteTorrent)
786            [torrent trashTorrent];
787       
788        //determine lowest order value
789        currentOrderValue = [torrent orderValue];
790        if ([lowestOrderValue compare: currentOrderValue] == NSOrderedDescending)
791            lowestOrderValue = currentOrderValue;
792
793        [torrent removeForever];
794       
795        [fTorrents removeObject: torrent];
796        [fDisplayedTorrents removeObject: torrent];
797    }
798    [torrents release];
799
800    //reset the order values if necessary
801    if ([lowestOrderValue intValue] < [fTorrents count])
802    {
803        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
804                                                @"orderValue" ascending: YES] autorelease];
805        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
806
807        NSArray * tempTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
808        [descriptors release];
809
810        int i;
811        for (i = [lowestOrderValue intValue]; i < [tempTorrents count]; i++)
812            [[tempTorrents objectAtIndex: i] setOrderValue: i];
813    }
814   
815    [fTableView deselectAll: nil];
816   
817    [self updateUI: nil];
818    [self applyFilter: nil];
819   
820    [self updateTorrentHistory];
821}
822
823- (void) removeNoDelete: (id) sender
824{
825    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
826                deleteData: NO deleteTorrent: NO];
827}
828
829- (void) removeDeleteData: (id) sender
830{
831    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
832                deleteData: YES deleteTorrent: NO];
833}
834
835- (void) removeDeleteTorrent: (id) sender
836{
837    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
838                deleteData: NO deleteTorrent: YES];
839}
840
841- (void) removeDeleteDataAndTorrent: (id) sender
842{
843    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
844                deleteData: YES deleteTorrent: YES];
845}
846
847- (void) copyTorrentFile: (id) sender
848{
849    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
850            [self torrentsAtIndexes: [fTableView selectedRowIndexes]]]];
851}
852
853- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
854{
855    if ([torrents count] == 0)
856    {
857        [torrents release];
858        return;
859    }
860
861    Torrent * torrent = [torrents objectAtIndex: 0];
862
863    //warn user if torrent file can't be found
864    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
865    {
866        NSAlert * alert = [[NSAlert alloc] init];
867        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
868        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
869                                "Torrent file copy alert -> title"), [torrent name]]];
870        [alert setInformativeText: [NSString stringWithFormat:
871                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
872                                    [torrent torrentLocation]]];
873        [alert setAlertStyle: NSWarningAlertStyle];
874       
875        [alert runModal];
876       
877        [torrents removeObjectAtIndex: 0];
878        [self copyTorrentFileForTorrents: torrents];
879    }
880    else
881    {
882        NSSavePanel * panel = [NSSavePanel savePanel];
883        [panel setRequiredFileType: @"torrent"];
884        [panel setCanSelectHiddenExtension: YES];
885       
886        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
887            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
888    }
889}
890
891- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (NSMutableArray *) torrents
892{
893    //if save successful, copy torrent to new location with name of data file
894    if (code == NSOKButton)
895        [[NSFileManager defaultManager] copyPath: [[torrents objectAtIndex: 0] torrentLocation]
896            toPath: [panel filename] handler: nil];
897   
898    [torrents removeObjectAtIndex: 0];
899    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
900}
901
902- (void) revealFile: (id) sender
903{
904    NSIndexSet * indexSet = [fTableView selectedRowIndexes];
905    unsigned int i;
906    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
907        [[fDisplayedTorrents objectAtIndex: i] revealData];
908}
909
910- (void) showPreferenceWindow: (id) sender
911{
912    NSWindow * window = [fPrefsController window];
913    if (![window isVisible])
914        [window center];
915
916    [window makeKeyAndOrderFront: nil];
917}
918
919- (void) showInfo: (id) sender
920{
921    if ([[fInfoController window] isVisible])
922        [fInfoController close];
923    else
924    {
925        [fInfoController updateInfoStats];
926        [[fInfoController window] orderFront: nil];
927    }
928}
929
930- (void) setInfoTab: (id) sender
931{
932    if (sender == fNextInfoTabItem)
933        [fInfoController setNextTab];
934    else
935        [fInfoController setPreviousTab];
936}
937
938- (void) showMessageWindow: (id) sender
939{
940    [fMessageController showWindow: nil];
941}
942
943- (void) updateControlTint: (NSNotification *) notification
944{
945    if ([fDefaults boolForKey: @"SpeedLimit"])
946        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
947                                        ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage];
948}
949
950- (void) updateUI: (NSTimer *) timer
951{
952    [fTorrents makeObjectsPerformSelector: @selector(update)];
953
954    //resort if necessary or just update the table
955    if ([fSortType isEqualToString: @"Progress"] || [fSortType isEqualToString: @"State"])
956        [self sortTorrents];
957    else
958        [fTableView reloadData];
959   
960    //update the global DL/UL rates
961    float downloadRate, uploadRate;
962    tr_torrentRates(fLib, & downloadRate, & uploadRate);
963    if (![fStatusBar isHidden])
964    {
965        [fTotalDLField setStringValue: [NSLocalizedString(@"Total DL: ", "Status bar -> total download")
966                                        stringByAppendingString: [NSString stringForSpeed: downloadRate]]];
967        [fTotalULField setStringValue: [NSLocalizedString(@"Total UL: ", "Status bar -> total upload")
968                                        stringByAppendingString: [NSString stringForSpeed: uploadRate]]];
969    }
970
971    //update non-constant parts of info window
972    if ([[fInfoController window] isVisible])
973        [fInfoController updateInfoStats];
974
975    //badge dock
976    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
977}
978
979- (void) torrentFinishedDownloading: (NSNotification *) notification
980{
981    Torrent * torrent = [notification object];
982
983    [self applyFilter: nil];
984    [self checkToStartWaiting: torrent];
985
986    if ([fDefaults boolForKey: @"PlayDownloadSound"])
987    {
988        NSSound * sound;
989        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
990            [sound play];
991    }
992
993    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
994        description: [torrent name]
995        notificationName: GROWL_DOWNLOAD_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
996
997    if (![fWindow isKeyWindow])
998        fCompleted++;
999}
1000
1001- (void) updateTorrentHistory
1002{
1003    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1004
1005    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1006    Torrent * torrent;
1007    while ((torrent = [enumerator nextObject]))
1008        [history addObject: [torrent history]];
1009
1010    [fDefaults setObject: history forKey: @"History"];
1011    [fDefaults synchronize];
1012}
1013
1014- (void) sortTorrents
1015{
1016    //remember selected rows if needed
1017    NSArray * selectedTorrents = nil;
1018    int numSelected = [fTableView numberOfSelectedRows];
1019    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1020        selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1021
1022    [self sortTorrentsIgnoreSelected]; //actually sort
1023   
1024    //set selected rows if needed
1025    if (selectedTorrents)
1026    {
1027        Torrent * torrent;
1028        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1029        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1030        while ((torrent = [enumerator nextObject]))
1031            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1032       
1033        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1034        [indexSet release];
1035    }
1036}
1037
1038//doesn't remember selected rows
1039- (void) sortTorrentsIgnoreSelected
1040{
1041    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1042                            ascending: YES selector: @selector(caseInsensitiveCompare:)] autorelease],
1043                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1044                                            ascending: YES] autorelease];
1045
1046    NSArray * descriptors;
1047    if ([fSortType isEqualToString: @"Name"])
1048        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1049    else if ([fSortType isEqualToString: @"State"])
1050    {
1051        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1052                                                @"stateSortKey" ascending: NO] autorelease],
1053                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1054                                            @"progressSortKey" ascending: NO] autorelease];
1055       
1056        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
1057                                                            nameDescriptor, orderDescriptor, nil];
1058    }
1059    else if ([fSortType isEqualToString: @"Progress"])
1060    {
1061        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1062                                            @"progressSortKey" ascending: YES] autorelease];
1063       
1064        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
1065    }
1066    else if ([fSortType isEqualToString: @"Date"])
1067    {
1068        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"date" ascending: YES] autorelease];
1069   
1070        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1071    }
1072    else
1073        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1074
1075    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1076    [descriptors release];
1077   
1078    [fTableView reloadData];
1079}
1080
1081- (void) setSort: (id) sender
1082{
1083    //get checked items
1084    NSMenuItem * prevSortItem, * prevSortActionItem;
1085    if ([fSortType isEqualToString: @"Name"])
1086    {
1087        prevSortItem = fNameSortItem;
1088        prevSortActionItem = fNameSortActionItem;
1089    }
1090    else if ([fSortType isEqualToString: @"State"])
1091    {
1092        prevSortItem = fStateSortItem;
1093        prevSortActionItem = fStateSortActionItem;
1094    }
1095    else if ([fSortType isEqualToString: @"Progress"])
1096    {
1097        prevSortItem = fProgressSortItem;
1098        prevSortActionItem = fProgressSortActionItem;
1099    }
1100    else if ([fSortType isEqualToString: @"Date"])
1101    {
1102        prevSortItem = fDateSortItem;
1103        prevSortActionItem = fDateSortActionItem;
1104    }
1105    else
1106    {
1107        prevSortItem = fOrderSortItem;
1108        prevSortActionItem = fOrderSortActionItem;
1109    }
1110   
1111    if (sender != prevSortItem && sender != prevSortActionItem)
1112    {
1113        [fSortType release];
1114       
1115        //get new items to check
1116        NSMenuItem * currentSortItem, * currentSortActionItem;
1117        if (sender == fNameSortItem || sender == fNameSortActionItem)
1118        {
1119            currentSortItem = fNameSortItem;
1120            currentSortActionItem = fNameSortActionItem;
1121            fSortType = [[NSString alloc] initWithString: @"Name"];
1122        }
1123        else if (sender == fStateSortItem || sender == fStateSortActionItem)
1124        {
1125            currentSortItem = fStateSortItem;
1126            currentSortActionItem = fStateSortActionItem;
1127            fSortType = [[NSString alloc] initWithString: @"State"];
1128        }
1129        else if (sender == fProgressSortItem || sender == fProgressSortActionItem)
1130        {
1131            currentSortItem = fProgressSortItem;
1132            currentSortActionItem = fProgressSortActionItem;
1133            fSortType = [[NSString alloc] initWithString: @"Progress"];
1134        }
1135        else if (sender == fDateSortItem || sender == fDateSortActionItem)
1136        {
1137            currentSortItem = fDateSortItem;
1138            currentSortActionItem = fDateSortActionItem;
1139            fSortType = [[NSString alloc] initWithString: @"Date"];
1140        }
1141        else
1142        {
1143            currentSortItem = fOrderSortItem;
1144            currentSortActionItem = fOrderSortActionItem;
1145            fSortType = [[NSString alloc] initWithString: @"Order"];
1146        }
1147   
1148        [prevSortItem setState: NSOffState];
1149        [prevSortActionItem setState: NSOffState];
1150        [currentSortItem setState: NSOnState];
1151        [currentSortActionItem setState: NSOnState];
1152       
1153        [fDefaults setObject: fSortType forKey: @"Sort"];
1154    }
1155
1156    [self sortTorrents];
1157}
1158
1159- (void) applyFilter: (id) sender
1160{
1161    //remember selected rows if needed
1162    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1163                ? [self torrentsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1164
1165    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1166
1167    BOOL filtering = YES;
1168    if ([fFilterType isEqualToString: @"Pause"])
1169    {
1170        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1171        Torrent * torrent;
1172        while ((torrent = [enumerator nextObject]))
1173            if (![torrent isActive])
1174                [tempTorrents addObject: torrent];
1175    }
1176    else if ([fFilterType isEqualToString: @"Seed"])
1177    {
1178        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1179        Torrent * torrent;
1180        while ((torrent = [enumerator nextObject]))
1181            if ([torrent isActive] && [torrent progress] >= 1.0)
1182                [tempTorrents addObject: torrent];
1183    }
1184    else if ([fFilterType isEqualToString: @"Download"])
1185    {
1186        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1187        Torrent * torrent;
1188        while ((torrent = [enumerator nextObject]))
1189            if ([torrent isActive] && [torrent progress] < 1.0)
1190                [tempTorrents addObject: torrent];
1191    }
1192    else
1193    {
1194        filtering = NO;
1195        [tempTorrents setArray: fTorrents];
1196    }
1197   
1198    NSString * searchString = [fSearchFilterField stringValue];
1199    if ([searchString length] > 0)
1200    {
1201        filtering = YES;
1202       
1203        int i;
1204        for (i = [tempTorrents count] - 1; i >= 0; i--)
1205            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1206                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1207                [tempTorrents removeObjectAtIndex: i];
1208    }
1209   
1210    [fDisplayedTorrents setArray: tempTorrents];
1211    [tempTorrents release];
1212   
1213    [self sortTorrentsIgnoreSelected];
1214   
1215    //set selected rows if needed
1216    if (selectedTorrents)
1217    {
1218        Torrent * torrent;
1219        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1220        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1221        unsigned index;
1222        while ((torrent = [enumerator nextObject]))
1223            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1224                [indexSet addIndex: index];
1225       
1226        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1227        [indexSet release];
1228    }
1229   
1230    //set status bar torrent count text
1231    NSMutableString * totalTorrentsString = [NSMutableString stringWithString: @""];
1232    if (filtering)
1233        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1234   
1235    int totalCount = [fTorrents count];
1236    if (totalCount > 1)
1237        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfers", "Status bar transfer count"), totalCount];
1238    else
1239        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfer", "Status bar transfer count"), totalCount];
1240   
1241    [fTotalTorrentsField setStringValue: totalTorrentsString];
1242
1243    [self setWindowSizeToFit];
1244}
1245
1246//resets filter and sorts torrents
1247- (void) setFilter: (id) sender
1248{
1249    BarButton * prevFilterButton;
1250    if ([fFilterType isEqualToString: @"Pause"])
1251        prevFilterButton = fPauseFilterButton;
1252    else if ([fFilterType isEqualToString: @"Seed"])
1253        prevFilterButton = fSeedFilterButton;
1254    else if ([fFilterType isEqualToString: @"Download"])
1255        prevFilterButton = fDownloadFilterButton;
1256    else
1257        prevFilterButton = fNoFilterButton;
1258   
1259    if (sender != prevFilterButton)
1260    {
1261        [prevFilterButton setEnabled: NO];
1262        [sender setEnabled: YES];
1263
1264        [fFilterType release];
1265        if (sender == fDownloadFilterButton)
1266            fFilterType = [[NSString alloc] initWithString: @"Download"];
1267        else if (sender == fPauseFilterButton)
1268            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1269        else if (sender == fSeedFilterButton)
1270            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1271        else
1272            fFilterType = [[NSString alloc] initWithString: @"None"];
1273
1274        [fDefaults setObject: fFilterType forKey: @"Filter"];
1275    }
1276
1277    [self applyFilter: nil];
1278}
1279
1280- (void) switchFilter: (id) sender
1281{
1282    NSButton * button;
1283    if ([fFilterType isEqualToString: @"None"])
1284        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1285    else if ([fFilterType isEqualToString: @"Download"])
1286        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1287    else if ([fFilterType isEqualToString: @"Seed"])
1288        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1289    else if ([fFilterType isEqualToString: @"Pause"])
1290        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1291    else
1292        button = fNoFilterButton;
1293   
1294    [self setFilter: button];
1295}
1296
1297- (void) toggleSpeedLimit: (id) sender
1298{
1299    BOOL setEnabled = ![fDefaults boolForKey: @"SpeedLimit"];
1300    int state = setEnabled ? NSOnState : NSOffState;
1301   
1302    [fDefaults setBool: setEnabled forKey: @"SpeedLimit"];
1303
1304    #warning get rid of
1305    [fSpeedLimitItem setState: state];
1306    [fSpeedLimitDockItem setState: state];
1307   
1308    [fSpeedLimitButton setImage: !setEnabled ? fSpeedLimitNormalImage
1309        : ([NSColor currentControlTint] == NSBlueControlTint ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage)];
1310   
1311    [fPrefsController applySpeedSettings: nil];
1312}
1313
1314- (void) autoSpeedLimitChange: (NSNotification *) notification
1315{
1316    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1317        return;
1318 
1319    int onHour = [fDefaults integerForKey: @"SpeedLimitAutoOnHour"],
1320        offHour = [fDefaults integerForKey: @"SpeedLimitAutoOffHour"];
1321   
1322    //check if should be on if within range
1323    BOOL shouldBeOn;
1324    int hour = [[NSCalendarDate calendarDate] hourOfDay];
1325   
1326    if (onHour == offHour)
1327        shouldBeOn = NO;
1328    else if (onHour < offHour)
1329        shouldBeOn = hour >= onHour && hour < offHour;
1330    else
1331        shouldBeOn = hour < offHour || hour >= onHour;
1332   
1333    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
1334        [self toggleSpeedLimit: nil];
1335}
1336
1337- (void) autoSpeedLimit: (NSTimer *) timer
1338{
1339    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1340        return;
1341
1342    BOOL limited = [fDefaults boolForKey: @"SpeedLimit"];
1343   
1344    //toggle if within first few seconds of hour
1345    NSCalendarDate * currentDate = [NSCalendarDate calendarDate];
1346    if ([currentDate minuteOfHour] == 0 && [currentDate secondOfMinute] < AUTO_SPEED_LIMIT_SECONDS
1347        && [currentDate hourOfDay] == [fDefaults integerForKey: limited
1348                                        ? @"SpeedLimitAutoOffHour" : @"SpeedLimitAutoOnHour"]
1349        && (limited || [fDefaults integerForKey: @"SpeedLimitAutoOnHour"]
1350                                    != [fDefaults integerForKey: @"SpeedLimitAutoOffHour"]))
1351    {
1352        [self toggleSpeedLimit: nil];
1353       
1354        [GrowlApplicationBridge notifyWithTitle: limited
1355                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
1356                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
1357            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
1358            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1359    }
1360}
1361
1362- (void) setLimitGlobalEnabled: (id) sender
1363{
1364    [fPrefsController applySpeedSettings: nil];
1365}
1366
1367- (void) setQuickLimitGlobal: (id) sender
1368{
1369    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
1370    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
1371   
1372    [fPrefsController applySpeedSettings: nil];
1373}
1374
1375- (void) setQuickRatioGlobal: (id) sender
1376{
1377    [fDefaults setBool: YES forKey: @"RatioCheck"];
1378    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
1379}
1380
1381- (void) checkWaitingForStopped: (NSNotification *) notification
1382{
1383    [self checkToStartWaiting: [notification object]];
1384   
1385    [self updateUI: nil];
1386    [self applyFilter: nil];
1387    [self updateTorrentHistory];
1388}
1389
1390- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1391{
1392    //don't try to start a transfer if there should be none waiting
1393    if (![fDefaults boolForKey: @"Queue"])
1394        return;
1395
1396    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1397   
1398    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1399    Torrent * torrent, * torrentToStart = nil;
1400    while ((torrent = [enumerator nextObject]))
1401    {
1402        //ignore the torrent just stopped
1403        if (torrent == finishedTorrent)
1404            continue;
1405   
1406        if ([torrent isActive])
1407        {
1408            if (![torrent isSeeding] && ![torrent isError])
1409            {
1410                desiredActive--;
1411                if (desiredActive <= 0)
1412                    return;
1413            }
1414        }
1415        else
1416        {
1417            //use as next if it is waiting to start and either no previous or order value is lower
1418            if ([torrent waitingToStart] && (!torrentToStart
1419                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1420                torrentToStart = torrent;
1421        }
1422    }
1423   
1424    //since it hasn't returned, the queue amount has not been met
1425    if (torrentToStart)
1426    {
1427        [torrentToStart startTransfer];
1428       
1429        [self updateUI: nil];
1430        [self applyFilter: nil];
1431        [self updateTorrentHistory];
1432    }
1433}
1434
1435- (void) torrentStartSettingChange: (NSNotification *) notification
1436{
1437    [self attemptToStartMultipleAuto: [notification object]];
1438
1439    [self updateUI: nil];
1440    [self applyFilter: nil];
1441    [self updateTorrentHistory];
1442}
1443
1444- (void) globalStartSettingChange: (NSNotification *) notification
1445{
1446    [self attemptToStartMultipleAuto: fTorrents];
1447   
1448    [self updateUI: nil];
1449    [self applyFilter: nil];
1450    [self updateTorrentHistory];
1451}
1452
1453- (void) torrentStoppedForRatio: (NSNotification *) notification
1454{
1455    [self applyFilter: nil];
1456    [fInfoController updateInfoStats];
1457    [fInfoController updateInfoSettings];
1458   
1459    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1460    {
1461        NSSound * sound;
1462        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1463            [sound play];
1464    }
1465   
1466    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1467        description: [[notification object] name]
1468        notificationName: GROWL_SEEDING_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1469}
1470
1471- (void) attemptToStartAuto: (Torrent *) torrent
1472{
1473    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1474}
1475
1476//will try to start, taking into consideration the start preference
1477- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1478{
1479    if (![fDefaults boolForKey: @"Queue"])
1480    {
1481        NSEnumerator * enumerator = [torrents objectEnumerator];
1482        Torrent * torrent;
1483        while ((torrent = [enumerator nextObject]))
1484            if ([torrent waitingToStart])
1485                [torrent startTransfer];
1486       
1487        return;
1488    }
1489   
1490    //determine the number of downloads needed to start
1491    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1492           
1493    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1494    Torrent * torrent;
1495    while ((torrent = [enumerator nextObject]))
1496        if ([torrent isActive] && ![torrent isSeeding] && ![torrent isError])
1497        {
1498            desiredActive--;
1499            if (desiredActive <= 0)
1500                break;
1501        }
1502   
1503    //sort torrents by order value
1504    NSArray * sortedTorrents;
1505    if ([torrents count] > 1 && desiredActive > 0)
1506    {
1507        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1508                                                    @"orderValue" ascending: YES] autorelease];
1509        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1510       
1511        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1512        [descriptors release];
1513    }
1514    else
1515        sortedTorrents = torrents;
1516
1517    enumerator = [sortedTorrents objectEnumerator];
1518    while ((torrent = [enumerator nextObject]))
1519    {
1520        if ([torrent waitingToStart])
1521        {
1522            if ([torrent progress] >= 1.0)
1523                [torrent startTransfer];
1524            else if (desiredActive > 0)
1525            {
1526                [torrent startTransfer];
1527                desiredActive--;
1528            }
1529            else
1530                continue;
1531           
1532            [torrent update];
1533        }
1534    }
1535}
1536
1537-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
1538{
1539    if ([notification isEqualToString: UKFileWatcherWriteNotification])
1540        [self checkAutoImportDirectory];
1541}
1542
1543- (void) changeAutoImport
1544{
1545    [fAutoImportedNames removeAllObjects];
1546    [self checkAutoImportDirectory];
1547}
1548
1549- (void) checkAutoImportDirectory
1550{
1551    if (![fDefaults boolForKey: @"AutoImport"])
1552        return;
1553       
1554    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1555   
1556    NSArray * importedNames;
1557    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
1558        return;
1559   
1560    //only import those that have not been imported yet
1561    NSMutableArray * newNames = [importedNames mutableCopy];
1562    [newNames removeObjectsInArray: fAutoImportedNames];
1563    [fAutoImportedNames setArray: importedNames];
1564   
1565    NSEnumerator * enumerator = [newNames objectEnumerator];
1566    NSString * file;
1567    unsigned oldCount;
1568    while ((file = [enumerator nextObject]))
1569    {
1570        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1571        {
1572            int error;
1573            tr_torrent_t * tempTor = tr_torrentInit(fLib, [[path stringByAppendingPathComponent: file] UTF8String],
1574                                                        0, & error);
1575           
1576            if (tempTor)
1577            {
1578                tr_torrentClose(fLib, tempTor);
1579               
1580                int count = [fTorrents count];
1581                [self openFiles: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1582               
1583                //check if torrent was opened
1584                if ([fTorrents count] > count)
1585                {
1586                    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
1587                        "Growl notification title") description: file
1588                        notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1589                }
1590            }
1591            else if (error != TR_EUNSUPPORTED && error != TR_EDUPLICATE)
1592                [fAutoImportedNames removeObjectIdenticalTo: file]; //failed to import for unknown reason, so try again later
1593            else;
1594        }
1595    }
1596   
1597    [newNames release];
1598}
1599
1600- (int) numberOfRowsInTableView: (NSTableView *) tableview
1601{
1602    return [fDisplayedTorrents count];
1603}
1604
1605- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
1606{
1607    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
1608}
1609
1610- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1611    toPasteboard: (NSPasteboard *) pasteboard
1612{
1613    //only allow reordering of rows if sorting by order with no filter
1614    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1615            && [[fSearchFilterField stringValue] length] == 0)
1616    {
1617        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1618        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1619                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1620        return YES;
1621    }
1622    return NO;
1623}
1624
1625- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1626    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1627{
1628    NSPasteboard * pasteboard = [info draggingPasteboard];
1629    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1630    {
1631        //check if any files to add have "torrent" as an extension
1632        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1633        NSString * file;
1634        while ((file = [enumerator nextObject]))
1635            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1636            {
1637                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1638                return NSDragOperationGeneric;
1639            }
1640    }
1641    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1642    {
1643        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1644        return NSDragOperationGeneric;
1645    }
1646    else
1647        return NSDragOperationNone;
1648}
1649
1650- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1651    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1652{
1653    NSPasteboard * pasteboard = [info draggingPasteboard];
1654    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1655    {
1656        //create an array of files with the "torrent" extension
1657        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1658        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1659        NSString * file;
1660        while ((file = [enumerator nextObject]))
1661            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1662                [filesToOpen addObject: file];
1663   
1664        [self application: NSApp openFiles: filesToOpen];
1665        [filesToOpen release];
1666    }
1667    else
1668    {
1669        //remember selected rows if needed
1670        NSArray * selectedTorrents = nil;
1671        int numSelected = [fTableView numberOfSelectedRows];
1672        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1673            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1674   
1675        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1676                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1677       
1678        //move torrent in array
1679        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1680        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1681       
1682        //determine the insertion index now that transfers to move have been removed
1683        int i, decrease = 0;
1684        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1685            decrease++;
1686       
1687        //insert objects at new location
1688        for (i = 0; i < [movingTorrents count]; i++)
1689            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1690       
1691        [movingTorrents release];
1692       
1693        //redo order values
1694        int low = [indexes firstIndex], high = [indexes lastIndex];
1695        if (newRow < low)
1696            low = newRow;
1697        else if (newRow > high + 1)
1698            high = newRow - 1;
1699        else;
1700       
1701        for (i = low; i <= high; i++)
1702            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1703       
1704        [fTableView reloadData];
1705       
1706        //set selected rows if needed
1707        if (selectedTorrents)
1708        {
1709            Torrent * torrent;
1710            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1711            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1712            while ((torrent = [enumerator nextObject]))
1713                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1714           
1715            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1716            [indexSet release];
1717        }
1718    }
1719   
1720    return YES;
1721}
1722
1723- (void) tableViewSelectionDidChange: (NSNotification *) notification
1724{
1725    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1726}
1727
1728- (void) toggleSmallView: (id) sender
1729{
1730    BOOL makeSmall = [fDefaults boolForKey: @"SmallView"];
1731   
1732    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1733   
1734    //window min height
1735    NSSize contentMinSize = [fWindow contentMinSize],
1736            contentSize = [[fWindow contentView] frame].size;
1737    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1738                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1739    [fWindow setContentMinSize: contentMinSize];
1740   
1741    //resize for larger min height if not set to auto size
1742    if (![fDefaults boolForKey: @"AutoSize"])
1743    {
1744        if (!makeSmall && contentSize.height < contentMinSize.height)
1745        {
1746            NSRect frame = [fWindow frame];
1747            float heightChange = contentMinSize.height - contentSize.height;
1748            frame.size.height += heightChange;
1749            frame.origin.y -= heightChange;
1750           
1751            [fWindow setFrame: frame display: YES];
1752            [fTableView reloadData];
1753        }
1754    }
1755    else
1756        [self setWindowSizeToFit];
1757}
1758
1759- (void) toggleStatusBar: (id) sender
1760{
1761    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1762    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1763}
1764
1765- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1766{
1767    if (show != [fStatusBar isHidden])
1768        return;
1769
1770    if (show)
1771        [fStatusBar setHidden: NO];
1772
1773    NSRect frame = [fWindow frame];
1774    float heightChange = [fStatusBar frame].size.height;
1775    if (!show)
1776        heightChange *= -1;
1777   
1778    //allow bar to show even if not enough room
1779    if (show && ![fDefaults boolForKey: @"AutoSize"])
1780    {
1781        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1782        if (frame.size.height > maxHeight)
1783        {
1784            float change = maxHeight - frame.size.height;
1785            frame.size.height += change;
1786            frame.origin.y -= change;
1787           
1788            [fWindow setFrame: frame display: NO animate: NO];
1789        }
1790    }
1791
1792    frame.size.height += heightChange;
1793    frame.origin.y -= heightChange;
1794   
1795    [self updateUI: nil];
1796   
1797    //set views to not autoresize
1798    unsigned int statsMask = [fStatusBar autoresizingMask];
1799    unsigned int filterMask = [fFilterBar autoresizingMask];
1800    unsigned int scrollMask = [fScrollView autoresizingMask];
1801    [fStatusBar setAutoresizingMask: 0];
1802    [fFilterBar setAutoresizingMask: 0];
1803    [fScrollView setAutoresizingMask: 0];
1804   
1805    [fWindow setFrame: frame display: YES animate: animate];
1806   
1807    //re-enable autoresize
1808    [fStatusBar setAutoresizingMask: statsMask];
1809    [fFilterBar setAutoresizingMask: filterMask];
1810    [fScrollView setAutoresizingMask: scrollMask];
1811   
1812    //change min size
1813    NSSize minSize = [fWindow contentMinSize];
1814    minSize.height += heightChange;
1815    [fWindow setContentMinSize: minSize];
1816   
1817    if (!show)
1818        [fStatusBar setHidden: YES];
1819}
1820
1821- (void) toggleFilterBar: (id) sender
1822{
1823    //disable filtering when hiding
1824    if (![fFilterBar isHidden])
1825    {
1826        [fSearchFilterField setStringValue: @""];
1827        [self setFilter: fNoFilterButton];
1828    }
1829
1830    [self showFilterBar: [fFilterBar isHidden] animate: YES];
1831    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
1832}
1833
1834- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1835{
1836    if (show != [fFilterBar isHidden])
1837        return;
1838
1839    if (show)
1840        [fFilterBar setHidden: NO];
1841
1842    NSRect frame = [fWindow frame];
1843    float heightChange = [fFilterBar frame].size.height;
1844    if (!show)
1845        heightChange *= -1;
1846   
1847    //allow bar to show even if not enough room
1848    if (show && ![fDefaults boolForKey: @"AutoSize"])
1849    {
1850        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1851        if (frame.size.height > maxHeight)
1852        {
1853            float change = maxHeight - frame.size.height;
1854            frame.size.height += change;
1855            frame.origin.y -= change;
1856           
1857            [fWindow setFrame: frame display: NO animate: NO];
1858        }
1859    }
1860
1861    frame.size.height += heightChange;
1862    frame.origin.y -= heightChange;
1863   
1864    //set views to not autoresize
1865    unsigned int filterMask = [fFilterBar autoresizingMask];
1866    unsigned int scrollMask = [fScrollView autoresizingMask];
1867    [fFilterBar setAutoresizingMask: 0];
1868    [fScrollView setAutoresizingMask: 0];
1869   
1870    [fWindow setFrame: frame display: YES animate: animate];
1871   
1872    //re-enable autoresize
1873    [fFilterBar setAutoresizingMask: filterMask];
1874    [fScrollView setAutoresizingMask: scrollMask];
1875   
1876    //change min size
1877    NSSize minSize = [fWindow contentMinSize];
1878    minSize.height += heightChange;
1879    [fWindow setContentMinSize: minSize];
1880   
1881    if (!show)
1882    {
1883        [fFilterBar setHidden: YES];
1884        [fWindow makeFirstResponder: fTableView];
1885    }
1886}
1887
1888- (void) toggleAdvancedBar: (id) sender
1889{
1890    [fTableView display];
1891}
1892
1893- (void) doNothing: (id) sender {}
1894
1895- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1896    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1897{
1898    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1899
1900    if ([ident isEqualToString: TOOLBAR_OPEN])
1901    {
1902        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
1903        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
1904        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
1905        [item setImage: [NSImage imageNamed: @"Open.png"]];
1906        [item setTarget: self];
1907        [item setAction: @selector(openShowSheet:)];
1908    }
1909    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1910    {
1911        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
1912        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
1913        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
1914        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1915        [item setTarget: self];
1916        [item setAction: @selector(removeNoDelete:)];
1917    }
1918    else if ([ident isEqualToString: TOOLBAR_INFO])
1919    {
1920        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
1921        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
1922        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
1923        [item setImage: [NSImage imageNamed: @"Info.png"]];
1924        [item setTarget: self];
1925        [item setAction: @selector(showInfo:)];
1926    }
1927    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1928    {
1929        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
1930        [item setPaletteLabel: [item label]];
1931        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
1932        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1933        [item setTarget: self];
1934        [item setAction: @selector(stopAllTorrents:)];
1935    }
1936    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1937    {
1938        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
1939        [item setPaletteLabel: [item label]];
1940        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
1941        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1942        [item setTarget: self];
1943        [item setAction: @selector(resumeAllTorrents:)];
1944    }
1945    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1946    {
1947        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
1948        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
1949        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
1950        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1951        [item setTarget: self];
1952        [item setAction: @selector(stopSelectedTorrents:)];
1953    }
1954    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1955    {
1956        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
1957        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
1958        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
1959        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1960        [item setTarget: self];
1961        [item setAction: @selector(resumeSelectedTorrents:)];
1962    }
1963    else if ([ident isEqualToString: TOOLBAR_FILTER])
1964    {
1965        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
1966        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
1967        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
1968        [item setImage: [NSImage imageNamed: @"Filter.png"]];
1969        [item setTarget: self];
1970        [item setAction: @selector(toggleFilterBar:)];
1971    }
1972    else
1973    {
1974        [item release];
1975        return nil;
1976    }
1977
1978    return item;
1979}
1980
1981- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1982{
1983    return [NSArray arrayWithObjects:
1984            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1985            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1986            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
1987            NSToolbarSeparatorItemIdentifier,
1988            NSToolbarSpaceItemIdentifier,
1989            NSToolbarFlexibleSpaceItemIdentifier,
1990            NSToolbarCustomizeToolbarItemIdentifier, nil];
1991}
1992
1993- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1994{
1995    return [NSArray arrayWithObjects:
1996            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1997            NSToolbarSeparatorItemIdentifier,
1998            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1999            NSToolbarFlexibleSpaceItemIdentifier,
2000            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2001}
2002
2003- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2004{
2005    NSString * ident = [toolbarItem itemIdentifier];
2006
2007    //enable remove item
2008    if ([ident isEqualToString: TOOLBAR_REMOVE])
2009        return [fTableView numberOfSelectedRows] > 0;
2010
2011    //enable pause all item
2012    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2013    {
2014        Torrent * torrent;
2015        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2016        while ((torrent = [enumerator nextObject]))
2017            if ([torrent isActive] || [torrent waitingToStart])
2018                return YES;
2019        return NO;
2020    }
2021
2022    //enable resume all item
2023    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2024    {
2025        Torrent * torrent;
2026        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2027        while ((torrent = [enumerator nextObject]))
2028            if ([torrent isPaused] && ![torrent waitingToStart])
2029                return YES;
2030        return NO;
2031    }
2032
2033    //enable pause item
2034    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2035    {
2036        Torrent * torrent;
2037        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2038        unsigned int i;
2039       
2040        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2041        {
2042            torrent = [fDisplayedTorrents objectAtIndex: i];
2043            if ([torrent isActive] || [torrent waitingToStart])
2044                return YES;
2045        }
2046        return NO;
2047    }
2048   
2049    //enable resume item
2050    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2051    {
2052        Torrent * torrent;
2053        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2054        unsigned int i;
2055       
2056        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2057        {
2058            torrent = [fDisplayedTorrents objectAtIndex: i];
2059            if ([torrent isPaused] && ![torrent waitingToStart])
2060                return YES;
2061        }
2062        return NO;
2063    }
2064
2065    return YES;
2066}
2067
2068- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2069{
2070    SEL action = [menuItem action];
2071
2072    //only enable some items if it is in a context menu or the window is useable
2073    BOOL canUseTable = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
2074
2075    //enable open items
2076    if (action == @selector(openShowSheet:))
2077        return [fWindow attachedSheet] == nil;
2078   
2079    //enable sort and advanced bar items
2080    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2081        return [fWindow isVisible];
2082
2083    //enable show info
2084    if (action == @selector(showInfo:))
2085    {
2086        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector",
2087                            "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2088        if (![[menuItem title] isEqualToString: title])
2089                [menuItem setTitle: title];
2090
2091        return YES;
2092    }
2093   
2094    //enable prev/next inspector tab
2095    if (action == @selector(setInfoTab:))
2096        return [[fInfoController window] isVisible];
2097   
2098    //enable toggle status bar
2099    if (action == @selector(toggleStatusBar:))
2100    {
2101        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2102                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2103        if (![[menuItem title] isEqualToString: title])
2104            [menuItem setTitle: title];
2105
2106        return [fWindow isVisible];
2107    }
2108   
2109    //enable toggle filter bar
2110    if (action == @selector(toggleFilterBar:))
2111    {
2112        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2113                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2114        if (![[menuItem title] isEqualToString: title])
2115            [menuItem setTitle: title];
2116
2117        return [fWindow isVisible];
2118    }
2119   
2120    //enable prev/next filter button
2121    if (action == @selector(switchFilter:))
2122        return [fWindow isVisible] && ![fFilterBar isHidden];
2123
2124    //enable reveal in finder
2125    if (action == @selector(revealFile:))
2126        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2127
2128    //enable remove items
2129    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2130        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2131    {
2132        BOOL warning = NO,
2133            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2134            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2135        Torrent * torrent;
2136        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2137        unsigned int i;
2138       
2139        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2140        {
2141            torrent = [fDisplayedTorrents objectAtIndex: i];
2142            if (!warning && [torrent isActive])
2143            {
2144                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2145                if (warning && canDelete)
2146                    break;
2147            }
2148            if (!canDelete && [torrent publicTorrent])
2149            {
2150                canDelete = YES;
2151                if (warning)
2152                    break;
2153            }
2154        }
2155   
2156        //append or remove ellipsis when needed
2157        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2158        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2159        {
2160            if (![title hasSuffix: ellipsis])
2161                [menuItem setTitle: [title stringByAppendingEllipsis]];
2162        }
2163        else
2164        {
2165            if ([title hasSuffix: ellipsis])
2166                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2167        }
2168       
2169        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2170    }
2171
2172    //enable pause all item
2173    if (action == @selector(stopAllTorrents:))
2174    {
2175        Torrent * torrent;
2176        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2177        while ((torrent = [enumerator nextObject]))
2178            if ([torrent isActive] || [torrent waitingToStart])
2179                return YES;
2180        return NO;
2181    }
2182   
2183    //enable resume all item
2184    if (action == @selector(resumeAllTorrents:))
2185    {
2186        Torrent * torrent;
2187        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2188        while ((torrent = [enumerator nextObject]))
2189            if ([torrent isPaused] && ![torrent waitingToStart])
2190                return YES;
2191        return NO;
2192    }
2193   
2194    //enable resume all waiting item
2195    if (action == @selector(resumeWaitingTorrents:))
2196    {
2197        if (![fDefaults boolForKey: @"Queue"])
2198            return NO;
2199   
2200        Torrent * torrent;
2201        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2202        while ((torrent = [enumerator nextObject]))
2203            if ([torrent waitingToStart])
2204                return YES;
2205        return NO;
2206    }
2207   
2208    //enable resume selected waiting item
2209    if (action == @selector(resumeSelectedTorrentsNoWait:))
2210    {
2211        if (![fDefaults boolForKey: @"Queue"])
2212            return NO;
2213   
2214        Torrent * torrent;
2215        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2216        unsigned int i;
2217       
2218        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2219        {
2220            torrent = [fDisplayedTorrents objectAtIndex: i];
2221            if ([torrent isPaused] && [torrent progress] < 1.0)
2222                return YES;
2223        }
2224        return NO;
2225    }
2226
2227    //enable pause item
2228    if (action == @selector(stopSelectedTorrents:))
2229    {
2230        if (!canUseTable)
2231            return NO;
2232   
2233        Torrent * torrent;
2234        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2235        unsigned int i;
2236       
2237        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2238        {
2239            torrent = [fDisplayedTorrents objectAtIndex: i];
2240            if ([torrent isActive] || [torrent waitingToStart])
2241                return YES;
2242        }
2243        return NO;
2244    }
2245   
2246    //enable resume item
2247    if (action == @selector(resumeSelectedTorrents:))
2248    {
2249        if (!canUseTable)
2250            return NO;
2251   
2252        Torrent * torrent;
2253        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2254        unsigned int i;
2255       
2256        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2257        {
2258            torrent = [fDisplayedTorrents objectAtIndex: i];
2259            if ([torrent isPaused] && ![torrent waitingToStart])
2260                return YES;
2261        }
2262        return NO;
2263    }
2264   
2265    //enable copy torrent file item
2266    if (action == @selector(copyTorrentFile:))
2267        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2268
2269    return YES;
2270}
2271
2272- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2273{
2274    NSEnumerator * enumerator;
2275    Torrent * torrent;
2276    BOOL active;
2277
2278    switch (messageType)
2279    {
2280        case kIOMessageSystemWillSleep:
2281            //close all connections before going to sleep and remember we should resume when we wake up
2282            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2283
2284            //wait for running transfers to stop (5 second timeout)
2285            NSDate * start = [NSDate date];
2286            BOOL timeUp = NO;
2287           
2288            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2289            Torrent * torrent;
2290            while (!timeUp && (torrent = [enumerator nextObject]))
2291                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2292                {
2293                    usleep(100000);
2294                    [torrent update];
2295                }
2296
2297            IOAllowPowerChange(fRootPort, (long) messageArgument);
2298            break;
2299
2300        case kIOMessageCanSystemSleep:
2301            //pevent idle sleep unless all paused
2302            active = NO;
2303            enumerator = [fTorrents objectEnumerator];
2304            while ((torrent = [enumerator nextObject]))
2305                if ([torrent isActive])
2306                {
2307                    active = YES;
2308                    break;
2309                }
2310
2311            if (active)
2312                IOCancelPowerChange(fRootPort, (long) messageArgument);
2313            else
2314                IOAllowPowerChange(fRootPort, (long) messageArgument);
2315            break;
2316
2317        case kIOMessageSystemHasPoweredOn:
2318            //resume sleeping transfers after we wake up
2319            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2320            break;
2321    }
2322}
2323
2324- (void) resetDockBadge: (NSNotification *) notification
2325{
2326    float downloadRate, uploadRate;
2327    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2328   
2329    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2330}
2331
2332- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2333{
2334    //if auto size is enabled, the current frame shouldn't need to change
2335    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2336   
2337    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2338    return frame;
2339}
2340
2341- (void) setWindowSizeToFit
2342{
2343    if ([fDefaults boolForKey: @"AutoSize"])
2344    {
2345        [fScrollView setHasVerticalScroller: NO];
2346        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2347        [fScrollView setHasVerticalScroller: YES];
2348    }
2349}
2350
2351- (NSRect) sizedWindowFrame
2352{
2353    NSRect frame = [fWindow frame];
2354    float newHeight = frame.size.height - [fScrollView frame].size.height
2355        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2356
2357    float minHeight = [fWindow minSize].height;
2358    if (newHeight < minHeight)
2359        newHeight = minHeight;
2360    else
2361    {
2362        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2363        if ([fStatusBar isHidden])
2364            maxHeight -= [fStatusBar frame].size.height;
2365        if ([fFilterBar isHidden])
2366            maxHeight -= [fFilterBar frame].size.height;
2367       
2368        if (newHeight > maxHeight)
2369            newHeight = maxHeight;
2370    }
2371
2372    frame.origin.y -= (newHeight - frame.size.height);
2373    frame.size.height = newHeight;
2374    return frame;
2375}
2376
2377- (void) showMainWindow: (id) sender
2378{
2379    [fWindow makeKeyAndOrderFront: nil];
2380}
2381
2382- (void) windowDidBecomeKey: (NSNotification *) notification
2383{
2384    //reset dock badge for completed
2385    if (fCompleted > 0)
2386    {
2387        fCompleted = 0;
2388        [self resetDockBadge: nil];
2389    }
2390}
2391
2392- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2393{
2394    //only resize horizontally if autosize is enabled
2395    if ([fDefaults boolForKey: @"AutoSize"])
2396        proposedFrameSize.height = [fWindow frame].size.height;
2397    return proposedFrameSize;
2398}
2399
2400- (void) windowDidResize: (NSNotification *) notification
2401{
2402    //hide search filter if it overlaps filter buttons
2403    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2404}
2405
2406- (void) linkHomepage: (id) sender
2407{
2408    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2409}
2410
2411- (void) linkForums: (id) sender
2412{
2413    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2414}
2415
2416- (void) prepareForUpdate: (NSNotification *) notification
2417{
2418    fUpdateInProgress = YES;
2419}
2420
2421- (NSDictionary *) registrationDictionaryForGrowl
2422{
2423    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2424                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2425    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2426                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2427}
2428
2429@end
Note: See TracBrowser for help on using the repository browser.