source: trunk/macosx/Controller.m @ 617

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

hide search filter if it overlaps filter buttons

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