source: trunk/macosx/Controller.m @ 614

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

small search field in filter

  • Property svn:keywords set to Date Rev Author Id
File size: 70.0 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 614 2006-07-16 17:59:20Z 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    //set table size
117    if ([fDefaults boolForKey: @"SmallView"])
118    {
119        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
120        [fSmallViewItem setState: NSOnState];
121    }
122   
123    //window min height
124    NSSize contentMinSize = [fWindow contentMinSize];
125    contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
126                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
127    [fWindow setContentMinSize: contentMinSize];
128   
129    //set info keyboard shortcuts
130    unichar ch = NSRightArrowFunctionKey;
131    [fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
132    ch = NSLeftArrowFunctionKey;
133    [fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
134   
135    //set up filter bar
136    NSView * contentView = [fWindow contentView];
137   
138    fFilterBarVisible = NO;
139    NSRect filterBarFrame = [fFilterBar frame];
140    filterBarFrame.size.width = [fWindow frame].size.width;
141    [fFilterBar setFrame: filterBarFrame];
142   
143    [contentView addSubview: fFilterBar];
144    [fFilterBar setFrameOrigin: NSMakePoint(0, [contentView frame].origin.y + [contentView frame].size.height)];
145    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
146   
147    //set up status bar
148    fStatusBarVisible = NO;
149    NSRect statusBarFrame = [fStatusBar frame];
150    statusBarFrame.size.width = [fWindow frame].size.width;
151    [fStatusBar setFrame: statusBarFrame];
152   
153    [contentView addSubview: fStatusBar];
154    [fStatusBar setFrameOrigin: NSMakePoint(0, [contentView frame].origin.y + [contentView frame].size.height)];
155    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
156   
157    //set speed limit
158    [self updateControlTint: nil];
159   
160    if ([fDefaults boolForKey: @"SpeedLimit"])
161    {
162        [fSpeedLimitItem setState: NSOnState];
163        [fSpeedLimitDockItem setState: NSOnState];
164        [fSpeedLimitButton setState: NSOnState];
165    }
166   
167    [[fSpeedLimitButton cell] setHighlightsBy: NSNoCellMask];
168
169    [fActionButton setToolTip: @"Shortcuts for changing global settings."];
170    [fSpeedLimitButton setToolTip: @"Speed Limit overrides the total bandwidth limits with its own limits."];
171
172    [fTableView setTorrents: fFilteredTorrents];
173    [[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell: [[TorrentCell alloc] init]];
174
175    [fTableView registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType,
176                                                        TORRENT_TABLE_VIEW_DATA_TYPE, nil]];
177
178    //register for sleep notifications
179    IONotificationPortRef notify;
180    io_object_t iterator;
181    if (fRootPort = IORegisterForSystemPower(self, & notify, sleepCallBack, & iterator))
182        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify),
183                            kCFRunLoopCommonModes);
184    else
185        NSLog(@"Could not IORegisterForSystemPower");
186
187    //load torrents from history
188    Torrent * torrent;
189    NSDictionary * historyItem;
190    NSEnumerator * enumerator = [[fDefaults arrayForKey: @"History"] objectEnumerator];
191    while ((historyItem = [enumerator nextObject]))
192        if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
193        {
194            [fTorrents addObject: torrent];
195            [torrent release];
196        }
197   
198    [self torrentNumberChanged];
199   
200    //set sort
201    fSortType = [[fDefaults stringForKey: @"Sort"] retain];
202   
203    NSMenuItem * currentSortItem;
204    if ([fSortType isEqualToString: @"Name"])
205        currentSortItem = fNameSortItem;
206    else if ([fSortType isEqualToString: @"State"])
207        currentSortItem = fStateSortItem;
208    else if ([fSortType isEqualToString: @"Progress"])
209        currentSortItem = fProgressSortItem;
210    else if ([fSortType isEqualToString: @"Date"])
211        currentSortItem = fDateSortItem;
212    else
213        currentSortItem = fOrderSortItem;
214    [currentSortItem setState: NSOnState];
215   
216    //set filter
217    fFilterType = [[fDefaults stringForKey: @"Filter"] retain];
218
219    [fNoFilterButton setText: @"All"];
220    [fPauseFilterButton setText: @"Paused"];
221    [fSeedFilterButton setText: @"Seeding"];
222    [fDownloadFilterButton setText: @"Downloading"];
223
224    NSMenuItem * currentFilterItem;
225    BarButton * currentFilterButton;
226    if ([fFilterType isEqualToString: @"Pause"])
227        currentFilterButton = fPauseFilterButton;
228    else if ([fFilterType isEqualToString: @"Seed"])
229        currentFilterButton = fSeedFilterButton;
230    else if ([fFilterType isEqualToString: @"Download"])
231        currentFilterButton = fDownloadFilterButton;
232    else
233        currentFilterButton = fNoFilterButton;
234
235    [currentFilterButton setEnabled: YES];
236   
237    //set upload limit action button
238    [fUploadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
239                    [fDefaults integerForKey: @"UploadLimit"]]];
240    if ([fDefaults boolForKey: @"CheckUpload"])
241        [fUploadLimitItem setState: NSOnState];
242    else
243        [fUploadNoLimitItem setState: NSOnState];
244
245        //set download limit action menu
246    [fDownloadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
247                    [fDefaults integerForKey: @"DownloadLimit"]]];
248    if ([fDefaults boolForKey: @"CheckDownload"])
249        [fDownloadLimitItem setState: NSOnState];
250    else
251        [fDownloadNoLimitItem setState: NSOnState];
252   
253    //set ratio action menu
254    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
255                                [fDefaults floatForKey: @"RatioLimit"]]];
256    if ([fDefaults boolForKey: @"RatioCheck"])
257        [fRatioSetItem setState: NSOnState];
258    else
259        [fRatioNotSetItem setState: NSOnState];
260   
261    //observe notifications
262    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
263   
264    [nc addObserver: self selector: @selector(updateControlTint:)
265                    name: NSControlTintDidChangeNotification object: nil];
266   
267    [nc addObserver: self selector: @selector(prepareForUpdate:)
268                    name: SUUpdaterWillRestartNotification object: nil];
269    fUpdateInProgress = NO;
270   
271    [nc addObserver: self selector: @selector(limitGlobalChange:)
272                    name: @"LimitGlobalChange" object: nil];
273   
274    [nc addObserver: self selector: @selector(ratioGlobalChange:)
275                    name: @"RatioGlobalChange" object: nil];
276   
277    //check to start another because of stopped torrent
278    [nc addObserver: self selector: @selector(checkWaitingForStopped:)
279                    name: @"StoppedDownloading" object: nil];
280   
281    //check all torrents for starting
282    [nc addObserver: self selector: @selector(globalStartSettingChange:)
283                    name: @"GlobalStartSettingChange" object: nil];
284
285    //check if torrent should now start
286    [nc addObserver: self selector: @selector(torrentStartSettingChange:)
287                    name: @"TorrentStartSettingChange" object: nil];
288   
289    //check if torrent should now start
290    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
291                    name: @"TorrentStoppedForRatio" object: nil];
292   
293    //change that just impacts the inspector
294    [nc addObserver: self selector: @selector(reloadInspectorSettings:)
295                    name: @"TorrentSettingChange" object: nil];
296   
297    //reset auto import
298    [nc addObserver: self selector: @selector(autoImportChange:)
299                    name: @"AutoImportSettingChange" object: nil];
300
301    //timer to update the interface every second
302    fCompleted = 0;
303    [self updateUI: nil];
304    fTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
305        selector: @selector(updateUI:) userInfo: nil repeats: YES];
306    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
307    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
308   
309    //timer for auto import, will check every 15 seconds
310    fAutoImportedNames = [[NSMutableArray alloc] init];
311   
312    [self checkAutoImportDirectory: nil];
313    fAutoImportTimer = [NSTimer scheduledTimerWithTimeInterval: 15.0 target: self
314        selector: @selector(checkAutoImportDirectory:) userInfo: nil repeats: YES];
315    [[NSRunLoop currentRunLoop] addTimer: fAutoImportTimer forMode: NSDefaultRunLoopMode];
316   
317    [self applyFilter: nil];
318   
319    [fWindow makeKeyAndOrderFront: nil];
320
321    //load info for no torrents
322    [fInfoController updateInfoForTorrents: [NSArray array]];
323    if ([fDefaults boolForKey: @"InfoVisible"])
324        [self showInfo: nil];
325}
326
327- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
328{
329    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
330        [fWindow makeKeyAndOrderFront: nil];
331    return NO;
332}
333
334- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
335{
336    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
337    {
338        int active = 0, downloading = 0;
339        Torrent * torrent;
340        NSEnumerator * enumerator = [fTorrents objectEnumerator];
341        while ((torrent = [enumerator nextObject]))
342            if ([torrent isActive])
343            {
344                active++;
345                if (![torrent isSeeding])
346                    downloading++;
347            }
348
349        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
350        {
351            NSString * message = active == 1
352                ? @"There is an active transfer. Do you really want to quit?"
353                : [NSString stringWithFormat:
354                    @"There are %d active transfers. Do you really want to quit?", active];
355
356            NSBeginAlertSheet(@"Confirm Quit", @"Quit", @"Cancel", nil, fWindow, self,
357                                @selector(quitSheetDidEnd:returnCode:contextInfo:),
358                                nil, nil, message);
359            return NSTerminateLater;
360        }
361    }
362
363    return NSTerminateNow;
364}
365
366- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
367    contextInfo: (void *) contextInfo
368{
369    [NSApp stopModal];
370    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
371}
372
373- (void) applicationWillTerminate: (NSNotification *) notification
374{
375    //stop timers
376    [fAutoImportTimer invalidate];
377    [fTimer invalidate];
378   
379    //save history and stop running torrents
380    [self updateTorrentHistory];
381    [fTorrents makeObjectsPerformSelector: @selector(stopTransferForQuit)];
382   
383    //remember window states and close all windows
384    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
385    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
386    [self showStatusBar: NO animate: NO];
387    [self showFilterBar: NO animate: NO];
388   
389    //clear badge
390    [fBadger clearBadge];
391
392    //end quickly if the app is updating
393    if (fUpdateInProgress)
394        return;
395
396    //wait for running transfers to stop (5 second timeout)
397    NSDate * start = [NSDate date];
398    BOOL timeUp = NO;
399   
400    NSEnumerator * enumerator = [fTorrents objectEnumerator];
401    Torrent * torrent;
402    while (!timeUp && (torrent = [enumerator nextObject]))
403        while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
404        {
405            usleep(100000);
406            [torrent update];
407        }
408}
409
410- (void) folderChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code
411    contextInfo: (Torrent *) torrent
412{
413    if (code == NSOKButton)
414    {
415        [torrent setDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
416        [torrent update];
417        [self attemptToStartAuto: torrent];
418       
419        [fTorrents addObject: torrent];
420       
421        [self torrentNumberChanged];
422    }
423   
424    [NSApp stopModal];
425}
426
427- (void) application: (NSApplication *) sender openFiles: (NSArray *) filenames
428{
429    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"], * torrentPath;
430    Torrent * torrent;
431    NSEnumerator * enumerator = [filenames objectEnumerator];
432    while ((torrentPath = [enumerator nextObject]))
433    {
434        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
435            continue;
436
437        //add it to the "File > Open Recent" menu
438        [[NSDocumentController sharedDocumentController]
439            noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
440
441        if ([downloadChoice isEqualToString: @"Ask"])
442        {
443            NSOpenPanel * panel = [NSOpenPanel openPanel];
444
445            [panel setPrompt: @"Select Download Folder"];
446            [panel setAllowsMultipleSelection: NO];
447            [panel setCanChooseFiles: NO];
448            [panel setCanChooseDirectories: YES];
449
450            [panel setMessage: [NSString stringWithFormat: @"Select the download folder for \"%@\"", [torrent name]]];
451
452            [panel beginSheetForDirectory: nil file: nil types: nil
453                modalForWindow: fWindow modalDelegate: self didEndSelector:
454                @selector( folderChoiceClosed:returnCode:contextInfo: )
455                contextInfo: torrent];
456            [NSApp runModalForWindow: panel];
457        }
458        else
459        {
460            NSString * folder = [downloadChoice isEqualToString: @"Constant"]
461                ? [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]
462                : [torrentPath stringByDeletingLastPathComponent];
463
464            [torrent setDownloadFolder: folder];
465            [torrent update];
466            [self attemptToStartAuto: torrent];
467           
468            [fTorrents addObject: torrent];
469        }
470       
471        [torrent release];
472    }
473
474    [self torrentNumberChanged];
475
476    [self updateUI: nil];
477    [self applyFilter: nil];
478    [self updateTorrentHistory];
479}
480
481- (NSArray *) torrentsAtIndexes: (NSIndexSet *) indexSet
482{
483    if ([fFilteredTorrents respondsToSelector: @selector(objectsAtIndexes:)])
484        return [fFilteredTorrents objectsAtIndexes: indexSet];
485    else
486    {
487        NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [indexSet count]];
488        unsigned int i;
489        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
490            [torrents addObject: [fFilteredTorrents objectAtIndex: i]];
491
492        return torrents;
493    }
494}
495
496- (void) torrentNumberChanged
497{
498    int count = [fTorrents count];
499    [fTotalTorrentsField setStringValue: [NSString stringWithFormat:
500        @"%d Transfer%s", count, count == 1 ? "" : "s"]];
501}
502
503//called on by applescript
504- (void) open: (NSArray *) files
505{
506    [self performSelectorOnMainThread: @selector(openFromSheet:) withObject: files waitUntilDone: NO];
507}
508
509- (void) openShowSheet: (id) sender
510{
511    NSOpenPanel * panel = [NSOpenPanel openPanel];
512
513    [panel setAllowsMultipleSelection: YES];
514    [panel setCanChooseFiles: YES];
515    [panel setCanChooseDirectories: NO];
516
517    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
518        modalForWindow: fWindow modalDelegate: self didEndSelector:
519        @selector(openSheetClosed:returnCode:contextInfo:) contextInfo: nil];
520}
521
522- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code
523    contextInfo: (void *) info
524{
525    if (code == NSOKButton)
526        [self performSelectorOnMainThread: @selector(openFromSheet:)
527                    withObject: [panel filenames] waitUntilDone: NO];
528}
529
530- (void) openFromSheet: (NSArray *) filenames
531{
532    [self application: NSApp openFiles: filenames];
533}
534
535- (void) resumeSelectedTorrents: (id) sender
536{
537    [self resumeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
538}
539
540- (void) resumeAllTorrents: (id) sender
541{
542    [self resumeTorrents: fTorrents];
543}
544
545- (void) resumeTorrents: (NSArray *) torrents;
546{
547    [torrents makeObjectsPerformSelector: @selector(startTransfer)];
548   
549    [self updateUI: nil];
550    [self applyFilter: nil];
551    [fInfoController updateInfoStatsAndSettings];
552    [self updateTorrentHistory];
553}
554
555- (void) stopSelectedTorrents: (id) sender
556{
557    [self stopTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
558}
559
560- (void) stopAllTorrents: (id) sender
561{
562    [self stopTorrents: fTorrents];
563}
564
565- (void) stopTorrents: (NSArray *) torrents;
566{
567    //don't want any of these starting then stopping
568    NSEnumerator * enumerator = [torrents objectEnumerator];
569    Torrent * torrent;
570    while ((torrent = [enumerator nextObject]))
571        [torrent setWaitToStart: NO];
572
573    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
574   
575    [self updateUI: nil];
576    [self applyFilter: nil];
577    [fInfoController updateInfoStatsAndSettings];
578    [self updateTorrentHistory];
579}
580
581- (void) removeTorrents: (NSArray *) torrents
582        deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
583{
584    [torrents retain];
585    int active = 0, downloading = 0;
586
587    if ([fDefaults boolForKey: @"CheckRemove"])
588    {
589        Torrent * torrent;
590        NSEnumerator * enumerator = [torrents objectEnumerator];
591        while ((torrent = [enumerator nextObject]))
592            if ([torrent isActive])
593            {
594                active++;
595                if (![torrent isSeeding])
596                    downloading++;
597            }
598
599        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
600        {
601            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
602                torrents, @"Torrents",
603                [NSNumber numberWithBool: deleteData], @"DeleteData",
604                [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
605
606            NSString * title, * message;
607           
608            int selected = [fTableView numberOfSelectedRows];
609            if (selected == 1)
610            {
611                title = [NSString stringWithFormat: @"Comfirm Removal of \"%@\"",
612                            [[fFilteredTorrents objectAtIndex: [fTableView selectedRow]] name]];
613                message = @"This transfer is active."
614                            " Once removed, continuing the transfer will require the torrent file."
615                            " Do you really want to remove it?";
616            }
617            else
618            {
619                title = [NSString stringWithFormat: @"Comfirm Removal of %d Transfers", selected];
620                if (selected == active)
621                    message = [NSString stringWithFormat:
622                        @"There are %d active transfers.", active];
623                else
624                    message = [NSString stringWithFormat:
625                        @"There are %d transfers (%d active).", selected, active];
626                message = [message stringByAppendingString:
627                    @" Once removed, continuing the transfers will require the torrent files."
628                    " Do you really want to remove them?"];
629            }
630
631            NSBeginAlertSheet(title, @"Remove", @"Cancel", nil, fWindow, self,
632                @selector(removeSheetDidEnd:returnCode:contextInfo:), nil, dict, message);
633            return;
634        }
635    }
636   
637    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
638}
639
640- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (NSDictionary *) dict
641{
642    [NSApp stopModal];
643
644    NSArray * torrents = [dict objectForKey: @"Torrents"];
645    BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue],
646        deleteTorrent = [[dict objectForKey: @"DeleteTorrent"] boolValue];
647    [dict release];
648   
649    if (returnCode == NSAlertDefaultReturn)
650        [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
651    else
652        [torrents release];
653}
654
655- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
656{
657    //don't want any of these starting then stopping
658    NSEnumerator * enumerator = [torrents objectEnumerator];
659    Torrent * torrent;
660    while ((torrent = [enumerator nextObject]))
661        [torrent setWaitToStart: NO];
662
663    NSNumber * lowestOrderValue = [NSNumber numberWithInt: [torrents count]], * currentOrderValue;
664
665    enumerator = [torrents objectEnumerator];
666    while ((torrent = [enumerator nextObject]))
667    {
668        [torrent stopTransfer];
669
670        if (deleteData)
671            [torrent trashData];
672        if (deleteTorrent)
673            [torrent trashTorrent];
674       
675        //determine lowest order value
676        currentOrderValue = [torrent orderValue];
677        if ([lowestOrderValue compare: currentOrderValue] == NSOrderedDescending)
678            lowestOrderValue = currentOrderValue;
679
680        [torrent removeForever];
681       
682        [fFilteredTorrents removeObject: torrent];
683        [fTorrents removeObject: torrent];
684    }
685    [torrents release];
686
687    //reset the order values if necessary
688    if ([lowestOrderValue intValue] < [fTorrents count])
689    {
690        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
691                                                @"orderValue" ascending: YES] autorelease];
692        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
693
694        NSArray * tempTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
695        [descriptors release];
696
697        int i;
698        for (i = [lowestOrderValue intValue]; i < [tempTorrents count]; i++)
699            [[tempTorrents objectAtIndex: i] setOrderValue: i];
700    }
701   
702    [self torrentNumberChanged];
703    [fTableView deselectAll: nil];
704    [self updateUI: nil];
705    [self updateTorrentHistory];
706}
707
708- (void) removeNoDelete: (id) sender
709{
710    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
711                deleteData: NO deleteTorrent: NO];
712}
713
714- (void) removeDeleteData: (id) sender
715{
716    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
717                deleteData: YES deleteTorrent: NO];
718}
719
720- (void) removeDeleteTorrent: (id) sender
721{
722    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
723                deleteData: NO deleteTorrent: YES];
724}
725
726- (void) removeDeleteDataAndTorrent: (id) sender
727{
728    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
729                deleteData: YES deleteTorrent: YES];
730}
731
732- (void) copyTorrentFile: (id) sender
733{
734    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
735            [self torrentsAtIndexes: [fTableView selectedRowIndexes]]]];
736}
737
738- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
739{
740    if ([torrents count] == 0)
741    {
742        [torrents release];
743        return;
744    }
745
746    Torrent * torrent = [torrents objectAtIndex: 0];
747
748    //warn user if torrent file can't be found
749    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
750    {
751        NSAlert * alert = [[NSAlert alloc] init];
752        [alert addButtonWithTitle: @"OK"];
753        [alert setMessageText: [NSString stringWithFormat:
754                @"Copy of \"%@\" Cannot Be Created", [torrent name]]];
755        [alert setInformativeText: [NSString stringWithFormat:
756                @"The torrent file (%@) cannot be found.", [torrent torrentLocation]]];
757        [alert setAlertStyle: NSWarningAlertStyle];
758       
759        [alert runModal];
760       
761        [torrents removeObjectAtIndex: 0];
762        [self copyTorrentFileForTorrents: torrents];
763    }
764    else
765    {
766        NSSavePanel * panel = [NSSavePanel savePanel];
767        [panel setRequiredFileType: @"torrent"];
768        [panel setCanSelectHiddenExtension: YES];
769       
770        [panel beginSheetForDirectory: nil file: [torrent name]
771            modalForWindow: fWindow modalDelegate: self didEndSelector:
772            @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
773    }
774}
775
776- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code
777    contextInfo: (NSMutableArray *) torrents
778{
779    //if save successful, copy torrent to new location with name of data file
780    if (code == NSOKButton)
781        [[NSFileManager defaultManager] copyPath: [[torrents objectAtIndex: 0] torrentLocation]
782                toPath: [panel filename] handler: nil];
783   
784    [torrents removeObjectAtIndex: 0];
785    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:)
786                withObject: torrents waitUntilDone: NO];
787}
788
789- (void) revealFile: (id) sender
790{
791    NSIndexSet * indexSet = [fTableView selectedRowIndexes];
792    unsigned int i;
793   
794    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
795        [[fFilteredTorrents objectAtIndex: i] revealData];
796}
797
798- (void) showPreferenceWindow: (id) sender
799{
800    NSWindow * window = [fPrefsController window];
801    if (![window isVisible])
802        [window center];
803
804    [window makeKeyAndOrderFront: nil];
805}
806
807- (void) showInfo: (id) sender
808{
809    if ([[fInfoController window] isVisible])
810        [fInfoController close];
811    else
812    {
813        [fInfoController updateInfoStats];
814        [[fInfoController window] orderFront: nil];
815    }
816}
817
818- (void) setInfoTab: (id) sender
819{
820    if (sender == fNextInfoTabItem)
821        [fInfoController setNextTab];
822    else
823        [fInfoController setPreviousTab];
824}
825
826- (void) updateControlTint: (NSNotification *) notification
827{
828    [fSpeedLimitButton setAlternateImage: [fDefaults integerForKey: @"AppleAquaColorVariant"] == NSBlueControlTint
829            ? [NSImage imageNamed: @"SpeedLimitButtonPressedBlue.png"]
830            : [NSImage imageNamed: @"SpeedLimitButtonPressedGraphite.png"]];
831}
832
833- (void) updateUI: (NSTimer *) t
834{
835    NSEnumerator * enumerator = [fTorrents objectEnumerator];
836    Torrent * torrent;
837    while ((torrent = [enumerator nextObject]))
838    {
839        [torrent update];
840
841        if ([torrent justFinished])
842        {
843            [self applyFilter: nil];
844            [self checkToStartWaiting: torrent];
845       
846            [GrowlApplicationBridge notifyWithTitle: @"Download Complete"
847                description: [torrent name] notificationName: @"Download Complete" iconData: nil
848                priority: 0 isSticky: NO clickContext: nil];
849
850            if (![fWindow isKeyWindow])
851                fCompleted++;
852        }
853    }
854
855    if ([fSortType isEqualToString: @"Progress"] || [fSortType isEqualToString: @"State"])
856        [self sortTorrents];
857    else
858        [fTableView reloadData];
859   
860    //update the global DL/UL rates
861    float downloadRate, uploadRate;
862    tr_torrentRates(fLib, & downloadRate, & uploadRate);
863    if (fStatusBarVisible)
864    {
865        [fTotalDLField setStringValue: [NSString stringForSpeed: downloadRate]];
866        [fTotalULField setStringValue: [NSString stringForSpeed: uploadRate]];
867    }
868
869    if ([[fInfoController window] isVisible])
870        [fInfoController updateInfoStats];
871
872    //badge dock
873    [fBadger updateBadgeWithCompleted: fCompleted
874        uploadRate: uploadRate downloadRate: downloadRate];
875}
876
877- (void) updateTorrentHistory
878{
879    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
880
881    NSEnumerator * enumerator = [fTorrents objectEnumerator];
882    Torrent * torrent;
883    while ((torrent = [enumerator nextObject]))
884        [history addObject: [torrent history]];
885
886    [fDefaults setObject: history forKey: @"History"];
887    [fDefaults synchronize];
888}
889
890- (void) sortTorrents
891{
892    //remember selected rows if needed
893    NSArray * selectedTorrents = nil;
894    int numSelected = [fTableView numberOfSelectedRows];
895    if (numSelected > 0 && numSelected < [fFilteredTorrents count])
896        selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
897
898    [self sortTorrentsIgnoreSelected]; //actually sort
899   
900    //set selected rows if needed
901    if (selectedTorrents)
902    {
903        Torrent * torrent;
904        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
905        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
906        while ((torrent = [enumerator nextObject]))
907            [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
908       
909        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
910        [indexSet release];
911    }
912}
913
914- (void) sortTorrentsIgnoreSelected
915{
916    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:
917                                            @"name" ascending: YES] autorelease],
918                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
919                                            @"orderValue" ascending: YES] autorelease];
920
921    NSArray * descriptors;
922    if ([fSortType isEqualToString: @"Name"])
923        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
924    else if ([fSortType isEqualToString: @"State"])
925    {
926        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
927                                                @"stateSortKey" ascending: NO] autorelease],
928                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
929                                            @"progressSortKey" ascending: NO] autorelease];
930       
931        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
932                                                            nameDescriptor, orderDescriptor, nil];
933    }
934    else if ([fSortType isEqualToString: @"Progress"])
935    {
936        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
937                                            @"progressSortKey" ascending: YES] autorelease];
938       
939        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
940    }
941    else if ([fSortType isEqualToString: @"Date"])
942    {
943        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
944                                            @"date" ascending: YES] autorelease];
945   
946        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
947    }
948    else
949        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
950
951    [fFilteredTorrents sortUsingDescriptors: descriptors];
952    [descriptors release];
953   
954    [fTableView reloadData];
955}
956
957- (void) setSort: (id) sender
958{
959    NSMenuItem * prevSortItem;
960    if ([fSortType isEqualToString: @"Name"])
961        prevSortItem = fNameSortItem;
962    else if ([fSortType isEqualToString: @"State"])
963        prevSortItem = fStateSortItem;
964    else if ([fSortType isEqualToString: @"Progress"])
965        prevSortItem = fProgressSortItem;
966    else if ([fSortType isEqualToString: @"Date"])
967        prevSortItem = fDateSortItem;
968    else
969        prevSortItem = fOrderSortItem;
970   
971    if (sender != prevSortItem)
972    {
973        [prevSortItem setState: NSOffState];
974        [sender setState: NSOnState];
975
976        [fSortType release];
977        if (sender == fNameSortItem)
978            fSortType = [[NSString alloc] initWithString: @"Name"];
979        else if (sender == fStateSortItem)
980            fSortType = [[NSString alloc] initWithString: @"State"];
981        else if (sender == fProgressSortItem)
982            fSortType = [[NSString alloc] initWithString: @"Progress"];
983        else if (sender == fDateSortItem)
984            fSortType = [[NSString alloc] initWithString: @"Date"];
985        else
986            fSortType = [[NSString alloc] initWithString: @"Order"];
987           
988        [fDefaults setObject: fSortType forKey: @"Sort"];
989    }
990
991    [self sortTorrents];
992}
993
994- (void) applyFilter: (id) sender
995{
996    //remember selected rows if needed
997    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
998                ? [self torrentsAtIndexes: [fTableView selectedRowIndexes]] : nil;
999
1000    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1001
1002    if ([fFilterType isEqualToString: @"Pause"])
1003    {
1004        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1005        Torrent * torrent;
1006        while ((torrent = [enumerator nextObject]))
1007            if (![torrent isActive])
1008                [tempTorrents addObject: torrent];
1009    }
1010    else if ([fFilterType isEqualToString: @"Seed"])
1011    {
1012        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1013        Torrent * torrent;
1014        while ((torrent = [enumerator nextObject]))
1015            if ([torrent isActive] && [torrent progress] >= 1.0)
1016                [tempTorrents addObject: torrent];
1017    }
1018    else if ([fFilterType isEqualToString: @"Download"])
1019    {
1020        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1021        Torrent * torrent;
1022        while ((torrent = [enumerator nextObject]))
1023            if ([torrent isActive] && [torrent progress] < 1.0)
1024                [tempTorrents addObject: torrent];
1025    }
1026    else
1027        [tempTorrents setArray: fTorrents];
1028   
1029    NSString * searchString = [fSearchFilterField stringValue];
1030    if (![searchString isEqualToString: @""])
1031    {
1032        int i;
1033        for (i = [tempTorrents count] - 1; i >= 0; i--)
1034            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1035                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1036                [tempTorrents removeObjectAtIndex: i];
1037    }
1038   
1039    [fFilteredTorrents setArray: tempTorrents];
1040    [tempTorrents release];
1041   
1042    [self sortTorrentsIgnoreSelected];
1043   
1044    //set selected rows if needed
1045    if (selectedTorrents)
1046    {
1047        Torrent * torrent;
1048        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1049        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1050        unsigned index;
1051        while ((torrent = [enumerator nextObject]))
1052            if ((index = [fFilteredTorrents indexOfObject: torrent]) != NSNotFound)
1053                [indexSet addIndex: index];
1054       
1055        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1056        [indexSet release];
1057    }
1058}
1059
1060//resets filter and sorts torrents
1061- (void) setFilter: (id) sender
1062{
1063    BarButton * prevFilterButton;
1064    if ([fFilterType isEqualToString: @"Pause"])
1065        prevFilterButton = fPauseFilterButton;
1066    else if ([fFilterType isEqualToString: @"Seed"])
1067        prevFilterButton = fSeedFilterButton;
1068    else if ([fFilterType isEqualToString: @"Download"])
1069        prevFilterButton = fDownloadFilterButton;
1070    else
1071        prevFilterButton = fNoFilterButton;
1072   
1073    if (sender != prevFilterButton)
1074    {
1075        [prevFilterButton setEnabled: NO];
1076        [sender setEnabled: YES];
1077
1078        [fFilterType release];
1079        if (sender == fDownloadFilterButton)
1080            fFilterType = [[NSString alloc] initWithString: @"Download"];
1081        else if (sender == fPauseFilterButton)
1082            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1083        else if (sender == fSeedFilterButton)
1084            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1085        else
1086            fFilterType = [[NSString alloc] initWithString: @"None"];
1087
1088        [fDefaults setObject: fFilterType forKey: @"Filter"];
1089    }
1090
1091    [self applyFilter: nil];
1092}
1093
1094- (void) toggleSpeedLimit: (id) sender
1095{
1096    int state = [fSpeedLimitItem state] ? NSOffState : NSOnState;
1097
1098    [fSpeedLimitItem setState: state];
1099    [fSpeedLimitDockItem setState: state];
1100    [fSpeedLimitButton setState: state];
1101   
1102    [fPrefsController enableSpeedLimit: state];
1103}
1104
1105- (void) setLimitGlobalEnabled: (id) sender
1106{
1107    [fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
1108        type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem) ? @"Upload" : @"Download"];
1109}
1110
1111- (void) setQuickLimitGlobal: (id) sender
1112{
1113    [fPrefsController setQuickLimit: [[sender title] intValue]
1114        type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
1115}
1116
1117- (void) limitGlobalChange: (NSNotification *) notification
1118{
1119    NSDictionary * dict = [notification object];
1120   
1121    NSMenuItem * limitItem, * noLimitItem;
1122    if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
1123    {
1124        limitItem = fUploadLimitItem;
1125        noLimitItem = fUploadNoLimitItem;
1126    }
1127    else
1128    {
1129        limitItem = fDownloadLimitItem;
1130        noLimitItem = fDownloadNoLimitItem;
1131    }
1132   
1133    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1134    [limitItem setState: enable ? NSOnState : NSOffState];
1135    [noLimitItem setState: !enable ? NSOnState : NSOffState];
1136   
1137    [limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
1138                            [[dict objectForKey: @"Limit"] intValue]]];
1139
1140    [dict release];
1141}
1142
1143- (void) setRatioGlobalEnabled: (id) sender
1144{
1145    [fPrefsController setRatioEnabled: sender == fRatioSetItem];
1146}
1147
1148- (void) setQuickRatioGlobal: (id) sender
1149{
1150    [fPrefsController setQuickRatio: [[sender title] floatValue]];
1151}
1152
1153- (void) ratioGlobalChange: (NSNotification *) notification
1154{
1155    NSDictionary * dict = [notification object];
1156   
1157    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1158    [fRatioSetItem setState: enable ? NSOnState : NSOffState];
1159    [fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
1160   
1161    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
1162                            [[dict objectForKey: @"Ratio"] floatValue]]];
1163
1164    [dict release];
1165}
1166
1167- (void) checkWaitingForStopped: (NSNotification *) notification
1168{
1169    [self checkToStartWaiting: [notification object]];
1170}
1171
1172- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1173{
1174    //don't try to start a transfer if there should be none waiting
1175    if (![[fDefaults stringForKey: @"StartSetting"] isEqualToString: @"Wait"])
1176        return;
1177
1178    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1179   
1180    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1181    Torrent * torrent, * torrentToStart = nil;
1182    while ((torrent = [enumerator nextObject]))
1183    {
1184        //ignore the torrent just stopped
1185        if (torrent == finishedTorrent)
1186            continue;
1187   
1188        if ([torrent isActive])
1189        {
1190            if (![torrent isSeeding])
1191            {
1192                desiredActive--;
1193                if (desiredActive <= 0)
1194                    return;
1195            }
1196        }
1197        else
1198        {
1199            //use as next if it is waiting to start and either no previous or order value is lower
1200            if ([torrent waitingToStart] && (!torrentToStart
1201                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1202                torrentToStart = torrent;
1203        }
1204    }
1205   
1206    //since it hasn't returned, the queue amount has not been met
1207    if (torrentToStart)
1208    {
1209        [torrentToStart startTransfer];
1210       
1211        [self applyFilter: nil];
1212        [self updateUI: nil];
1213        [fInfoController updateInfoStatsAndSettings];
1214        [self updateTorrentHistory];
1215    }
1216}
1217
1218- (void) torrentStartSettingChange: (NSNotification *) notification
1219{
1220    [self attemptToStartMultipleAuto: [notification object]];
1221
1222    [self applyFilter: nil];
1223    [self updateUI: nil];
1224    [fInfoController updateInfoStatsAndSettings];
1225    [self updateTorrentHistory];
1226}
1227
1228- (void) globalStartSettingChange: (NSNotification *) notification
1229{
1230    [self attemptToStartMultipleAuto: fTorrents];
1231   
1232    [self applyFilter: nil];
1233    [self updateUI: nil];
1234    [fInfoController updateInfoStatsAndSettings];
1235    [self updateTorrentHistory];
1236}
1237
1238- (void) torrentStoppedForRatio: (NSNotification *) notification
1239{
1240    [self applyFilter: nil];
1241    [fInfoController updateInfoStatsAndSettings];
1242   
1243    [GrowlApplicationBridge notifyWithTitle: @"Seeding Complete"
1244                description: [[notification object] name] notificationName: @"Seeding Complete"
1245                iconData: nil priority: 0 isSticky: NO clickContext: nil];
1246}
1247
1248- (void) attemptToStartAuto: (Torrent *) torrent
1249{
1250    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1251}
1252
1253//will try to start, taking into consideration the start preference
1254- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1255{
1256    NSString * startSetting = [fDefaults stringForKey: @"StartSetting"];
1257    if ([startSetting isEqualToString: @"Start"])
1258    {
1259        NSEnumerator * enumerator = [torrents objectEnumerator];
1260        Torrent * torrent;
1261        while ((torrent = [enumerator nextObject]))
1262            if ([torrent waitingToStart])
1263                [torrent startTransfer];
1264       
1265        return;
1266    }
1267    else if (![startSetting isEqualToString: @"Wait"])
1268        return;
1269    else;
1270   
1271    //determine the number of downloads needed to start
1272    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1273           
1274    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1275    Torrent * torrent;
1276    while ((torrent = [enumerator nextObject]))
1277        if ([torrent isActive] && ![torrent isSeeding])
1278        {
1279            desiredActive--;
1280            if (desiredActive <= 0)
1281                break;
1282        }
1283   
1284    //sort torrents by order value
1285    NSArray * sortedTorrents;
1286    if ([torrents count] > 1 && desiredActive > 0)
1287    {
1288        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1289                                                    @"orderValue" ascending: YES] autorelease];
1290        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1291       
1292        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1293        [descriptors release];
1294    }
1295    else
1296        sortedTorrents = torrents;
1297
1298    enumerator = [sortedTorrents objectEnumerator];
1299    while ((torrent = [enumerator nextObject]))
1300    {
1301        if ([torrent progress] >= 1.0)
1302            [torrent startTransfer];
1303        else
1304        {
1305            if ([torrent waitingToStart] && desiredActive > 0)
1306            {
1307                [torrent startTransfer];
1308                desiredActive--;
1309            }
1310        }
1311       
1312        [torrent update];
1313    }
1314}
1315
1316- (void) reloadInspectorSettings: (NSNotification *) notification
1317{
1318    [fInfoController updateInfoStatsAndSettings];
1319}
1320
1321- (void) checkAutoImportDirectory: (NSTimer *) timer
1322{
1323    if (![fDefaults boolForKey: @"AutoImport"])
1324        return;
1325       
1326    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1327   
1328    //if folder cannot be found or the contents hasn't changed simply give up
1329    NSArray * allFileNames;
1330    if (!(allFileNames = [[NSFileManager defaultManager] directoryContentsAtPath: path])
1331            || [allFileNames isEqualToArray: fAutoImportedNames])
1332        return;
1333
1334    //try to add files that haven't already been added
1335    NSMutableArray * newFileNames = [NSMutableArray arrayWithArray: allFileNames];
1336    [newFileNames removeObjectsInArray: fAutoImportedNames];
1337   
1338    //save the current list of files
1339    [fAutoImportedNames setArray: allFileNames];
1340   
1341    NSEnumerator * enumerator = [newFileNames objectEnumerator];
1342    NSString * file;
1343    unsigned oldCount;
1344    while ((file = [enumerator nextObject]))
1345        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1346        {
1347            oldCount = [fTorrents count];
1348            [self openFromSheet: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1349           
1350            //import only actually happened if the torrent array is larger
1351            if (oldCount < [fTorrents count])
1352                [GrowlApplicationBridge notifyWithTitle: @"Torrent File Auto Added"
1353                    description: file notificationName: @"Torrent Auto Added" iconData: nil
1354                    priority: 0 isSticky: NO clickContext: nil];
1355        }
1356}
1357
1358- (void) autoImportChange: (NSNotification *) notification
1359{
1360    [fAutoImportedNames removeAllObjects];
1361    [self checkAutoImportDirectory: nil];
1362}
1363
1364- (int) numberOfRowsInTableView: (NSTableView *) t
1365{
1366    return [fFilteredTorrents count];
1367}
1368
1369- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
1370    forTableColumn: (NSTableColumn *) tableColumn row: (int) row
1371{
1372    [cell setTorrent: [fFilteredTorrents objectAtIndex: row]];
1373}
1374
1375- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1376    toPasteboard: (NSPasteboard *) pasteboard
1377{
1378    //only allow reordering of rows if sorting by order with no filter
1379    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"])
1380    {
1381        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1382        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1383                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1384        return YES;
1385    }
1386    return NO;
1387}
1388
1389- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1390    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1391{
1392    NSPasteboard * pasteboard = [info draggingPasteboard];
1393    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1394    {
1395        //check if any files to add have "torrent" as an extension
1396        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1397        NSString * file;
1398        while ((file = [enumerator nextObject]))
1399            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1400            {
1401                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1402                return NSDragOperationGeneric;
1403            }
1404    }
1405    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1406    {
1407        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1408        return NSDragOperationGeneric;
1409    }
1410    else;
1411   
1412    return NSDragOperationNone;
1413}
1414
1415- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1416    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1417{
1418    NSPasteboard * pasteboard = [info draggingPasteboard];
1419    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1420    {
1421        //create an array of files with the "torrent" extension
1422        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1423        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1424        NSString * file;
1425        while ((file = [enumerator nextObject]))
1426            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1427                [filesToOpen addObject: file];
1428   
1429        [self application: NSApp openFiles: filesToOpen];
1430        [filesToOpen release];
1431    }
1432    else
1433    {
1434        //remember selected rows if needed
1435        NSArray * selectedTorrents = nil;
1436        int numSelected = [fTableView numberOfSelectedRows];
1437        if (numSelected > 0 && numSelected < [fFilteredTorrents count])
1438            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1439   
1440        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1441                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1442       
1443        //move torrent in array
1444        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1445        [fFilteredTorrents removeObjectsInArray: movingTorrents];
1446       
1447        //determine the insertion index now that transfers to move have been removed
1448        int i, decrease = 0;
1449        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1450            decrease++;
1451       
1452        //insert objects at new location
1453        for (i = 0; i < [movingTorrents count]; i++)
1454            [fFilteredTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1455       
1456        [movingTorrents release];
1457       
1458        //redo order values
1459        int low = [indexes firstIndex], high = [indexes lastIndex];
1460        if (newRow < low)
1461            low = newRow;
1462        else if (newRow > high + 1)
1463            high = newRow - 1;
1464        else;
1465       
1466        for (i = low; i <= high; i++)
1467            [[fFilteredTorrents objectAtIndex: i] setOrderValue: i];
1468       
1469        [fTableView reloadData];
1470       
1471        //set selected rows if needed
1472        if (selectedTorrents)
1473        {
1474            Torrent * torrent;
1475            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1476            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1477            while ((torrent = [enumerator nextObject]))
1478                [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
1479           
1480            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1481            [indexSet release];
1482        }
1483    }
1484   
1485    return YES;
1486}
1487
1488- (void) tableViewSelectionDidChange: (NSNotification *) notification
1489{
1490    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1491}
1492
1493- (void) toggleSmallView: (id) sender
1494{
1495    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
1496   
1497    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1498    [fSmallViewItem setState: makeSmall];
1499   
1500    [fDefaults setBool: makeSmall forKey: @"SmallView"];
1501   
1502    //window min height
1503    NSSize contentMinSize = [fWindow contentMinSize],
1504            contentSize = [[fWindow contentView] frame].size;
1505    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1506                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1507    [fWindow setContentMinSize: contentMinSize];
1508   
1509    //resize for larger min height
1510    if (!makeSmall && contentSize.height < contentMinSize.height)
1511    {
1512        NSRect frame = [fWindow frame];
1513        float heightChange = contentMinSize.height - contentSize.height;
1514        frame.size.height += heightChange;
1515        frame.origin.y -= heightChange;
1516       
1517        [fWindow setFrame: frame display: YES];
1518        [fTableView reloadData];
1519    }
1520}
1521
1522- (void) toggleStatusBar: (id) sender
1523{
1524    [self showStatusBar: !fStatusBarVisible animate: YES];
1525    [fDefaults setBool: fStatusBarVisible forKey: @"StatusBar"];
1526}
1527
1528- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1529{
1530    if (show == fStatusBarVisible)
1531        return;
1532
1533    NSRect frame = [fWindow frame];
1534    float heightChange = [fStatusBar frame].size.height;
1535    if (!show)
1536        heightChange *= -1;
1537
1538    frame.size.height += heightChange;
1539    frame.origin.y -= heightChange;
1540       
1541    fStatusBarVisible = !fStatusBarVisible;
1542   
1543    [self updateUI: nil];
1544   
1545    //set views to not autoresize
1546    unsigned int statsMask = [fStatusBar autoresizingMask];
1547    unsigned int filterMask = [fFilterBar autoresizingMask];
1548    unsigned int scrollMask = [fScrollView autoresizingMask];
1549    [fStatusBar setAutoresizingMask: 0];
1550    [fFilterBar setAutoresizingMask: 0];
1551    [fScrollView setAutoresizingMask: 0];
1552   
1553    [fWindow setFrame: frame display: YES animate: animate];
1554   
1555    //re-enable autoresize
1556    [fStatusBar setAutoresizingMask: statsMask];
1557    [fFilterBar setAutoresizingMask: filterMask];
1558    [fScrollView setAutoresizingMask: scrollMask];
1559   
1560    //change min size
1561    NSSize minSize = [fWindow contentMinSize];
1562    minSize.height += heightChange;
1563    [fWindow setContentMinSize: minSize];
1564   
1565    //reset tracking rects for filter buttons
1566    [fNoFilterButton resetBounds: nil];
1567    [fSeedFilterButton resetBounds: nil];
1568    [fDownloadFilterButton resetBounds: nil];
1569    [fPauseFilterButton resetBounds: nil];
1570}
1571
1572- (void) toggleFilterBar: (id) sender
1573{
1574    if (!fFilterBarVisible)
1575        [fSearchFilterField setEnabled: YES];
1576
1577    [self showFilterBar: !fFilterBarVisible animate: YES];
1578    [fDefaults setBool: fFilterBarVisible forKey: @"FilterBar"];
1579   
1580    //disable filtering when hiding
1581    if (!fFilterBarVisible)
1582    {
1583        [fSearchFilterField setEnabled: NO];
1584        [fSearchFilterField setStringValue: @""];
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) linkHomepage: (id) sender
2036{
2037    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2038}
2039
2040- (void) linkForums: (id) sender
2041{
2042    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2043}
2044
2045- (void) checkUpdate: (id) sender
2046{
2047    [fPrefsController checkUpdate];
2048}
2049
2050- (void) prepareForUpdate: (NSNotification *) notification
2051{
2052    fUpdateInProgress = YES;
2053}
2054
2055- (NSDictionary *) registrationDictionaryForGrowl
2056{
2057    NSArray * notifications = [NSArray arrayWithObjects: @"Download Complete",
2058                                @"Seeding Complete", @"Torrent Auto Added", nil];
2059    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2060                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2061}
2062
2063@end
Note: See TracBrowser for help on using the repository browser.