source: trunk/macosx/Controller.m @ 636

Last change on this file since 636 was 636, checked in by livings124, 16 years ago

Make order of updateUI: and applyFilter: consistent.

  • Property svn:keywords set to Date Rev Author Id
File size: 70.9 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 636 2006-07-17 11:22:50Z 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
33#import <Sparkle/Sparkle.h>
34#import <Growl/GrowlApplicationBridge.h>
35
36#define TOOLBAR_OPEN            @"Toolbar Open"
37#define TOOLBAR_REMOVE          @"Toolbar Remove"
38#define TOOLBAR_INFO            @"Toolbar Info"
39#define TOOLBAR_PAUSE_ALL       @"Toolbar Pause All"
40#define TOOLBAR_RESUME_ALL      @"Toolbar Resume All"
41#define TOOLBAR_PAUSE_SELECTED  @"Toolbar Pause Selected"
42#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected"
43
44#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
45
46#define ROW_HEIGHT_REGULAR 65.0
47#define ROW_HEIGHT_SMALL 40.0
48
49#define WEBSITE_URL @"http://transmission.m0k.org/"
50#define FORUM_URL   @"http://transmission.m0k.org/forum/"
51
52static void sleepCallBack(void * controller, io_service_t y,
53        natural_t messageType, void * messageArgument)
54{
55    Controller * c = controller;
56    [c sleepCallBack: messageType argument: messageArgument];
57}
58
59
60@implementation Controller
61
62- (id) init
63{
64    if ((self = [super init]))
65    {
66        fLib = tr_init();
67       
68        fTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
69        fFilteredTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
70       
71        fDefaults = [NSUserDefaults standardUserDefaults];
72        fInfoController = [[InfoWindowController alloc] initWithWindowNibName: @"InfoWindow"];
73        fPrefsController = [[PrefsController alloc] initWithWindowNibName: @"PrefsWindow"];
74        fBadger = [[Badger alloc] init];
75       
76        [GrowlApplicationBridge setGrowlDelegate: self];
77    }
78    return self;
79}
80
81- (void) dealloc
82{
83    [[NSNotificationCenter defaultCenter] removeObserver: self];
84
85    [fTorrents release];
86    [fFilteredTorrents release];
87   
88    [fToolbar release];
89    [fInfoController release];
90    [fPrefsController release];
91    [fBadger release];
92   
93    [fSortType release];
94    [fFilterType release];
95    [fAutoImportedNames release];
96   
97    tr_close(fLib);
98    [super dealloc];
99}
100
101- (void) awakeFromNib
102{
103    [fPrefsController setPrefs: fLib];
104   
105    [fStatusBar setBackgroundImage: [NSImage imageNamed: @"StatusBorder.png"]];
106    [fFilterBar setBackgroundImage: [NSImage imageNamed: @"FilterBarBackground.png"]];
107   
108    [fWindow setAcceptsMouseMovedEvents: YES]; //ensure filter buttons display correctly
109   
110    [fAdvancedBarItem setState: [fDefaults boolForKey: @"UseAdvancedBar"]];
111
112    fToolbar = [[NSToolbar alloc] initWithIdentifier: @"Transmission Toolbar"];
113    [fToolbar setDelegate: self];
114    [fToolbar setAllowsUserCustomization: YES];
115    [fToolbar setAutosavesConfiguration: YES];
116    [fWindow setToolbar: fToolbar];
117    [fWindow setDelegate: self];
118   
119    [fWindow makeFirstResponder: fTableView];
120   
121    //set table size
122    if ([fDefaults boolForKey: @"SmallView"])
123    {
124        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
125        [fSmallViewItem setState: NSOnState];
126    }
127   
128    //window min height
129    NSSize contentMinSize = [fWindow contentMinSize];
130    contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
131                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
132    [fWindow setContentMinSize: contentMinSize];
133   
134    //set info keyboard shortcuts
135    unichar ch = NSRightArrowFunctionKey;
136    [fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
137    ch = NSLeftArrowFunctionKey;
138    [fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
139   
140    //set up filter bar
141    NSView * contentView = [fWindow contentView];
142   
143    fFilterBarVisible = NO;
144    NSRect filterBarFrame = [fFilterBar frame];
145    filterBarFrame.size.width = [fWindow frame].size.width;
146    [fFilterBar setFrame: filterBarFrame];
147   
148    [contentView addSubview: fFilterBar];
149    [fFilterBar setFrameOrigin: NSMakePoint(0, [contentView frame].origin.y + [contentView frame].size.height)];
150   
151    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
152   
153    //set up status bar
154    fStatusBarVisible = NO;
155    NSRect statusBarFrame = [fStatusBar frame];
156    statusBarFrame.size.width = [fWindow frame].size.width;
157    [fStatusBar setFrame: statusBarFrame];
158   
159    [contentView addSubview: fStatusBar];
160    [fStatusBar setFrameOrigin: NSMakePoint(0, [contentView frame].origin.y + [contentView frame].size.height)];
161    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
162   
163    //set speed limit
164    [self updateControlTint: nil];
165   
166    if ([fDefaults boolForKey: @"SpeedLimit"])
167    {
168        [fSpeedLimitItem setState: NSOnState];
169        [fSpeedLimitDockItem setState: NSOnState];
170        [fSpeedLimitButton setState: NSOnState];
171    }
172   
173    [[fSpeedLimitButton cell] setHighlightsBy: NSNoCellMask];
174
175    [fActionButton setToolTip: @"Shortcuts for changing global settings."];
176    [fSpeedLimitButton setToolTip: @"Speed Limit overrides the total bandwidth limits with its own limits."];
177
178    [fTableView setTorrents: fFilteredTorrents];
179    [[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell: [[TorrentCell alloc] init]];
180
181    [fTableView registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType,
182                                                        TORRENT_TABLE_VIEW_DATA_TYPE, nil]];
183
184    //register for sleep notifications
185    IONotificationPortRef notify;
186    io_object_t iterator;
187    if (fRootPort = IORegisterForSystemPower(self, & notify, sleepCallBack, & iterator))
188        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify),
189                            kCFRunLoopCommonModes);
190    else
191        NSLog(@"Could not IORegisterForSystemPower");
192
193    //load torrents from history
194    Torrent * torrent;
195    NSDictionary * historyItem;
196    NSEnumerator * enumerator = [[fDefaults arrayForKey: @"History"] objectEnumerator];
197    while ((historyItem = [enumerator nextObject]))
198        if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
199        {
200            [fTorrents addObject: torrent];
201            [torrent release];
202        }
203   
204    [self torrentNumberChanged];
205   
206    //set sort
207    fSortType = [[fDefaults stringForKey: @"Sort"] retain];
208   
209    NSMenuItem * currentSortItem;
210    if ([fSortType isEqualToString: @"Name"])
211        currentSortItem = fNameSortItem;
212    else if ([fSortType isEqualToString: @"State"])
213        currentSortItem = fStateSortItem;
214    else if ([fSortType isEqualToString: @"Progress"])
215        currentSortItem = fProgressSortItem;
216    else if ([fSortType isEqualToString: @"Date"])
217        currentSortItem = fDateSortItem;
218    else
219        currentSortItem = fOrderSortItem;
220    [currentSortItem setState: NSOnState];
221   
222    //set filter
223    fFilterType = [[fDefaults stringForKey: @"Filter"] retain];
224
225    [fNoFilterButton setText: @"All"];
226    [fPauseFilterButton setText: @"Paused"];
227    [fSeedFilterButton setText: @"Seeding"];
228    [fDownloadFilterButton setText: @"Downloading"];
229
230    NSMenuItem * currentFilterItem;
231    BarButton * currentFilterButton;
232    if ([fFilterType isEqualToString: @"Pause"])
233        currentFilterButton = fPauseFilterButton;
234    else if ([fFilterType isEqualToString: @"Seed"])
235        currentFilterButton = fSeedFilterButton;
236    else if ([fFilterType isEqualToString: @"Download"])
237        currentFilterButton = fDownloadFilterButton;
238    else
239        currentFilterButton = fNoFilterButton;
240
241    [currentFilterButton setEnabled: YES];
242   
243    //set upload limit action button
244    [fUploadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
245                    [fDefaults integerForKey: @"UploadLimit"]]];
246    if ([fDefaults boolForKey: @"CheckUpload"])
247        [fUploadLimitItem setState: NSOnState];
248    else
249        [fUploadNoLimitItem setState: NSOnState];
250
251        //set download limit action menu
252    [fDownloadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
253                    [fDefaults integerForKey: @"DownloadLimit"]]];
254    if ([fDefaults boolForKey: @"CheckDownload"])
255        [fDownloadLimitItem setState: NSOnState];
256    else
257        [fDownloadNoLimitItem setState: NSOnState];
258   
259    //set ratio action menu
260    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
261                                [fDefaults floatForKey: @"RatioLimit"]]];
262    if ([fDefaults boolForKey: @"RatioCheck"])
263        [fRatioSetItem setState: NSOnState];
264    else
265        [fRatioNotSetItem setState: NSOnState];
266   
267    //observe notifications
268    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
269   
270    [nc addObserver: self selector: @selector(updateControlTint:)
271                    name: NSControlTintDidChangeNotification object: nil];
272   
273    [nc addObserver: self selector: @selector(prepareForUpdate:)
274                    name: SUUpdaterWillRestartNotification object: nil];
275    fUpdateInProgress = NO;
276   
277    [nc addObserver: self selector: @selector(limitGlobalChange:)
278                    name: @"LimitGlobalChange" object: nil];
279   
280    [nc addObserver: self selector: @selector(ratioGlobalChange:)
281                    name: @"RatioGlobalChange" object: nil];
282   
283    //check to start another because of stopped torrent
284    [nc addObserver: self selector: @selector(checkWaitingForStopped:)
285                    name: @"StoppedDownloading" object: nil];
286   
287    //check all torrents for starting
288    [nc addObserver: self selector: @selector(globalStartSettingChange:)
289                    name: @"GlobalStartSettingChange" object: nil];
290
291    //check if torrent should now start
292    [nc addObserver: self selector: @selector(torrentStartSettingChange:)
293                    name: @"TorrentStartSettingChange" object: nil];
294   
295    //check if torrent should now start
296    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
297                    name: @"TorrentStoppedForRatio" object: nil];
298   
299    //change that just impacts the inspector
300    [nc addObserver: self selector: @selector(reloadInspectorSettings:)
301                    name: @"TorrentSettingChange" object: nil];
302   
303    //reset auto import
304    [nc addObserver: self selector: @selector(autoImportChange:)
305                    name: @"AutoImportSettingChange" object: nil];
306
307    //timer to update the interface every second
308    fCompleted = 0;
309    [self updateUI: nil];
310    fTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
311        selector: @selector(updateUI:) userInfo: nil repeats: YES];
312    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
313    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
314   
315    //timer for auto import, will check every 15 seconds
316    fAutoImportedNames = [[NSMutableArray alloc] init];
317   
318    [self checkAutoImportDirectory: nil];
319    fAutoImportTimer = [NSTimer scheduledTimerWithTimeInterval: 15.0 target: self
320        selector: @selector(checkAutoImportDirectory:) userInfo: nil repeats: YES];
321    [[NSRunLoop currentRunLoop] addTimer: fAutoImportTimer forMode: NSDefaultRunLoopMode];
322   
323    [self applyFilter: nil];
324   
325    [fWindow makeKeyAndOrderFront: nil];
326
327    //load info for no torrents
328    [fInfoController updateInfoForTorrents: [NSArray array]];
329    if ([fDefaults boolForKey: @"InfoVisible"])
330        [self showInfo: nil];
331}
332
333- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
334{
335    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
336        [fWindow makeKeyAndOrderFront: nil];
337    return NO;
338}
339
340- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
341{
342    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
343    {
344        int active = 0, downloading = 0;
345        Torrent * torrent;
346        NSEnumerator * enumerator = [fTorrents objectEnumerator];
347        while ((torrent = [enumerator nextObject]))
348            if ([torrent isActive])
349            {
350                active++;
351                if (![torrent isSeeding])
352                    downloading++;
353            }
354
355        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
356        {
357            NSString * message = active == 1
358                ? @"There is an active transfer. Do you really want to quit?"
359                : [NSString stringWithFormat:
360                    @"There are %d active transfers. Do you really want to quit?", active];
361
362            NSBeginAlertSheet(@"Confirm Quit", @"Quit", @"Cancel", nil, fWindow, self,
363                                @selector(quitSheetDidEnd:returnCode:contextInfo:),
364                                nil, nil, message);
365            return NSTerminateLater;
366        }
367    }
368
369    return NSTerminateNow;
370}
371
372- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
373    contextInfo: (void *) contextInfo
374{
375    [NSApp stopModal];
376    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
377}
378
379- (void) applicationWillTerminate: (NSNotification *) notification
380{
381    //stop timers
382    [fAutoImportTimer invalidate];
383    [fTimer invalidate];
384   
385    //save history and stop running torrents
386    [self updateTorrentHistory];
387    [fTorrents makeObjectsPerformSelector: @selector(stopTransferForQuit)];
388   
389    //remember window states and close all windows
390    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
391    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
392    [self showStatusBar: NO animate: NO];
393    [self showFilterBar: NO animate: NO];
394   
395    //clear badge
396    [fBadger clearBadge];
397
398    //end quickly if the app is updating
399    if (fUpdateInProgress)
400        return;
401
402    //wait for running transfers to stop (5 second timeout)
403    NSDate * start = [NSDate date];
404    BOOL timeUp = NO;
405   
406    NSEnumerator * enumerator = [fTorrents objectEnumerator];
407    Torrent * torrent;
408    while (!timeUp && (torrent = [enumerator nextObject]))
409        while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
410        {
411            usleep(100000);
412            [torrent update];
413        }
414}
415
416- (void) folderChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code
417    contextInfo: (Torrent *) torrent
418{
419    if (code == NSOKButton)
420    {
421        [torrent setDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
422        [torrent update];
423        [self attemptToStartAuto: torrent];
424       
425        [fTorrents addObject: torrent];
426       
427        [self torrentNumberChanged];
428    }
429   
430    [NSApp stopModal];
431}
432
433- (void) application: (NSApplication *) sender openFiles: (NSArray *) filenames
434{
435    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"], * torrentPath;
436    Torrent * torrent;
437    NSEnumerator * enumerator = [filenames objectEnumerator];
438    while ((torrentPath = [enumerator nextObject]))
439    {
440        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
441            continue;
442
443        //add it to the "File > Open Recent" menu
444        [[NSDocumentController sharedDocumentController]
445            noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
446
447        if ([downloadChoice isEqualToString: @"Ask"])
448        {
449            NSOpenPanel * panel = [NSOpenPanel openPanel];
450
451            [panel setPrompt: @"Select Download Folder"];
452            [panel setAllowsMultipleSelection: NO];
453            [panel setCanChooseFiles: NO];
454            [panel setCanChooseDirectories: YES];
455
456            [panel setMessage: [NSString stringWithFormat: @"Select the download folder for \"%@\"", [torrent name]]];
457
458            [panel beginSheetForDirectory: nil file: nil types: nil
459                modalForWindow: fWindow modalDelegate: self didEndSelector:
460                @selector( folderChoiceClosed:returnCode:contextInfo: )
461                contextInfo: torrent];
462            [NSApp runModalForWindow: panel];
463        }
464        else
465        {
466            NSString * folder = [downloadChoice isEqualToString: @"Constant"]
467                ? [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]
468                : [torrentPath stringByDeletingLastPathComponent];
469
470            [torrent setDownloadFolder: folder];
471            [torrent update];
472            [self attemptToStartAuto: torrent];
473           
474            [fTorrents addObject: torrent];
475        }
476       
477        [torrent release];
478    }
479
480    [self torrentNumberChanged];
481
482    [self updateUI: nil];
483    [self applyFilter: nil];
484    [self updateTorrentHistory];
485}
486
487- (NSArray *) torrentsAtIndexes: (NSIndexSet *) indexSet
488{
489    if ([fFilteredTorrents respondsToSelector: @selector(objectsAtIndexes:)])
490        return [fFilteredTorrents objectsAtIndexes: indexSet];
491    else
492    {
493        NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [indexSet count]];
494        unsigned int i;
495        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
496            [torrents addObject: [fFilteredTorrents objectAtIndex: i]];
497
498        return torrents;
499    }
500}
501
502- (void) torrentNumberChanged
503{
504    int count = [fTorrents count];
505    [fTotalTorrentsField setStringValue: [NSString stringWithFormat:
506        @"%d Transfer%s", count, count == 1 ? "" : "s"]];
507}
508
509//called on by applescript
510- (void) open: (NSArray *) files
511{
512    [self performSelectorOnMainThread: @selector(openFromSheet:) withObject: files waitUntilDone: NO];
513}
514
515- (void) openShowSheet: (id) sender
516{
517    NSOpenPanel * panel = [NSOpenPanel openPanel];
518
519    [panel setAllowsMultipleSelection: YES];
520    [panel setCanChooseFiles: YES];
521    [panel setCanChooseDirectories: NO];
522
523    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
524        modalForWindow: fWindow modalDelegate: self didEndSelector:
525        @selector(openSheetClosed:returnCode:contextInfo:) contextInfo: nil];
526}
527
528- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code
529    contextInfo: (void *) info
530{
531    if (code == NSOKButton)
532        [self performSelectorOnMainThread: @selector(openFromSheet:)
533                    withObject: [panel filenames] waitUntilDone: NO];
534}
535
536- (void) openFromSheet: (NSArray *) filenames
537{
538    [self application: NSApp openFiles: filenames];
539}
540
541- (void) resumeSelectedTorrents: (id) sender
542{
543    [self resumeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
544}
545
546- (void) resumeAllTorrents: (id) sender
547{
548    [self resumeTorrents: fTorrents];
549}
550
551- (void) resumeTorrents: (NSArray *) torrents;
552{
553    [torrents makeObjectsPerformSelector: @selector(startTransfer)];
554   
555    [self updateUI: nil];
556    [self applyFilter: nil];
557    [fInfoController updateInfoStatsAndSettings];
558    [self updateTorrentHistory];
559}
560
561- (void) stopSelectedTorrents: (id) sender
562{
563    [self stopTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
564}
565
566- (void) stopAllTorrents: (id) sender
567{
568    [self stopTorrents: fTorrents];
569}
570
571- (void) stopTorrents: (NSArray *) torrents;
572{
573    //don't want any of these starting then stopping
574    NSEnumerator * enumerator = [torrents objectEnumerator];
575    Torrent * torrent;
576    while ((torrent = [enumerator nextObject]))
577        [torrent setWaitToStart: NO];
578
579    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
580   
581    [self updateUI: nil];
582    [self applyFilter: nil];
583    [fInfoController updateInfoStatsAndSettings];
584    [self updateTorrentHistory];
585}
586
587- (void) removeTorrents: (NSArray *) torrents
588        deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
589{
590    [torrents retain];
591    int active = 0, downloading = 0;
592
593    if ([fDefaults boolForKey: @"CheckRemove"])
594    {
595        Torrent * torrent;
596        NSEnumerator * enumerator = [torrents objectEnumerator];
597        while ((torrent = [enumerator nextObject]))
598            if ([torrent isActive])
599            {
600                active++;
601                if (![torrent isSeeding])
602                    downloading++;
603            }
604
605        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
606        {
607            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
608                torrents, @"Torrents",
609                [NSNumber numberWithBool: deleteData], @"DeleteData",
610                [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
611
612            NSString * title, * message;
613           
614            int selected = [fTableView numberOfSelectedRows];
615            if (selected == 1)
616            {
617                title = [NSString stringWithFormat: @"Comfirm Removal of \"%@\"",
618                            [[fFilteredTorrents objectAtIndex: [fTableView selectedRow]] name]];
619                message = @"This transfer is active."
620                            " Once removed, continuing the transfer will require the torrent file."
621                            " Do you really want to remove it?";
622            }
623            else
624            {
625                title = [NSString stringWithFormat: @"Comfirm Removal of %d Transfers", selected];
626                if (selected == active)
627                    message = [NSString stringWithFormat:
628                        @"There are %d active transfers.", active];
629                else
630                    message = [NSString stringWithFormat:
631                        @"There are %d transfers (%d active).", selected, active];
632                message = [message stringByAppendingString:
633                    @" Once removed, continuing the transfers will require the torrent files."
634                    " Do you really want to remove them?"];
635            }
636
637            NSBeginAlertSheet(title, @"Remove", @"Cancel", nil, fWindow, self,
638                @selector(removeSheetDidEnd:returnCode:contextInfo:), nil, dict, message);
639            return;
640        }
641    }
642   
643    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
644}
645
646- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (NSDictionary *) dict
647{
648    [NSApp stopModal];
649
650    NSArray * torrents = [dict objectForKey: @"Torrents"];
651    BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue],
652        deleteTorrent = [[dict objectForKey: @"DeleteTorrent"] boolValue];
653    [dict release];
654   
655    if (returnCode == NSAlertDefaultReturn)
656        [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
657    else
658        [torrents release];
659}
660
661- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
662{
663    //don't want any of these starting then stopping
664    NSEnumerator * enumerator = [torrents objectEnumerator];
665    Torrent * torrent;
666    while ((torrent = [enumerator nextObject]))
667        [torrent setWaitToStart: NO];
668
669    NSNumber * lowestOrderValue = [NSNumber numberWithInt: [torrents count]], * currentOrderValue;
670
671    enumerator = [torrents objectEnumerator];
672    while ((torrent = [enumerator nextObject]))
673    {
674        [torrent stopTransfer];
675
676        if (deleteData)
677            [torrent trashData];
678        if (deleteTorrent)
679            [torrent trashTorrent];
680       
681        //determine lowest order value
682        currentOrderValue = [torrent orderValue];
683        if ([lowestOrderValue compare: currentOrderValue] == NSOrderedDescending)
684            lowestOrderValue = currentOrderValue;
685
686        [torrent removeForever];
687       
688        [fFilteredTorrents removeObject: torrent];
689        [fTorrents removeObject: torrent];
690    }
691    [torrents release];
692
693    //reset the order values if necessary
694    if ([lowestOrderValue intValue] < [fTorrents count])
695    {
696        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
697                                                @"orderValue" ascending: YES] autorelease];
698        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
699
700        NSArray * tempTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
701        [descriptors release];
702
703        int i;
704        for (i = [lowestOrderValue intValue]; i < [tempTorrents count]; i++)
705            [[tempTorrents objectAtIndex: i] setOrderValue: i];
706    }
707   
708    [self torrentNumberChanged];
709    [fTableView deselectAll: nil];
710    [self updateUI: nil];
711    [self updateTorrentHistory];
712}
713
714- (void) removeNoDelete: (id) sender
715{
716    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
717                deleteData: NO deleteTorrent: NO];
718}
719
720- (void) removeDeleteData: (id) sender
721{
722    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
723                deleteData: YES deleteTorrent: NO];
724}
725
726- (void) removeDeleteTorrent: (id) sender
727{
728    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
729                deleteData: NO deleteTorrent: YES];
730}
731
732- (void) removeDeleteDataAndTorrent: (id) sender
733{
734    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
735                deleteData: YES deleteTorrent: YES];
736}
737
738- (void) copyTorrentFile: (id) sender
739{
740    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
741            [self torrentsAtIndexes: [fTableView selectedRowIndexes]]]];
742}
743
744- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
745{
746    if ([torrents count] == 0)
747    {
748        [torrents release];
749        return;
750    }
751
752    Torrent * torrent = [torrents objectAtIndex: 0];
753
754    //warn user if torrent file can't be found
755    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
756    {
757        NSAlert * alert = [[NSAlert alloc] init];
758        [alert addButtonWithTitle: @"OK"];
759        [alert setMessageText: [NSString stringWithFormat:
760                @"Copy of \"%@\" Cannot Be Created", [torrent name]]];
761        [alert setInformativeText: [NSString stringWithFormat:
762                @"The torrent file (%@) cannot be found.", [torrent torrentLocation]]];
763        [alert setAlertStyle: NSWarningAlertStyle];
764       
765        [alert runModal];
766       
767        [torrents removeObjectAtIndex: 0];
768        [self copyTorrentFileForTorrents: torrents];
769    }
770    else
771    {
772        NSSavePanel * panel = [NSSavePanel savePanel];
773        [panel setRequiredFileType: @"torrent"];
774        [panel setCanSelectHiddenExtension: YES];
775       
776        [panel beginSheetForDirectory: nil file: [torrent name]
777            modalForWindow: fWindow modalDelegate: self didEndSelector:
778            @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
779    }
780}
781
782- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code
783    contextInfo: (NSMutableArray *) torrents
784{
785    //if save successful, copy torrent to new location with name of data file
786    if (code == NSOKButton)
787        [[NSFileManager defaultManager] copyPath: [[torrents objectAtIndex: 0] torrentLocation]
788                toPath: [panel filename] handler: nil];
789   
790    [torrents removeObjectAtIndex: 0];
791    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:)
792                withObject: torrents waitUntilDone: NO];
793}
794
795- (void) revealFile: (id) sender
796{
797    NSIndexSet * indexSet = [fTableView selectedRowIndexes];
798    unsigned int i;
799   
800    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
801        [[fFilteredTorrents objectAtIndex: i] revealData];
802}
803
804- (void) showPreferenceWindow: (id) sender
805{
806    NSWindow * window = [fPrefsController window];
807    if (![window isVisible])
808        [window center];
809
810    [window makeKeyAndOrderFront: nil];
811}
812
813- (void) showInfo: (id) sender
814{
815    if ([[fInfoController window] isVisible])
816        [fInfoController close];
817    else
818    {
819        [fInfoController updateInfoStats];
820        [[fInfoController window] orderFront: nil];
821    }
822}
823
824- (void) setInfoTab: (id) sender
825{
826    if (sender == fNextInfoTabItem)
827        [fInfoController setNextTab];
828    else
829        [fInfoController setPreviousTab];
830}
831
832- (void) updateControlTint: (NSNotification *) notification
833{
834    [fSpeedLimitButton setAlternateImage: [fDefaults integerForKey: @"AppleAquaColorVariant"] == NSBlueControlTint
835            ? [NSImage imageNamed: @"SpeedLimitButtonPressedBlue.png"]
836            : [NSImage imageNamed: @"SpeedLimitButtonPressedGraphite.png"]];
837}
838
839- (void) updateUI: (NSTimer *) t
840{
841    NSEnumerator * enumerator = [fTorrents objectEnumerator];
842    Torrent * torrent;
843    while ((torrent = [enumerator nextObject]))
844    {
845        [torrent update];
846
847        if ([torrent justFinished])
848        {
849            [self applyFilter: nil];
850            [self checkToStartWaiting: torrent];
851       
852            [GrowlApplicationBridge notifyWithTitle: @"Download Complete"
853                description: [torrent name] notificationName: @"Download Complete" iconData: nil
854                priority: 0 isSticky: NO clickContext: nil];
855
856            if (![fWindow isKeyWindow])
857                fCompleted++;
858        }
859    }
860
861    if ([fSortType isEqualToString: @"Progress"] || [fSortType isEqualToString: @"State"])
862        [self sortTorrents];
863    else
864        [fTableView reloadData];
865   
866    //update the global DL/UL rates
867    float downloadRate, uploadRate;
868    tr_torrentRates(fLib, & downloadRate, & uploadRate);
869    if (fStatusBarVisible)
870    {
871        [fTotalDLField setStringValue: [NSString stringForSpeed: downloadRate]];
872        [fTotalULField setStringValue: [NSString stringForSpeed: uploadRate]];
873    }
874
875    if ([[fInfoController window] isVisible])
876        [fInfoController updateInfoStats];
877
878    //badge dock
879    [fBadger updateBadgeWithCompleted: fCompleted
880        uploadRate: uploadRate downloadRate: downloadRate];
881}
882
883- (void) updateTorrentHistory
884{
885    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
886
887    NSEnumerator * enumerator = [fTorrents objectEnumerator];
888    Torrent * torrent;
889    while ((torrent = [enumerator nextObject]))
890        [history addObject: [torrent history]];
891
892    [fDefaults setObject: history forKey: @"History"];
893    [fDefaults synchronize];
894}
895
896- (void) sortTorrents
897{
898    //remember selected rows if needed
899    NSArray * selectedTorrents = nil;
900    int numSelected = [fTableView numberOfSelectedRows];
901    if (numSelected > 0 && numSelected < [fFilteredTorrents count])
902        selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
903
904    [self sortTorrentsIgnoreSelected]; //actually sort
905   
906    //set selected rows if needed
907    if (selectedTorrents)
908    {
909        Torrent * torrent;
910        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
911        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
912        while ((torrent = [enumerator nextObject]))
913            [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
914       
915        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
916        [indexSet release];
917    }
918}
919
920//doesn't remember selected rows
921- (void) sortTorrentsIgnoreSelected
922{
923    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:
924                                            @"name" ascending: YES] autorelease],
925                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
926                                            @"orderValue" ascending: YES] autorelease];
927
928    NSArray * descriptors;
929    if ([fSortType isEqualToString: @"Name"])
930        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
931    else if ([fSortType isEqualToString: @"State"])
932    {
933        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
934                                                @"stateSortKey" ascending: NO] autorelease],
935                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
936                                            @"progressSortKey" ascending: NO] autorelease];
937       
938        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
939                                                            nameDescriptor, orderDescriptor, nil];
940    }
941    else if ([fSortType isEqualToString: @"Progress"])
942    {
943        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
944                                            @"progressSortKey" ascending: YES] autorelease];
945       
946        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
947    }
948    else if ([fSortType isEqualToString: @"Date"])
949    {
950        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
951                                            @"date" ascending: YES] autorelease];
952   
953        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
954    }
955    else
956        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
957
958    [fFilteredTorrents sortUsingDescriptors: descriptors];
959    [descriptors release];
960   
961    [fTableView reloadData];
962}
963
964- (void) setSort: (id) sender
965{
966    NSMenuItem * prevSortItem;
967    if ([fSortType isEqualToString: @"Name"])
968        prevSortItem = fNameSortItem;
969    else if ([fSortType isEqualToString: @"State"])
970        prevSortItem = fStateSortItem;
971    else if ([fSortType isEqualToString: @"Progress"])
972        prevSortItem = fProgressSortItem;
973    else if ([fSortType isEqualToString: @"Date"])
974        prevSortItem = fDateSortItem;
975    else
976        prevSortItem = fOrderSortItem;
977   
978    if (sender != prevSortItem)
979    {
980        [prevSortItem setState: NSOffState];
981        [sender setState: NSOnState];
982
983        [fSortType release];
984        if (sender == fNameSortItem)
985            fSortType = [[NSString alloc] initWithString: @"Name"];
986        else if (sender == fStateSortItem)
987            fSortType = [[NSString alloc] initWithString: @"State"];
988        else if (sender == fProgressSortItem)
989            fSortType = [[NSString alloc] initWithString: @"Progress"];
990        else if (sender == fDateSortItem)
991            fSortType = [[NSString alloc] initWithString: @"Date"];
992        else
993            fSortType = [[NSString alloc] initWithString: @"Order"];
994           
995        [fDefaults setObject: fSortType forKey: @"Sort"];
996    }
997
998    [self sortTorrents];
999}
1000
1001- (void) applyFilter: (id) sender
1002{
1003    //remember selected rows if needed
1004    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1005                ? [self torrentsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1006
1007    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1008
1009    if ([fFilterType isEqualToString: @"Pause"])
1010    {
1011        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1012        Torrent * torrent;
1013        while ((torrent = [enumerator nextObject]))
1014            if (![torrent isActive])
1015                [tempTorrents addObject: torrent];
1016    }
1017    else if ([fFilterType isEqualToString: @"Seed"])
1018    {
1019        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1020        Torrent * torrent;
1021        while ((torrent = [enumerator nextObject]))
1022            if ([torrent isActive] && [torrent progress] >= 1.0)
1023                [tempTorrents addObject: torrent];
1024    }
1025    else if ([fFilterType isEqualToString: @"Download"])
1026    {
1027        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1028        Torrent * torrent;
1029        while ((torrent = [enumerator nextObject]))
1030            if ([torrent isActive] && [torrent progress] < 1.0)
1031                [tempTorrents addObject: torrent];
1032    }
1033    else
1034        [tempTorrents setArray: fTorrents];
1035   
1036    NSString * searchString = [fSearchFilterField stringValue];
1037    if (![searchString isEqualToString: @""])
1038    {
1039        int i;
1040        for (i = [tempTorrents count] - 1; i >= 0; i--)
1041            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1042                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1043                [tempTorrents removeObjectAtIndex: i];
1044    }
1045   
1046    [fFilteredTorrents setArray: tempTorrents];
1047    [tempTorrents release];
1048   
1049    [self sortTorrentsIgnoreSelected];
1050   
1051    //set selected rows if needed
1052    if (selectedTorrents)
1053    {
1054        Torrent * torrent;
1055        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1056        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1057        unsigned index;
1058        while ((torrent = [enumerator nextObject]))
1059            if ((index = [fFilteredTorrents indexOfObject: torrent]) != NSNotFound)
1060                [indexSet addIndex: index];
1061       
1062        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1063        [indexSet release];
1064    }
1065}
1066
1067//resets filter and sorts torrents
1068- (void) setFilter: (id) sender
1069{
1070    BarButton * prevFilterButton;
1071    if ([fFilterType isEqualToString: @"Pause"])
1072        prevFilterButton = fPauseFilterButton;
1073    else if ([fFilterType isEqualToString: @"Seed"])
1074        prevFilterButton = fSeedFilterButton;
1075    else if ([fFilterType isEqualToString: @"Download"])
1076        prevFilterButton = fDownloadFilterButton;
1077    else
1078        prevFilterButton = fNoFilterButton;
1079   
1080    if (sender != prevFilterButton)
1081    {
1082        [prevFilterButton setEnabled: NO];
1083        [sender setEnabled: YES];
1084
1085        [fFilterType release];
1086        if (sender == fDownloadFilterButton)
1087            fFilterType = [[NSString alloc] initWithString: @"Download"];
1088        else if (sender == fPauseFilterButton)
1089            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1090        else if (sender == fSeedFilterButton)
1091            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1092        else
1093            fFilterType = [[NSString alloc] initWithString: @"None"];
1094
1095        [fDefaults setObject: fFilterType forKey: @"Filter"];
1096    }
1097
1098    [self applyFilter: nil];
1099}
1100
1101- (void) toggleSpeedLimit: (id) sender
1102{
1103    int state = [fSpeedLimitItem state] ? NSOffState : NSOnState;
1104
1105    [fSpeedLimitItem setState: state];
1106    [fSpeedLimitDockItem setState: state];
1107    [fSpeedLimitButton setState: state];
1108   
1109    [fPrefsController enableSpeedLimit: state];
1110}
1111
1112- (void) setLimitGlobalEnabled: (id) sender
1113{
1114    [fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
1115        type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem) ? @"Upload" : @"Download"];
1116}
1117
1118- (void) setQuickLimitGlobal: (id) sender
1119{
1120    [fPrefsController setQuickLimit: [[sender title] intValue]
1121        type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
1122}
1123
1124- (void) limitGlobalChange: (NSNotification *) notification
1125{
1126    NSDictionary * dict = [notification object];
1127   
1128    NSMenuItem * limitItem, * noLimitItem;
1129    if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
1130    {
1131        limitItem = fUploadLimitItem;
1132        noLimitItem = fUploadNoLimitItem;
1133    }
1134    else
1135    {
1136        limitItem = fDownloadLimitItem;
1137        noLimitItem = fDownloadNoLimitItem;
1138    }
1139   
1140    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1141    [limitItem setState: enable ? NSOnState : NSOffState];
1142    [noLimitItem setState: !enable ? NSOnState : NSOffState];
1143   
1144    [limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
1145                            [[dict objectForKey: @"Limit"] intValue]]];
1146
1147    [dict release];
1148}
1149
1150- (void) setRatioGlobalEnabled: (id) sender
1151{
1152    [fPrefsController setRatioEnabled: sender == fRatioSetItem];
1153}
1154
1155- (void) setQuickRatioGlobal: (id) sender
1156{
1157    [fPrefsController setQuickRatio: [[sender title] floatValue]];
1158}
1159
1160- (void) ratioGlobalChange: (NSNotification *) notification
1161{
1162    NSDictionary * dict = [notification object];
1163   
1164    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1165    [fRatioSetItem setState: enable ? NSOnState : NSOffState];
1166    [fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
1167   
1168    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
1169                            [[dict objectForKey: @"Ratio"] floatValue]]];
1170
1171    [dict release];
1172}
1173
1174- (void) checkWaitingForStopped: (NSNotification *) notification
1175{
1176    [self checkToStartWaiting: [notification object]];
1177   
1178    [self updateUI: nil];
1179    [self applyFilter: nil];
1180    [fInfoController updateInfoStatsAndSettings];
1181    [self updateTorrentHistory];
1182}
1183
1184- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1185{
1186    //don't try to start a transfer if there should be none waiting
1187    if (![[fDefaults stringForKey: @"StartSetting"] isEqualToString: @"Wait"])
1188        return;
1189
1190    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1191   
1192    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1193    Torrent * torrent, * torrentToStart = nil;
1194    while ((torrent = [enumerator nextObject]))
1195    {
1196        //ignore the torrent just stopped
1197        if (torrent == finishedTorrent)
1198            continue;
1199   
1200        if ([torrent isActive])
1201        {
1202            if (![torrent isSeeding])
1203            {
1204                desiredActive--;
1205                if (desiredActive <= 0)
1206                    return;
1207            }
1208        }
1209        else
1210        {
1211            //use as next if it is waiting to start and either no previous or order value is lower
1212            if ([torrent waitingToStart] && (!torrentToStart
1213                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1214                torrentToStart = torrent;
1215        }
1216    }
1217   
1218    //since it hasn't returned, the queue amount has not been met
1219    if (torrentToStart)
1220    {
1221        [torrentToStart startTransfer];
1222       
1223        [self updateUI: nil];
1224        [self applyFilter: nil];
1225        [fInfoController updateInfoStatsAndSettings];
1226        [self updateTorrentHistory];
1227    }
1228}
1229
1230- (void) torrentStartSettingChange: (NSNotification *) notification
1231{
1232    [self attemptToStartMultipleAuto: [notification object]];
1233
1234    [self updateUI: nil];
1235    [self applyFilter: nil];
1236    [fInfoController updateInfoStatsAndSettings];
1237    [self updateTorrentHistory];
1238}
1239
1240- (void) globalStartSettingChange: (NSNotification *) notification
1241{
1242    [self attemptToStartMultipleAuto: fTorrents];
1243   
1244    [self updateUI: nil];
1245    [self applyFilter: nil];
1246    [fInfoController updateInfoStatsAndSettings];
1247    [self updateTorrentHistory];
1248}
1249
1250- (void) torrentStoppedForRatio: (NSNotification *) notification
1251{
1252    [self applyFilter: nil];
1253    [fInfoController updateInfoStatsAndSettings];
1254   
1255    [GrowlApplicationBridge notifyWithTitle: @"Seeding Complete"
1256                description: [[notification object] name] notificationName: @"Seeding Complete"
1257                iconData: nil priority: 0 isSticky: NO clickContext: nil];
1258}
1259
1260- (void) attemptToStartAuto: (Torrent *) torrent
1261{
1262    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1263}
1264
1265//will try to start, taking into consideration the start preference
1266- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1267{
1268    NSString * startSetting = [fDefaults stringForKey: @"StartSetting"];
1269    if ([startSetting isEqualToString: @"Start"])
1270    {
1271        NSEnumerator * enumerator = [torrents objectEnumerator];
1272        Torrent * torrent;
1273        while ((torrent = [enumerator nextObject]))
1274            if ([torrent waitingToStart])
1275                [torrent startTransfer];
1276       
1277        return;
1278    }
1279    else if (![startSetting isEqualToString: @"Wait"])
1280        return;
1281    else;
1282   
1283    //determine the number of downloads needed to start
1284    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1285           
1286    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1287    Torrent * torrent;
1288    while ((torrent = [enumerator nextObject]))
1289        if ([torrent isActive] && ![torrent isSeeding])
1290        {
1291            desiredActive--;
1292            if (desiredActive <= 0)
1293                break;
1294        }
1295   
1296    //sort torrents by order value
1297    NSArray * sortedTorrents;
1298    if ([torrents count] > 1 && desiredActive > 0)
1299    {
1300        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1301                                                    @"orderValue" ascending: YES] autorelease];
1302        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1303       
1304        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1305        [descriptors release];
1306    }
1307    else
1308        sortedTorrents = torrents;
1309
1310    enumerator = [sortedTorrents objectEnumerator];
1311    while ((torrent = [enumerator nextObject]))
1312    {
1313        if ([torrent progress] >= 1.0)
1314            [torrent startTransfer];
1315        else
1316        {
1317            if ([torrent waitingToStart] && desiredActive > 0)
1318            {
1319                [torrent startTransfer];
1320                desiredActive--;
1321            }
1322        }
1323       
1324        [torrent update];
1325    }
1326}
1327
1328- (void) reloadInspectorSettings: (NSNotification *) notification
1329{
1330    [fInfoController updateInfoStatsAndSettings];
1331}
1332
1333- (void) checkAutoImportDirectory: (NSTimer *) timer
1334{
1335    if (![fDefaults boolForKey: @"AutoImport"])
1336        return;
1337       
1338    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1339   
1340    //if folder cannot be found or the contents hasn't changed simply give up
1341    NSArray * allFileNames;
1342    if (!(allFileNames = [[NSFileManager defaultManager] directoryContentsAtPath: path])
1343            || [allFileNames isEqualToArray: fAutoImportedNames])
1344        return;
1345
1346    //try to add files that haven't already been added
1347    NSMutableArray * newFileNames = [NSMutableArray arrayWithArray: allFileNames];
1348    [newFileNames removeObjectsInArray: fAutoImportedNames];
1349   
1350    //save the current list of files
1351    [fAutoImportedNames setArray: allFileNames];
1352   
1353    NSEnumerator * enumerator = [newFileNames objectEnumerator];
1354    NSString * file;
1355    unsigned oldCount;
1356    while ((file = [enumerator nextObject]))
1357        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1358        {
1359            oldCount = [fTorrents count];
1360            [self openFromSheet: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1361           
1362            //import only actually happened if the torrent array is larger
1363            if (oldCount < [fTorrents count])
1364                [GrowlApplicationBridge notifyWithTitle: @"Torrent File Auto Added"
1365                    description: file notificationName: @"Torrent Auto Added" iconData: nil
1366                    priority: 0 isSticky: NO clickContext: nil];
1367        }
1368}
1369
1370- (void) autoImportChange: (NSNotification *) notification
1371{
1372    [fAutoImportedNames removeAllObjects];
1373    [self checkAutoImportDirectory: nil];
1374}
1375
1376- (int) numberOfRowsInTableView: (NSTableView *) t
1377{
1378    return [fFilteredTorrents count];
1379}
1380
1381- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
1382    forTableColumn: (NSTableColumn *) tableColumn row: (int) row
1383{
1384    [cell setTorrent: [fFilteredTorrents objectAtIndex: row]];
1385}
1386
1387- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1388    toPasteboard: (NSPasteboard *) pasteboard
1389{
1390    //only allow reordering of rows if sorting by order with no filter
1391    if ([fSortType isEqualToString: @"Order"] && [fTorrents count] == [fFilteredTorrents count])
1392    {
1393        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1394        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1395                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1396        return YES;
1397    }
1398    return NO;
1399}
1400
1401- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1402    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1403{
1404    NSPasteboard * pasteboard = [info draggingPasteboard];
1405    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1406    {
1407        //check if any files to add have "torrent" as an extension
1408        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1409        NSString * file;
1410        while ((file = [enumerator nextObject]))
1411            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1412            {
1413                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1414                return NSDragOperationGeneric;
1415            }
1416    }
1417    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1418    {
1419        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1420        return NSDragOperationGeneric;
1421    }
1422    else;
1423   
1424    return NSDragOperationNone;
1425}
1426
1427- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1428    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1429{
1430    NSPasteboard * pasteboard = [info draggingPasteboard];
1431    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1432    {
1433        //create an array of files with the "torrent" extension
1434        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1435        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1436        NSString * file;
1437        while ((file = [enumerator nextObject]))
1438            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1439                [filesToOpen addObject: file];
1440   
1441        [self application: NSApp openFiles: filesToOpen];
1442        [filesToOpen release];
1443    }
1444    else
1445    {
1446        //remember selected rows if needed
1447        NSArray * selectedTorrents = nil;
1448        int numSelected = [fTableView numberOfSelectedRows];
1449        if (numSelected > 0 && numSelected < [fFilteredTorrents count])
1450            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1451   
1452        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1453                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1454       
1455        //move torrent in array
1456        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1457        [fFilteredTorrents removeObjectsInArray: movingTorrents];
1458       
1459        //determine the insertion index now that transfers to move have been removed
1460        int i, decrease = 0;
1461        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1462            decrease++;
1463       
1464        //insert objects at new location
1465        for (i = 0; i < [movingTorrents count]; i++)
1466            [fFilteredTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1467       
1468        [movingTorrents release];
1469       
1470        //redo order values
1471        int low = [indexes firstIndex], high = [indexes lastIndex];
1472        if (newRow < low)
1473            low = newRow;
1474        else if (newRow > high + 1)
1475            high = newRow - 1;
1476        else;
1477       
1478        for (i = low; i <= high; i++)
1479            [[fFilteredTorrents objectAtIndex: i] setOrderValue: i];
1480       
1481        [fTableView reloadData];
1482       
1483        //set selected rows if needed
1484        if (selectedTorrents)
1485        {
1486            Torrent * torrent;
1487            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1488            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1489            while ((torrent = [enumerator nextObject]))
1490                [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
1491           
1492            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1493            [indexSet release];
1494        }
1495    }
1496   
1497    return YES;
1498}
1499
1500- (void) tableViewSelectionDidChange: (NSNotification *) notification
1501{
1502    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1503}
1504
1505- (void) toggleSmallView: (id) sender
1506{
1507    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
1508   
1509    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1510    [fSmallViewItem setState: makeSmall];
1511   
1512    [fDefaults setBool: makeSmall forKey: @"SmallView"];
1513   
1514    //window min height
1515    NSSize contentMinSize = [fWindow contentMinSize],
1516            contentSize = [[fWindow contentView] frame].size;
1517    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1518                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1519    [fWindow setContentMinSize: contentMinSize];
1520   
1521    //resize for larger min height
1522    if (!makeSmall && contentSize.height < contentMinSize.height)
1523    {
1524        NSRect frame = [fWindow frame];
1525        float heightChange = contentMinSize.height - contentSize.height;
1526        frame.size.height += heightChange;
1527        frame.origin.y -= heightChange;
1528       
1529        [fWindow setFrame: frame display: YES];
1530        [fTableView reloadData];
1531    }
1532}
1533
1534- (void) toggleStatusBar: (id) sender
1535{
1536    [self showStatusBar: !fStatusBarVisible animate: YES];
1537    [fDefaults setBool: fStatusBarVisible forKey: @"StatusBar"];
1538}
1539
1540- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1541{
1542    if (show == fStatusBarVisible)
1543        return;
1544
1545    NSRect frame = [fWindow frame];
1546    float heightChange = [fStatusBar frame].size.height;
1547    if (!show)
1548        heightChange *= -1;
1549
1550    frame.size.height += heightChange;
1551    frame.origin.y -= heightChange;
1552       
1553    fStatusBarVisible = !fStatusBarVisible;
1554   
1555    [self updateUI: nil];
1556   
1557    //set views to not autoresize
1558    unsigned int statsMask = [fStatusBar autoresizingMask];
1559    unsigned int filterMask = [fFilterBar autoresizingMask];
1560    unsigned int scrollMask = [fScrollView autoresizingMask];
1561    [fStatusBar setAutoresizingMask: 0];
1562    [fFilterBar setAutoresizingMask: 0];
1563    [fScrollView setAutoresizingMask: 0];
1564   
1565    [fWindow setFrame: frame display: YES animate: animate];
1566   
1567    //re-enable autoresize
1568    [fStatusBar setAutoresizingMask: statsMask];
1569    [fFilterBar setAutoresizingMask: filterMask];
1570    [fScrollView setAutoresizingMask: scrollMask];
1571   
1572    //change min size
1573    NSSize minSize = [fWindow contentMinSize];
1574    minSize.height += heightChange;
1575    [fWindow setContentMinSize: minSize];
1576   
1577    //reset tracking rects for filter buttons
1578    [fNoFilterButton resetBounds: nil];
1579    [fSeedFilterButton resetBounds: nil];
1580    [fDownloadFilterButton resetBounds: nil];
1581    [fPauseFilterButton resetBounds: nil];
1582}
1583
1584- (void) toggleFilterBar: (id) sender
1585{
1586    [self showFilterBar: !fFilterBarVisible animate: YES];
1587    [fDefaults setBool: fFilterBarVisible forKey: @"FilterBar"];
1588   
1589    //disable filtering when hiding
1590    if (!fFilterBarVisible)
1591    {
1592        [fSearchFilterField setStringValue: @""];
1593        [self setFilter: fNoFilterButton];
1594    }
1595}
1596
1597- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1598{
1599    if (show == fFilterBarVisible)
1600        return;
1601
1602    NSRect frame = [fWindow frame];
1603    float heightChange = [fFilterBar frame].size.height;
1604    if (!show)
1605        heightChange *= -1;
1606
1607    frame.size.height += heightChange;
1608    frame.origin.y -= heightChange;
1609       
1610    fFilterBarVisible = !fFilterBarVisible;
1611   
1612    //set views to not autoresize
1613    unsigned int filterMask = [fFilterBar autoresizingMask];
1614    unsigned int scrollMask = [fScrollView autoresizingMask];
1615    [fFilterBar setAutoresizingMask: 0];
1616    [fScrollView setAutoresizingMask: 0];
1617   
1618    [fWindow setFrame: frame display: YES animate: animate];
1619   
1620    //re-enable autoresize
1621    [fFilterBar setAutoresizingMask: filterMask];
1622    [fScrollView setAutoresizingMask: scrollMask];
1623   
1624    //change min size
1625    NSSize minSize = [fWindow contentMinSize];
1626    minSize.height += heightChange;
1627    [fWindow setContentMinSize: minSize];
1628   
1629    //enable/disable search field
1630    [fSearchFilterField setEnabled: show];
1631    if (!show)
1632        [fWindow makeFirstResponder: fTableView];
1633   
1634    //reset tracking rects for filter buttons
1635    [fNoFilterButton resetBounds: nil];
1636    [fSeedFilterButton resetBounds: nil];
1637    [fDownloadFilterButton resetBounds: nil];
1638    [fPauseFilterButton resetBounds: nil];
1639}
1640
1641- (void) toggleAdvancedBar: (id) sender
1642{
1643    int state = ![fAdvancedBarItem state];
1644    [fAdvancedBarItem setState: state];
1645    [fDefaults setBool: state forKey: @"UseAdvancedBar"];
1646
1647    [fTableView display];
1648}
1649
1650- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1651    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1652{
1653    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1654
1655    if ([ident isEqualToString: TOOLBAR_OPEN])
1656    {
1657        [item setLabel: @"Open"];
1658        [item setPaletteLabel: @"Open Torrent Files"];
1659        [item setToolTip: @"Open torrent files"];
1660        [item setImage: [NSImage imageNamed: @"Open.png"]];
1661        [item setTarget: self];
1662        [item setAction: @selector(openShowSheet:)];
1663    }
1664    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1665    {
1666        [item setLabel: @"Remove"];
1667        [item setPaletteLabel: @"Remove Selected"];
1668        [item setToolTip: @"Remove selected transfers"];
1669        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1670        [item setTarget: self];
1671        [item setAction: @selector(removeNoDelete:)];
1672    }
1673    else if ([ident isEqualToString: TOOLBAR_INFO])
1674    {
1675        [item setLabel: @"Inspector"];
1676        [item setPaletteLabel: @"Show/Hide Inspector"];
1677        [item setToolTip: @"Display torrent inspector"];
1678        [item setImage: [NSImage imageNamed: @"Info.png"]];
1679        [item setTarget: self];
1680        [item setAction: @selector(showInfo:)];
1681    }
1682    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1683    {
1684        [item setLabel: @"Pause All"];
1685        [item setPaletteLabel: [item label]];
1686        [item setToolTip: @"Pause all transfers"];
1687        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1688        [item setTarget: self];
1689        [item setAction: @selector(stopAllTorrents:)];
1690    }
1691    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1692    {
1693        [item setLabel: @"Resume All"];
1694        [item setPaletteLabel: [item label]];
1695        [item setToolTip: @"Resume all transfers"];
1696        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1697        [item setTarget: self];
1698        [item setAction: @selector(resumeAllTorrents:)];
1699    }
1700    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1701    {
1702        [item setLabel: @"Pause"];
1703        [item setPaletteLabel: @"Pause Selected"];
1704        [item setToolTip: @"Pause selected transfers"];
1705        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1706        [item setTarget: self];
1707        [item setAction: @selector(stopSelectedTorrents:)];
1708    }
1709    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1710    {
1711        [item setLabel: @"Resume"];
1712        [item setPaletteLabel: @"Resume Selected"];
1713        [item setToolTip: @"Resume selected transfers"];
1714        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1715        [item setTarget: self];
1716        [item setAction: @selector(resumeSelectedTorrents:)];
1717    }
1718    else
1719    {
1720        [item release];
1721        return nil;
1722    }
1723
1724    return item;
1725}
1726
1727- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1728{
1729    return [NSArray arrayWithObjects:
1730            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1731            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1732            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_INFO,
1733            NSToolbarSeparatorItemIdentifier,
1734            NSToolbarSpaceItemIdentifier,
1735            NSToolbarFlexibleSpaceItemIdentifier,
1736            NSToolbarCustomizeToolbarItemIdentifier, nil];
1737}
1738
1739- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1740{
1741    return [NSArray arrayWithObjects:
1742            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1743            NSToolbarSeparatorItemIdentifier,
1744            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1745            NSToolbarFlexibleSpaceItemIdentifier,
1746            TOOLBAR_INFO, nil];
1747}
1748
1749- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1750{
1751    NSString * ident = [toolbarItem itemIdentifier];
1752
1753    //enable remove item
1754    if ([ident isEqualToString: TOOLBAR_REMOVE])
1755        return [fTableView numberOfSelectedRows] > 0;
1756
1757    //enable pause all item
1758    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1759    {
1760        Torrent * torrent;
1761        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1762        while ((torrent = [enumerator nextObject]))
1763            if ([torrent isActive])
1764                return YES;
1765        return NO;
1766    }
1767
1768    //enable resume all item
1769    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1770    {
1771        Torrent * torrent;
1772        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1773        while ((torrent = [enumerator nextObject]))
1774            if ([torrent isPaused])
1775                return YES;
1776        return NO;
1777    }
1778
1779    //enable pause item
1780    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1781    {
1782        Torrent * torrent;
1783        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1784        unsigned int i;
1785       
1786        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1787            if ([[fFilteredTorrents objectAtIndex: i] isActive])
1788                return YES;
1789        return NO;
1790    }
1791   
1792    //enable resume item
1793    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1794    {
1795        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1796        unsigned int i;
1797       
1798        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1799            if ([[fFilteredTorrents objectAtIndex: i] isPaused])
1800                return YES;
1801        return NO;
1802    }
1803
1804    return YES;
1805}
1806
1807- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1808{
1809    SEL action = [menuItem action];
1810
1811    //only enable some items if it is in a context menu or the window is useable
1812    BOOL canUseMenu = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
1813
1814    //enable show info
1815    if (action == @selector(showInfo:))
1816    {
1817        NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
1818        if (![[menuItem title] isEqualToString: title])
1819                [menuItem setTitle: title];
1820
1821        return YES;
1822    }
1823   
1824    //enable prev/next inspector tab
1825    if (action == @selector(setInfoTab:))
1826        return [[fInfoController window] isVisible];
1827   
1828    //enable toggle status bar
1829    if (action == @selector(toggleStatusBar:))
1830    {
1831        NSString * title = fStatusBarVisible ? @"Hide Status Bar" : @"Show Status Bar";
1832        if (![[menuItem title] isEqualToString: title])
1833                [menuItem setTitle: title];
1834
1835        return canUseMenu;
1836    }
1837   
1838    //enable toggle filter bar
1839    if (action == @selector(toggleFilterBar:))
1840    {
1841        NSString * title = fFilterBarVisible ? @"Hide Filter Bar" : @"Show Filter Bar";
1842        if (![[menuItem title] isEqualToString: title])
1843                [menuItem setTitle: title];
1844
1845        return canUseMenu;
1846    }
1847
1848    //enable resume all item
1849    if (action == @selector(resumeAllTorrents:))
1850    {
1851        Torrent * torrent;
1852        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1853        while ((torrent = [enumerator nextObject]))
1854            if ([torrent isPaused])
1855                return YES;
1856        return NO;
1857    }
1858
1859    //enable pause all item
1860    if (action == @selector(stopAllTorrents:))
1861    {
1862        Torrent * torrent;
1863        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1864        while ((torrent = [enumerator nextObject]))
1865            if ([torrent isActive])
1866                return YES;
1867        return NO;
1868    }
1869
1870    //enable reveal in finder
1871    if (action == @selector(revealFile:))
1872        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1873
1874    //enable remove items
1875    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
1876        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
1877    {
1878        BOOL warning = NO,
1879            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
1880            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
1881        Torrent * torrent;
1882        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1883        unsigned int i;
1884       
1885        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1886        {
1887            torrent = [fFilteredTorrents objectAtIndex: i];
1888            if (!warning && [torrent isActive])
1889            {
1890                warning = onlyDownloading ? ![torrent isSeeding] : YES;
1891                if (warning && canDelete)
1892                    break;
1893            }
1894            if (!canDelete && [torrent publicTorrent])
1895            {
1896                canDelete = YES;
1897                if (warning)
1898                    break;
1899            }
1900        }
1901   
1902        //append or remove ellipsis when needed
1903        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
1904        if (warning && [fDefaults boolForKey: @"CheckRemove"])
1905        {
1906            if (![title hasSuffix: ellipsis])
1907                [menuItem setTitle: [title stringByAppendingEllipsis]];
1908        }
1909        else
1910        {
1911            if ([title hasSuffix: ellipsis])
1912                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
1913        }
1914       
1915        return canUseMenu && canDelete && [fTableView numberOfSelectedRows] > 0;
1916    }
1917
1918    //enable pause item
1919    if (action == @selector(stopSelectedTorrents:))
1920    {
1921        if (!canUseMenu)
1922            return NO;
1923   
1924        Torrent * torrent;
1925        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1926        unsigned int i;
1927       
1928        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1929        {
1930            torrent = [fFilteredTorrents objectAtIndex: i];
1931            if ([torrent isActive])
1932                return YES;
1933        }
1934        return NO;
1935    }
1936   
1937    //enable resume item
1938    if (action == @selector(resumeSelectedTorrents:))
1939    {
1940        if (!canUseMenu)
1941            return NO;
1942   
1943        Torrent * torrent;
1944        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1945        unsigned int i;
1946       
1947        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1948        {
1949            torrent = [fFilteredTorrents objectAtIndex: i];
1950            if ([torrent isPaused])
1951                return YES;
1952        }
1953        return NO;
1954    }
1955   
1956    //enable sort and advanced bar items
1957    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:)
1958            || action == @selector(toggleSmallView:))
1959        return canUseMenu;
1960   
1961    //enable copy torrent file item
1962    if (action == @selector(copyTorrentFile:))
1963    {
1964        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1965    }
1966
1967    return YES;
1968}
1969
1970- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
1971{
1972    NSEnumerator * enumerator;
1973    Torrent * torrent;
1974    BOOL active;
1975
1976    switch (messageType)
1977    {
1978        case kIOMessageSystemWillSleep:
1979            //close all connections before going to sleep and remember we should resume when we wake up
1980            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
1981
1982            //wait for running transfers to stop (5 second timeout)
1983            NSDate * start = [NSDate date];
1984            BOOL timeUp = NO;
1985           
1986            NSEnumerator * enumerator = [fTorrents objectEnumerator];
1987            Torrent * torrent;
1988            while (!timeUp && (torrent = [enumerator nextObject]))
1989                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
1990                {
1991                    usleep(100000);
1992                    [torrent update];
1993                }
1994
1995            IOAllowPowerChange(fRootPort, (long) messageArgument);
1996            break;
1997
1998        case kIOMessageCanSystemSleep:
1999            //pevent idle sleep unless all paused
2000            active = NO;
2001            enumerator = [fTorrents objectEnumerator];
2002            while ((torrent = [enumerator nextObject]))
2003                if ([torrent isActive])
2004                {
2005                    active = YES;
2006                    break;
2007                }
2008
2009            if (active)
2010                IOCancelPowerChange(fRootPort, (long) messageArgument);
2011            else
2012                IOAllowPowerChange(fRootPort, (long) messageArgument);
2013            break;
2014
2015        case kIOMessageSystemHasPoweredOn:
2016            //resume sleeping transfers after we wake up
2017            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2018            break;
2019    }
2020}
2021
2022- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2023{
2024    NSRect windowRect = [fWindow frame];
2025    float newHeight = windowRect.size.height - [fScrollView frame].size.height
2026        + [fFilteredTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2027
2028    float minHeight = [fWindow minSize].height;
2029    if (newHeight < minHeight)
2030        newHeight = minHeight;
2031
2032    windowRect.origin.y -= (newHeight - windowRect.size.height);
2033    windowRect.size.height = newHeight;
2034
2035    return windowRect;
2036}
2037
2038- (void) showMainWindow: (id) sender
2039{
2040    [fWindow makeKeyAndOrderFront: nil];
2041}
2042
2043- (void) windowDidBecomeKey: (NSNotification *) notification
2044{
2045    fCompleted = 0;
2046}
2047
2048- (void) windowDidResize: (NSNotification *) notification
2049{
2050    //hide search filter if it overlaps filter buttons
2051    NSRect buttonFrame = [fPauseFilterButton frame];
2052    BOOL overlap = buttonFrame.origin.x + buttonFrame.size.width + 2.0 > [fSearchFilterField frame].origin.x;
2053   
2054    if (![fSearchFilterField isHidden])
2055    {
2056        if (overlap)
2057            [fSearchFilterField setHidden: YES];
2058    }
2059    else
2060    {
2061        if (!overlap)
2062            [fSearchFilterField setHidden: NO];
2063    }
2064}
2065
2066- (void) linkHomepage: (id) sender
2067{
2068    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2069}
2070
2071- (void) linkForums: (id) sender
2072{
2073    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2074}
2075
2076- (void) checkUpdate: (id) sender
2077{
2078    [fPrefsController checkUpdate];
2079}
2080
2081- (void) prepareForUpdate: (NSNotification *) notification
2082{
2083    fUpdateInProgress = YES;
2084}
2085
2086- (NSDictionary *) registrationDictionaryForGrowl
2087{
2088    NSArray * notifications = [NSArray arrayWithObjects: @"Download Complete",
2089                                @"Seeding Complete", @"Torrent Auto Added", nil];
2090    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2091                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2092}
2093
2094@end
Note: See TracBrowser for help on using the repository browser.