source: trunk/macosx/Controller.m @ 1045

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

better auto importing of incomplete files

  • Property svn:keywords set to Date Rev Author Id
File size: 85.9 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 1045 2006-10-31 19:29:38Z 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            oldCount = [fTorrents count];
1573            [self openFiles: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1574           
1575            //import only actually happened if the torrent array is larger
1576            if (oldCount < [fTorrents count])
1577            {
1578                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
1579                    "Growl notification title") description: file
1580                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1581            }
1582            else
1583                [fAutoImportedNames removeObjectIdenticalTo: file]; //failed to import, possibly because not fully downloaded
1584        }
1585    }
1586   
1587    [newNames release];
1588}
1589
1590- (int) numberOfRowsInTableView: (NSTableView *) tableview
1591{
1592    return [fDisplayedTorrents count];
1593}
1594
1595- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
1596{
1597    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
1598}
1599
1600- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1601    toPasteboard: (NSPasteboard *) pasteboard
1602{
1603    //only allow reordering of rows if sorting by order with no filter
1604    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1605            && [[fSearchFilterField stringValue] length] == 0)
1606    {
1607        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1608        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1609                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1610        return YES;
1611    }
1612    return NO;
1613}
1614
1615- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1616    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1617{
1618    NSPasteboard * pasteboard = [info draggingPasteboard];
1619    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1620    {
1621        //check if any files to add have "torrent" as an extension
1622        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1623        NSString * file;
1624        while ((file = [enumerator nextObject]))
1625            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1626            {
1627                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1628                return NSDragOperationGeneric;
1629            }
1630    }
1631    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1632    {
1633        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1634        return NSDragOperationGeneric;
1635    }
1636    else
1637        return NSDragOperationNone;
1638}
1639
1640- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1641    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1642{
1643    NSPasteboard * pasteboard = [info draggingPasteboard];
1644    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1645    {
1646        //create an array of files with the "torrent" extension
1647        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1648        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1649        NSString * file;
1650        while ((file = [enumerator nextObject]))
1651            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1652                [filesToOpen addObject: file];
1653   
1654        [self application: NSApp openFiles: filesToOpen];
1655        [filesToOpen release];
1656    }
1657    else
1658    {
1659        //remember selected rows if needed
1660        NSArray * selectedTorrents = nil;
1661        int numSelected = [fTableView numberOfSelectedRows];
1662        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1663            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1664   
1665        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1666                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1667       
1668        //move torrent in array
1669        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1670        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1671       
1672        //determine the insertion index now that transfers to move have been removed
1673        int i, decrease = 0;
1674        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1675            decrease++;
1676       
1677        //insert objects at new location
1678        for (i = 0; i < [movingTorrents count]; i++)
1679            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1680       
1681        [movingTorrents release];
1682       
1683        //redo order values
1684        int low = [indexes firstIndex], high = [indexes lastIndex];
1685        if (newRow < low)
1686            low = newRow;
1687        else if (newRow > high + 1)
1688            high = newRow - 1;
1689        else;
1690       
1691        for (i = low; i <= high; i++)
1692            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1693       
1694        [fTableView reloadData];
1695       
1696        //set selected rows if needed
1697        if (selectedTorrents)
1698        {
1699            Torrent * torrent;
1700            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1701            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1702            while ((torrent = [enumerator nextObject]))
1703                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1704           
1705            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1706            [indexSet release];
1707        }
1708    }
1709   
1710    return YES;
1711}
1712
1713- (void) tableViewSelectionDidChange: (NSNotification *) notification
1714{
1715    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1716}
1717
1718- (void) toggleSmallView: (id) sender
1719{
1720    BOOL makeSmall = [fDefaults boolForKey: @"SmallView"];
1721   
1722    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1723   
1724    //window min height
1725    NSSize contentMinSize = [fWindow contentMinSize],
1726            contentSize = [[fWindow contentView] frame].size;
1727    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1728                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1729    [fWindow setContentMinSize: contentMinSize];
1730   
1731    //resize for larger min height if not set to auto size
1732    if (![fDefaults boolForKey: @"AutoSize"])
1733    {
1734        if (!makeSmall && contentSize.height < contentMinSize.height)
1735        {
1736            NSRect frame = [fWindow frame];
1737            float heightChange = contentMinSize.height - contentSize.height;
1738            frame.size.height += heightChange;
1739            frame.origin.y -= heightChange;
1740           
1741            [fWindow setFrame: frame display: YES];
1742            [fTableView reloadData];
1743        }
1744    }
1745    else
1746        [self setWindowSizeToFit];
1747}
1748
1749- (void) toggleStatusBar: (id) sender
1750{
1751    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1752    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1753}
1754
1755- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1756{
1757    if (show != [fStatusBar isHidden])
1758        return;
1759
1760    if (show)
1761        [fStatusBar setHidden: NO];
1762
1763    NSRect frame = [fWindow frame];
1764    float heightChange = [fStatusBar frame].size.height;
1765    if (!show)
1766        heightChange *= -1;
1767   
1768    //allow bar to show even if not enough room
1769    if (show && ![fDefaults boolForKey: @"AutoSize"])
1770    {
1771        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1772        if (frame.size.height > maxHeight)
1773        {
1774            float change = maxHeight - frame.size.height;
1775            frame.size.height += change;
1776            frame.origin.y -= change;
1777           
1778            [fWindow setFrame: frame display: NO animate: NO];
1779        }
1780    }
1781
1782    frame.size.height += heightChange;
1783    frame.origin.y -= heightChange;
1784   
1785    [self updateUI: nil];
1786   
1787    //set views to not autoresize
1788    unsigned int statsMask = [fStatusBar autoresizingMask];
1789    unsigned int filterMask = [fFilterBar autoresizingMask];
1790    unsigned int scrollMask = [fScrollView autoresizingMask];
1791    [fStatusBar setAutoresizingMask: 0];
1792    [fFilterBar setAutoresizingMask: 0];
1793    [fScrollView setAutoresizingMask: 0];
1794   
1795    [fWindow setFrame: frame display: YES animate: animate];
1796   
1797    //re-enable autoresize
1798    [fStatusBar setAutoresizingMask: statsMask];
1799    [fFilterBar setAutoresizingMask: filterMask];
1800    [fScrollView setAutoresizingMask: scrollMask];
1801   
1802    //change min size
1803    NSSize minSize = [fWindow contentMinSize];
1804    minSize.height += heightChange;
1805    [fWindow setContentMinSize: minSize];
1806   
1807    if (!show)
1808        [fStatusBar setHidden: YES];
1809}
1810
1811- (void) toggleFilterBar: (id) sender
1812{
1813    //disable filtering when hiding
1814    if (![fFilterBar isHidden])
1815    {
1816        [fSearchFilterField setStringValue: @""];
1817        [self setFilter: fNoFilterButton];
1818    }
1819
1820    [self showFilterBar: [fFilterBar isHidden] animate: YES];
1821    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
1822}
1823
1824- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1825{
1826    if (show != [fFilterBar isHidden])
1827        return;
1828
1829    if (show)
1830        [fFilterBar setHidden: NO];
1831
1832    NSRect frame = [fWindow frame];
1833    float heightChange = [fFilterBar frame].size.height;
1834    if (!show)
1835        heightChange *= -1;
1836   
1837    //allow bar to show even if not enough room
1838    if (show && ![fDefaults boolForKey: @"AutoSize"])
1839    {
1840        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1841        if (frame.size.height > maxHeight)
1842        {
1843            float change = maxHeight - frame.size.height;
1844            frame.size.height += change;
1845            frame.origin.y -= change;
1846           
1847            [fWindow setFrame: frame display: NO animate: NO];
1848        }
1849    }
1850
1851    frame.size.height += heightChange;
1852    frame.origin.y -= heightChange;
1853   
1854    //set views to not autoresize
1855    unsigned int filterMask = [fFilterBar autoresizingMask];
1856    unsigned int scrollMask = [fScrollView autoresizingMask];
1857    [fFilterBar setAutoresizingMask: 0];
1858    [fScrollView setAutoresizingMask: 0];
1859   
1860    [fWindow setFrame: frame display: YES animate: animate];
1861   
1862    //re-enable autoresize
1863    [fFilterBar setAutoresizingMask: filterMask];
1864    [fScrollView setAutoresizingMask: scrollMask];
1865   
1866    //change min size
1867    NSSize minSize = [fWindow contentMinSize];
1868    minSize.height += heightChange;
1869    [fWindow setContentMinSize: minSize];
1870   
1871    if (!show)
1872    {
1873        [fFilterBar setHidden: YES];
1874        [fWindow makeFirstResponder: fTableView];
1875    }
1876}
1877
1878- (void) toggleAdvancedBar: (id) sender
1879{
1880    [fTableView display];
1881}
1882
1883- (void) doNothing: (id) sender {}
1884
1885- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1886    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1887{
1888    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1889
1890    if ([ident isEqualToString: TOOLBAR_OPEN])
1891    {
1892        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
1893        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
1894        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
1895        [item setImage: [NSImage imageNamed: @"Open.png"]];
1896        [item setTarget: self];
1897        [item setAction: @selector(openShowSheet:)];
1898    }
1899    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1900    {
1901        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
1902        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
1903        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
1904        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1905        [item setTarget: self];
1906        [item setAction: @selector(removeNoDelete:)];
1907    }
1908    else if ([ident isEqualToString: TOOLBAR_INFO])
1909    {
1910        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
1911        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
1912        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
1913        [item setImage: [NSImage imageNamed: @"Info.png"]];
1914        [item setTarget: self];
1915        [item setAction: @selector(showInfo:)];
1916    }
1917    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1918    {
1919        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
1920        [item setPaletteLabel: [item label]];
1921        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
1922        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1923        [item setTarget: self];
1924        [item setAction: @selector(stopAllTorrents:)];
1925    }
1926    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1927    {
1928        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
1929        [item setPaletteLabel: [item label]];
1930        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
1931        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1932        [item setTarget: self];
1933        [item setAction: @selector(resumeAllTorrents:)];
1934    }
1935    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1936    {
1937        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
1938        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
1939        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
1940        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1941        [item setTarget: self];
1942        [item setAction: @selector(stopSelectedTorrents:)];
1943    }
1944    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1945    {
1946        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
1947        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
1948        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
1949        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1950        [item setTarget: self];
1951        [item setAction: @selector(resumeSelectedTorrents:)];
1952    }
1953    else if ([ident isEqualToString: TOOLBAR_FILTER])
1954    {
1955        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
1956        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
1957        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
1958        [item setImage: [NSImage imageNamed: @"Filter.png"]];
1959        [item setTarget: self];
1960        [item setAction: @selector(toggleFilterBar:)];
1961    }
1962    else
1963    {
1964        [item release];
1965        return nil;
1966    }
1967
1968    return item;
1969}
1970
1971- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1972{
1973    return [NSArray arrayWithObjects:
1974            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1975            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1976            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
1977            NSToolbarSeparatorItemIdentifier,
1978            NSToolbarSpaceItemIdentifier,
1979            NSToolbarFlexibleSpaceItemIdentifier,
1980            NSToolbarCustomizeToolbarItemIdentifier, nil];
1981}
1982
1983- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1984{
1985    return [NSArray arrayWithObjects:
1986            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1987            NSToolbarSeparatorItemIdentifier,
1988            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1989            NSToolbarFlexibleSpaceItemIdentifier,
1990            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
1991}
1992
1993- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1994{
1995    NSString * ident = [toolbarItem itemIdentifier];
1996
1997    //enable remove item
1998    if ([ident isEqualToString: TOOLBAR_REMOVE])
1999        return [fTableView numberOfSelectedRows] > 0;
2000
2001    //enable pause all item
2002    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2003    {
2004        Torrent * torrent;
2005        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2006        while ((torrent = [enumerator nextObject]))
2007            if ([torrent isActive] || [torrent waitingToStart])
2008                return YES;
2009        return NO;
2010    }
2011
2012    //enable resume all item
2013    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2014    {
2015        Torrent * torrent;
2016        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2017        while ((torrent = [enumerator nextObject]))
2018            if ([torrent isPaused] && ![torrent waitingToStart])
2019                return YES;
2020        return NO;
2021    }
2022
2023    //enable pause item
2024    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2025    {
2026        Torrent * torrent;
2027        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2028        unsigned int i;
2029       
2030        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2031        {
2032            torrent = [fDisplayedTorrents objectAtIndex: i];
2033            if ([torrent isActive] || [torrent waitingToStart])
2034                return YES;
2035        }
2036        return NO;
2037    }
2038   
2039    //enable resume item
2040    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2041    {
2042        Torrent * torrent;
2043        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2044        unsigned int i;
2045       
2046        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2047        {
2048            torrent = [fDisplayedTorrents objectAtIndex: i];
2049            if ([torrent isPaused] && ![torrent waitingToStart])
2050                return YES;
2051        }
2052        return NO;
2053    }
2054
2055    return YES;
2056}
2057
2058- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2059{
2060    SEL action = [menuItem action];
2061
2062    //only enable some items if it is in a context menu or the window is useable
2063    BOOL canUseTable = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
2064
2065    //enable open items
2066    if (action == @selector(openShowSheet:))
2067        return [fWindow attachedSheet] == nil;
2068   
2069    //enable sort and advanced bar items
2070    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2071        return [fWindow isVisible];
2072
2073    //enable show info
2074    if (action == @selector(showInfo:))
2075    {
2076        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector",
2077                            "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2078        if (![[menuItem title] isEqualToString: title])
2079                [menuItem setTitle: title];
2080
2081        return YES;
2082    }
2083   
2084    //enable prev/next inspector tab
2085    if (action == @selector(setInfoTab:))
2086        return [[fInfoController window] isVisible];
2087   
2088    //enable toggle status bar
2089    if (action == @selector(toggleStatusBar:))
2090    {
2091        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2092                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2093        if (![[menuItem title] isEqualToString: title])
2094            [menuItem setTitle: title];
2095
2096        return [fWindow isVisible];
2097    }
2098   
2099    //enable toggle filter bar
2100    if (action == @selector(toggleFilterBar:))
2101    {
2102        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2103                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2104        if (![[menuItem title] isEqualToString: title])
2105            [menuItem setTitle: title];
2106
2107        return [fWindow isVisible];
2108    }
2109   
2110    //enable prev/next filter button
2111    if (action == @selector(switchFilter:))
2112        return [fWindow isVisible] && ![fFilterBar isHidden];
2113
2114    //enable reveal in finder
2115    if (action == @selector(revealFile:))
2116        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2117
2118    //enable remove items
2119    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2120        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2121    {
2122        BOOL warning = NO,
2123            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2124            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2125        Torrent * torrent;
2126        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2127        unsigned int i;
2128       
2129        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2130        {
2131            torrent = [fDisplayedTorrents objectAtIndex: i];
2132            if (!warning && [torrent isActive])
2133            {
2134                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2135                if (warning && canDelete)
2136                    break;
2137            }
2138            if (!canDelete && [torrent publicTorrent])
2139            {
2140                canDelete = YES;
2141                if (warning)
2142                    break;
2143            }
2144        }
2145   
2146        //append or remove ellipsis when needed
2147        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2148        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2149        {
2150            if (![title hasSuffix: ellipsis])
2151                [menuItem setTitle: [title stringByAppendingEllipsis]];
2152        }
2153        else
2154        {
2155            if ([title hasSuffix: ellipsis])
2156                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2157        }
2158       
2159        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2160    }
2161
2162    //enable pause all item
2163    if (action == @selector(stopAllTorrents:))
2164    {
2165        Torrent * torrent;
2166        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2167        while ((torrent = [enumerator nextObject]))
2168            if ([torrent isActive] || [torrent waitingToStart])
2169                return YES;
2170        return NO;
2171    }
2172   
2173    //enable resume all item
2174    if (action == @selector(resumeAllTorrents:))
2175    {
2176        Torrent * torrent;
2177        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2178        while ((torrent = [enumerator nextObject]))
2179            if ([torrent isPaused] && ![torrent waitingToStart])
2180                return YES;
2181        return NO;
2182    }
2183   
2184    //enable resume all waiting item
2185    if (action == @selector(resumeWaitingTorrents:))
2186    {
2187        if (![fDefaults boolForKey: @"Queue"])
2188            return NO;
2189   
2190        Torrent * torrent;
2191        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2192        while ((torrent = [enumerator nextObject]))
2193            if ([torrent waitingToStart])
2194                return YES;
2195        return NO;
2196    }
2197   
2198    //enable resume selected waiting item
2199    if (action == @selector(resumeSelectedTorrentsNoWait:))
2200    {
2201        if (![fDefaults boolForKey: @"Queue"])
2202            return NO;
2203   
2204        Torrent * torrent;
2205        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2206        unsigned int i;
2207       
2208        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2209        {
2210            torrent = [fDisplayedTorrents objectAtIndex: i];
2211            if ([torrent isPaused] && [torrent progress] < 1.0)
2212                return YES;
2213        }
2214        return NO;
2215    }
2216
2217    //enable pause item
2218    if (action == @selector(stopSelectedTorrents:))
2219    {
2220        if (!canUseTable)
2221            return NO;
2222   
2223        Torrent * torrent;
2224        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2225        unsigned int i;
2226       
2227        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2228        {
2229            torrent = [fDisplayedTorrents objectAtIndex: i];
2230            if ([torrent isActive] || [torrent waitingToStart])
2231                return YES;
2232        }
2233        return NO;
2234    }
2235   
2236    //enable resume item
2237    if (action == @selector(resumeSelectedTorrents:))
2238    {
2239        if (!canUseTable)
2240            return NO;
2241   
2242        Torrent * torrent;
2243        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2244        unsigned int i;
2245       
2246        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2247        {
2248            torrent = [fDisplayedTorrents objectAtIndex: i];
2249            if ([torrent isPaused] && ![torrent waitingToStart])
2250                return YES;
2251        }
2252        return NO;
2253    }
2254   
2255    //enable copy torrent file item
2256    if (action == @selector(copyTorrentFile:))
2257        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2258
2259    return YES;
2260}
2261
2262- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2263{
2264    NSEnumerator * enumerator;
2265    Torrent * torrent;
2266    BOOL active;
2267
2268    switch (messageType)
2269    {
2270        case kIOMessageSystemWillSleep:
2271            //close all connections before going to sleep and remember we should resume when we wake up
2272            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2273
2274            //wait for running transfers to stop (5 second timeout)
2275            NSDate * start = [NSDate date];
2276            BOOL timeUp = NO;
2277           
2278            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2279            Torrent * torrent;
2280            while (!timeUp && (torrent = [enumerator nextObject]))
2281                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2282                {
2283                    usleep(100000);
2284                    [torrent update];
2285                }
2286
2287            IOAllowPowerChange(fRootPort, (long) messageArgument);
2288            break;
2289
2290        case kIOMessageCanSystemSleep:
2291            //pevent idle sleep unless all paused
2292            active = NO;
2293            enumerator = [fTorrents objectEnumerator];
2294            while ((torrent = [enumerator nextObject]))
2295                if ([torrent isActive])
2296                {
2297                    active = YES;
2298                    break;
2299                }
2300
2301            if (active)
2302                IOCancelPowerChange(fRootPort, (long) messageArgument);
2303            else
2304                IOAllowPowerChange(fRootPort, (long) messageArgument);
2305            break;
2306
2307        case kIOMessageSystemHasPoweredOn:
2308            //resume sleeping transfers after we wake up
2309            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2310            break;
2311    }
2312}
2313
2314- (void) resetDockBadge: (NSNotification *) notification
2315{
2316    float downloadRate, uploadRate;
2317    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2318   
2319    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2320}
2321
2322- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2323{
2324    //if auto size is enabled, the current frame shouldn't need to change
2325    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2326   
2327    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2328    return frame;
2329}
2330
2331- (void) setWindowSizeToFit
2332{
2333    if ([fDefaults boolForKey: @"AutoSize"])
2334    {
2335        [fScrollView setHasVerticalScroller: NO];
2336        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2337        [fScrollView setHasVerticalScroller: YES];
2338    }
2339}
2340
2341- (NSRect) sizedWindowFrame
2342{
2343    NSRect frame = [fWindow frame];
2344    float newHeight = frame.size.height - [fScrollView frame].size.height
2345        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2346
2347    float minHeight = [fWindow minSize].height;
2348    if (newHeight < minHeight)
2349        newHeight = minHeight;
2350    else
2351    {
2352        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2353        if ([fStatusBar isHidden])
2354            maxHeight -= [fStatusBar frame].size.height;
2355        if ([fFilterBar isHidden])
2356            maxHeight -= [fFilterBar frame].size.height;
2357       
2358        if (newHeight > maxHeight)
2359            newHeight = maxHeight;
2360    }
2361
2362    frame.origin.y -= (newHeight - frame.size.height);
2363    frame.size.height = newHeight;
2364    return frame;
2365}
2366
2367- (void) showMainWindow: (id) sender
2368{
2369    [fWindow makeKeyAndOrderFront: nil];
2370}
2371
2372- (void) windowDidBecomeKey: (NSNotification *) notification
2373{
2374    //reset dock badge for completed
2375    if (fCompleted > 0)
2376    {
2377        fCompleted = 0;
2378        [self resetDockBadge: nil];
2379    }
2380}
2381
2382- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2383{
2384    //only resize horizontally if autosize is enabled
2385    if ([fDefaults boolForKey: @"AutoSize"])
2386        proposedFrameSize.height = [fWindow frame].size.height;
2387    return proposedFrameSize;
2388}
2389
2390- (void) windowDidResize: (NSNotification *) notification
2391{
2392    //hide search filter if it overlaps filter buttons
2393    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2394}
2395
2396- (void) linkHomepage: (id) sender
2397{
2398    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2399}
2400
2401- (void) linkForums: (id) sender
2402{
2403    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2404}
2405
2406- (void) prepareForUpdate: (NSNotification *) notification
2407{
2408    fUpdateInProgress = YES;
2409}
2410
2411- (NSDictionary *) registrationDictionaryForGrowl
2412{
2413    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2414                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2415    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2416                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2417}
2418
2419@end
Note: See TracBrowser for help on using the repository browser.