source: trunk/macosx/Controller.m @ 1043

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

get rid of a variable

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