source: trunk/macosx/Controller.m @ 606

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

Blue turtle for aqua, gray turtle for graphite.

  • Property svn:keywords set to Date Rev Author Id
File size: 69.4 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 606 2006-07-16 15:14:53Z 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];
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];
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];
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];
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];
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
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    [fFilteredTorrents setArray: tempTorrents];
1030    [tempTorrents release];
1031   
1032    [self sortTorrentsIgnoreSelected];
1033   
1034    //set selected rows if needed
1035    if (selectedTorrents)
1036    {
1037        Torrent * torrent;
1038        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1039        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1040        unsigned index;
1041        while ((torrent = [enumerator nextObject]))
1042            if ((index = [fFilteredTorrents indexOfObject: torrent]) != NSNotFound)
1043                [indexSet addIndex: index];
1044       
1045        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1046        [indexSet release];
1047    }
1048}
1049
1050//resets filter and sorts torrents
1051- (void) setFilter: (id) sender
1052{
1053    BarButton * prevFilterButton;
1054    if ([fFilterType isEqualToString: @"Pause"])
1055        prevFilterButton = fPauseFilterButton;
1056    else if ([fFilterType isEqualToString: @"Seed"])
1057        prevFilterButton = fSeedFilterButton;
1058    else if ([fFilterType isEqualToString: @"Download"])
1059        prevFilterButton = fDownloadFilterButton;
1060    else
1061        prevFilterButton = fNoFilterButton;
1062   
1063    if (sender != prevFilterButton)
1064    {
1065        [prevFilterButton setEnabled: NO];
1066        [sender setEnabled: YES];
1067
1068        [fFilterType release];
1069        if (sender == fDownloadFilterButton)
1070            fFilterType = [[NSString alloc] initWithString: @"Download"];
1071        else if (sender == fPauseFilterButton)
1072            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1073        else if (sender == fSeedFilterButton)
1074            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1075        else
1076            fFilterType = [[NSString alloc] initWithString: @"None"];
1077
1078        [fDefaults setObject: fFilterType forKey: @"Filter"];
1079    }
1080
1081    [self applyFilter];
1082}
1083
1084- (void) toggleSpeedLimit: (id) sender
1085{
1086    int state = [fSpeedLimitItem state] ? NSOffState : NSOnState;
1087
1088    [fSpeedLimitItem setState: state];
1089    [fSpeedLimitDockItem setState: state];
1090    [fSpeedLimitButton setState: state];
1091   
1092    [fPrefsController enableSpeedLimit: state];
1093}
1094
1095- (void) setLimitGlobalEnabled: (id) sender
1096{
1097    [fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
1098        type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem) ? @"Upload" : @"Download"];
1099}
1100
1101- (void) setQuickLimitGlobal: (id) sender
1102{
1103    [fPrefsController setQuickLimit: [[sender title] intValue]
1104        type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
1105}
1106
1107- (void) limitGlobalChange: (NSNotification *) notification
1108{
1109    NSDictionary * dict = [notification object];
1110   
1111    NSMenuItem * limitItem, * noLimitItem;
1112    if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
1113    {
1114        limitItem = fUploadLimitItem;
1115        noLimitItem = fUploadNoLimitItem;
1116    }
1117    else
1118    {
1119        limitItem = fDownloadLimitItem;
1120        noLimitItem = fDownloadNoLimitItem;
1121    }
1122   
1123    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1124    [limitItem setState: enable ? NSOnState : NSOffState];
1125    [noLimitItem setState: !enable ? NSOnState : NSOffState];
1126   
1127    [limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
1128                            [[dict objectForKey: @"Limit"] intValue]]];
1129
1130    [dict release];
1131}
1132
1133- (void) setRatioGlobalEnabled: (id) sender
1134{
1135    [fPrefsController setRatioEnabled: sender == fRatioSetItem];
1136}
1137
1138- (void) setQuickRatioGlobal: (id) sender
1139{
1140    [fPrefsController setQuickRatio: [[sender title] floatValue]];
1141}
1142
1143- (void) ratioGlobalChange: (NSNotification *) notification
1144{
1145    NSDictionary * dict = [notification object];
1146   
1147    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1148    [fRatioSetItem setState: enable ? NSOnState : NSOffState];
1149    [fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
1150   
1151    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
1152                            [[dict objectForKey: @"Ratio"] floatValue]]];
1153
1154    [dict release];
1155}
1156
1157- (void) checkWaitingForStopped: (NSNotification *) notification
1158{
1159    [self checkToStartWaiting: [notification object]];
1160}
1161
1162- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1163{
1164    //don't try to start a transfer if there should be none waiting
1165    if (![[fDefaults stringForKey: @"StartSetting"] isEqualToString: @"Wait"])
1166        return;
1167
1168    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1169   
1170    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1171    Torrent * torrent, * torrentToStart = nil;
1172    while ((torrent = [enumerator nextObject]))
1173    {
1174        //ignore the torrent just stopped
1175        if (torrent == finishedTorrent)
1176            continue;
1177   
1178        if ([torrent isActive])
1179        {
1180            if (![torrent isSeeding])
1181            {
1182                desiredActive--;
1183                if (desiredActive <= 0)
1184                    return;
1185            }
1186        }
1187        else
1188        {
1189            //use as next if it is waiting to start and either no previous or order value is lower
1190            if ([torrent waitingToStart] && (!torrentToStart
1191                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1192                torrentToStart = torrent;
1193        }
1194    }
1195   
1196    //since it hasn't returned, the queue amount has not been met
1197    if (torrentToStart)
1198    {
1199        [torrentToStart startTransfer];
1200       
1201        [self applyFilter];
1202        [self updateUI: nil];
1203        [fInfoController updateInfoStatsAndSettings];
1204        [self updateTorrentHistory];
1205    }
1206}
1207
1208- (void) torrentStartSettingChange: (NSNotification *) notification
1209{
1210    [self attemptToStartMultipleAuto: [notification object]];
1211
1212    [self applyFilter];
1213    [self updateUI: nil];
1214    [fInfoController updateInfoStatsAndSettings];
1215    [self updateTorrentHistory];
1216}
1217
1218- (void) globalStartSettingChange: (NSNotification *) notification
1219{
1220    [self attemptToStartMultipleAuto: fTorrents];
1221   
1222    [self applyFilter];
1223    [self updateUI: nil];
1224    [fInfoController updateInfoStatsAndSettings];
1225    [self updateTorrentHistory];
1226}
1227
1228- (void) torrentStoppedForRatio: (NSNotification *) notification
1229{
1230    [self applyFilter];
1231    [fInfoController updateInfoStatsAndSettings];
1232   
1233    [GrowlApplicationBridge notifyWithTitle: @"Seeding Complete"
1234                description: [[notification object] name] notificationName: @"Seeding Complete"
1235                iconData: nil priority: 0 isSticky: NO clickContext: nil];
1236}
1237
1238- (void) attemptToStartAuto: (Torrent *) torrent
1239{
1240    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1241}
1242
1243//will try to start, taking into consideration the start preference
1244- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1245{
1246    NSString * startSetting = [fDefaults stringForKey: @"StartSetting"];
1247    if ([startSetting isEqualToString: @"Start"])
1248    {
1249        NSEnumerator * enumerator = [torrents objectEnumerator];
1250        Torrent * torrent;
1251        while ((torrent = [enumerator nextObject]))
1252            if ([torrent waitingToStart])
1253                [torrent startTransfer];
1254       
1255        return;
1256    }
1257    else if (![startSetting isEqualToString: @"Wait"])
1258        return;
1259    else;
1260   
1261    //determine the number of downloads needed to start
1262    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1263           
1264    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1265    Torrent * torrent;
1266    while ((torrent = [enumerator nextObject]))
1267        if ([torrent isActive] && ![torrent isSeeding])
1268        {
1269            desiredActive--;
1270            if (desiredActive <= 0)
1271                break;
1272        }
1273   
1274    //sort torrents by order value
1275    NSArray * sortedTorrents;
1276    if ([torrents count] > 1 && desiredActive > 0)
1277    {
1278        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1279                                                    @"orderValue" ascending: YES] autorelease];
1280        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1281       
1282        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1283        [descriptors release];
1284    }
1285    else
1286        sortedTorrents = torrents;
1287
1288    enumerator = [sortedTorrents objectEnumerator];
1289    while ((torrent = [enumerator nextObject]))
1290    {
1291        if ([torrent progress] >= 1.0)
1292            [torrent startTransfer];
1293        else
1294        {
1295            if ([torrent waitingToStart] && desiredActive > 0)
1296            {
1297                [torrent startTransfer];
1298                desiredActive--;
1299            }
1300        }
1301       
1302        [torrent update];
1303    }
1304}
1305
1306- (void) reloadInspectorSettings: (NSNotification *) notification
1307{
1308    [fInfoController updateInfoStatsAndSettings];
1309}
1310
1311- (void) checkAutoImportDirectory: (NSTimer *) timer
1312{
1313    if (![fDefaults boolForKey: @"AutoImport"])
1314        return;
1315       
1316    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1317   
1318    //if folder cannot be found or the contents hasn't changed simply give up
1319    NSArray * allFileNames;
1320    if (!(allFileNames = [[NSFileManager defaultManager] directoryContentsAtPath: path])
1321            || [allFileNames isEqualToArray: fAutoImportedNames])
1322        return;
1323
1324    //try to add files that haven't already been added
1325    NSMutableArray * newFileNames = [NSMutableArray arrayWithArray: allFileNames];
1326    [newFileNames removeObjectsInArray: fAutoImportedNames];
1327   
1328    //save the current list of files
1329    [fAutoImportedNames setArray: allFileNames];
1330   
1331    NSEnumerator * enumerator = [newFileNames objectEnumerator];
1332    NSString * file;
1333    unsigned oldCount;
1334    while ((file = [enumerator nextObject]))
1335        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1336        {
1337            oldCount = [fTorrents count];
1338            [self openFromSheet: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1339           
1340            //import only actually happened if the torrent array is larger
1341            if (oldCount < [fTorrents count])
1342                [GrowlApplicationBridge notifyWithTitle: @"Torrent File Auto Added"
1343                    description: file notificationName: @"Torrent Auto Added" iconData: nil
1344                    priority: 0 isSticky: NO clickContext: nil];
1345        }
1346}
1347
1348- (void) autoImportChange: (NSNotification *) notification
1349{
1350    [fAutoImportedNames removeAllObjects];
1351    [self checkAutoImportDirectory: nil];
1352}
1353
1354- (int) numberOfRowsInTableView: (NSTableView *) t
1355{
1356    return [fFilteredTorrents count];
1357}
1358
1359- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
1360    forTableColumn: (NSTableColumn *) tableColumn row: (int) row
1361{
1362    [cell setTorrent: [fFilteredTorrents objectAtIndex: row]];
1363}
1364
1365- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1366    toPasteboard: (NSPasteboard *) pasteboard
1367{
1368    //only allow reordering of rows if sorting by order with no filter
1369    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"])
1370    {
1371        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1372        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1373                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1374        return YES;
1375    }
1376    return NO;
1377}
1378
1379- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1380    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1381{
1382    NSPasteboard * pasteboard = [info draggingPasteboard];
1383    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1384    {
1385        //check if any files to add have "torrent" as an extension
1386        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1387        NSString * file;
1388        while ((file = [enumerator nextObject]))
1389            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1390            {
1391                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1392                return NSDragOperationGeneric;
1393            }
1394    }
1395    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1396    {
1397        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1398        return NSDragOperationGeneric;
1399    }
1400    else;
1401   
1402    return NSDragOperationNone;
1403}
1404
1405- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1406    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1407{
1408    NSPasteboard * pasteboard = [info draggingPasteboard];
1409    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1410    {
1411        //create an array of files with the "torrent" extension
1412        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1413        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1414        NSString * file;
1415        while ((file = [enumerator nextObject]))
1416            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1417                [filesToOpen addObject: file];
1418   
1419        [self application: NSApp openFiles: filesToOpen];
1420        [filesToOpen release];
1421    }
1422    else
1423    {
1424        //remember selected rows if needed
1425        NSArray * selectedTorrents = nil;
1426        int numSelected = [fTableView numberOfSelectedRows];
1427        if (numSelected > 0 && numSelected < [fFilteredTorrents count])
1428            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1429   
1430        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1431                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1432       
1433        //move torrent in array
1434        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1435        [fFilteredTorrents removeObjectsInArray: movingTorrents];
1436       
1437        //determine the insertion index now that transfers to move have been removed
1438        int i, decrease = 0;
1439        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1440            decrease++;
1441       
1442        //insert objects at new location
1443        for (i = 0; i < [movingTorrents count]; i++)
1444            [fFilteredTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1445       
1446        [movingTorrents release];
1447       
1448        //redo order values
1449        int low = [indexes firstIndex], high = [indexes lastIndex];
1450        if (newRow < low)
1451            low = newRow;
1452        else if (newRow > high + 1)
1453            high = newRow - 1;
1454        else;
1455       
1456        for (i = low; i <= high; i++)
1457            [[fFilteredTorrents objectAtIndex: i] setOrderValue: i];
1458       
1459        [fTableView reloadData];
1460       
1461        //set selected rows if needed
1462        if (selectedTorrents)
1463        {
1464            Torrent * torrent;
1465            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1466            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1467            while ((torrent = [enumerator nextObject]))
1468                [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
1469           
1470            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1471            [indexSet release];
1472        }
1473    }
1474   
1475    return YES;
1476}
1477
1478- (void) tableViewSelectionDidChange: (NSNotification *) notification
1479{
1480    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1481}
1482
1483- (void) toggleSmallView: (id) sender
1484{
1485    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
1486   
1487    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1488    [fSmallViewItem setState: makeSmall];
1489   
1490    [fDefaults setBool: makeSmall forKey: @"SmallView"];
1491   
1492    //window min height
1493    NSSize contentMinSize = [fWindow contentMinSize],
1494            contentSize = [[fWindow contentView] frame].size;
1495    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1496                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1497    [fWindow setContentMinSize: contentMinSize];
1498   
1499    //resize for larger min height
1500    if (!makeSmall && contentSize.height < contentMinSize.height)
1501    {
1502        NSRect frame = [fWindow frame];
1503        float heightChange = contentMinSize.height - contentSize.height;
1504        frame.size.height += heightChange;
1505        frame.origin.y -= heightChange;
1506       
1507        [fWindow setFrame: frame display: YES];
1508        [fTableView reloadData];
1509    }
1510}
1511
1512- (void) toggleStatusBar: (id) sender
1513{
1514    [self showStatusBar: !fStatusBarVisible animate: YES];
1515    [fDefaults setBool: fStatusBarVisible forKey: @"StatusBar"];
1516}
1517
1518- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1519{
1520    if (show == fStatusBarVisible)
1521        return;
1522
1523    NSRect frame = [fWindow frame];
1524    float heightChange = [fStatusBar frame].size.height;
1525    if (!show)
1526        heightChange *= -1;
1527
1528    frame.size.height += heightChange;
1529    frame.origin.y -= heightChange;
1530       
1531    fStatusBarVisible = !fStatusBarVisible;
1532   
1533    [self updateUI: nil];
1534   
1535    //set views to not autoresize
1536    unsigned int statsMask = [fStatusBar autoresizingMask];
1537    unsigned int filterMask = [fFilterBar autoresizingMask];
1538    unsigned int scrollMask = [fScrollView autoresizingMask];
1539    [fStatusBar setAutoresizingMask: 0];
1540    [fFilterBar setAutoresizingMask: 0];
1541    [fScrollView setAutoresizingMask: 0];
1542   
1543    [fWindow setFrame: frame display: YES animate: animate];
1544   
1545    //re-enable autoresize
1546    [fStatusBar setAutoresizingMask: statsMask];
1547    [fFilterBar setAutoresizingMask: filterMask];
1548    [fScrollView setAutoresizingMask: scrollMask];
1549   
1550    //change min size
1551    NSSize minSize = [fWindow contentMinSize];
1552    minSize.height += heightChange;
1553    [fWindow setContentMinSize: minSize];
1554   
1555    //reset tracking rects for filter buttons
1556    [fNoFilterButton resetBounds: nil];
1557    [fSeedFilterButton resetBounds: nil];
1558    [fDownloadFilterButton resetBounds: nil];
1559    [fPauseFilterButton resetBounds: nil];
1560}
1561
1562- (void) toggleFilterBar: (id) sender
1563{
1564    [self showFilterBar: !fFilterBarVisible animate: YES];
1565    [fDefaults setBool: fFilterBarVisible forKey: @"FilterBar"];
1566   
1567    //disable filtering when hiding
1568    if (!fFilterBarVisible)
1569        [self setFilter: fNoFilterButton];
1570}
1571
1572- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1573{
1574    if (show == fFilterBarVisible)
1575        return;
1576
1577    NSRect frame = [fWindow frame];
1578    float heightChange = [fFilterBar frame].size.height;
1579    if (!show)
1580        heightChange *= -1;
1581
1582    frame.size.height += heightChange;
1583    frame.origin.y -= heightChange;
1584       
1585    fFilterBarVisible = !fFilterBarVisible;
1586   
1587    //set views to not autoresize
1588    unsigned int filterMask = [fFilterBar autoresizingMask];
1589    unsigned int scrollMask = [fScrollView autoresizingMask];
1590    [fFilterBar setAutoresizingMask: 0];
1591    [fScrollView setAutoresizingMask: 0];
1592   
1593    [fWindow setFrame: frame display: YES animate: animate];
1594   
1595    //re-enable autoresize
1596    [fFilterBar setAutoresizingMask: filterMask];
1597    [fScrollView setAutoresizingMask: scrollMask];
1598   
1599    //change min size
1600    NSSize minSize = [fWindow contentMinSize];
1601    minSize.height += heightChange;
1602    [fWindow setContentMinSize: minSize];
1603   
1604    //reset tracking rects for filter buttons
1605    [fNoFilterButton resetBounds: nil];
1606    [fSeedFilterButton resetBounds: nil];
1607    [fDownloadFilterButton resetBounds: nil];
1608    [fPauseFilterButton resetBounds: nil];
1609}
1610
1611- (void) toggleAdvancedBar: (id) sender
1612{
1613    int state = ![fAdvancedBarItem state];
1614    [fAdvancedBarItem setState: state];
1615    [fDefaults setBool: state forKey: @"UseAdvancedBar"];
1616
1617    [fTableView display];
1618}
1619
1620- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1621    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1622{
1623    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1624
1625    if ([ident isEqualToString: TOOLBAR_OPEN])
1626    {
1627        [item setLabel: @"Open"];
1628        [item setPaletteLabel: @"Open Torrent Files"];
1629        [item setToolTip: @"Open torrent files"];
1630        [item setImage: [NSImage imageNamed: @"Open.png"]];
1631        [item setTarget: self];
1632        [item setAction: @selector(openShowSheet:)];
1633    }
1634    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1635    {
1636        [item setLabel: @"Remove"];
1637        [item setPaletteLabel: @"Remove Selected"];
1638        [item setToolTip: @"Remove selected transfers"];
1639        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1640        [item setTarget: self];
1641        [item setAction: @selector(removeNoDelete:)];
1642    }
1643    else if ([ident isEqualToString: TOOLBAR_INFO])
1644    {
1645        [item setLabel: @"Inspector"];
1646        [item setPaletteLabel: @"Show/Hide Inspector"];
1647        [item setToolTip: @"Display torrent inspector"];
1648        [item setImage: [NSImage imageNamed: @"Info.png"]];
1649        [item setTarget: self];
1650        [item setAction: @selector(showInfo:)];
1651    }
1652    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1653    {
1654        [item setLabel: @"Pause All"];
1655        [item setPaletteLabel: [item label]];
1656        [item setToolTip: @"Pause all transfers"];
1657        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1658        [item setTarget: self];
1659        [item setAction: @selector(stopAllTorrents:)];
1660    }
1661    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1662    {
1663        [item setLabel: @"Resume All"];
1664        [item setPaletteLabel: [item label]];
1665        [item setToolTip: @"Resume all transfers"];
1666        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1667        [item setTarget: self];
1668        [item setAction: @selector(resumeAllTorrents:)];
1669    }
1670    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1671    {
1672        [item setLabel: @"Pause"];
1673        [item setPaletteLabel: @"Pause Selected"];
1674        [item setToolTip: @"Pause selected transfers"];
1675        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1676        [item setTarget: self];
1677        [item setAction: @selector(stopSelectedTorrents:)];
1678    }
1679    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1680    {
1681        [item setLabel: @"Resume"];
1682        [item setPaletteLabel: @"Resume Selected"];
1683        [item setToolTip: @"Resume selected transfers"];
1684        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1685        [item setTarget: self];
1686        [item setAction: @selector(resumeSelectedTorrents:)];
1687    }
1688    else
1689    {
1690        [item release];
1691        return nil;
1692    }
1693
1694    return item;
1695}
1696
1697- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1698{
1699    return [NSArray arrayWithObjects:
1700            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1701            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1702            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_INFO,
1703            NSToolbarSeparatorItemIdentifier,
1704            NSToolbarSpaceItemIdentifier,
1705            NSToolbarFlexibleSpaceItemIdentifier,
1706            NSToolbarCustomizeToolbarItemIdentifier, nil];
1707}
1708
1709- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1710{
1711    return [NSArray arrayWithObjects:
1712            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1713            NSToolbarSeparatorItemIdentifier,
1714            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1715            NSToolbarFlexibleSpaceItemIdentifier,
1716            TOOLBAR_INFO, nil];
1717}
1718
1719- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1720{
1721    NSString * ident = [toolbarItem itemIdentifier];
1722
1723    //enable remove item
1724    if ([ident isEqualToString: TOOLBAR_REMOVE])
1725        return [fTableView numberOfSelectedRows] > 0;
1726
1727    //enable pause all item
1728    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1729    {
1730        Torrent * torrent;
1731        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1732        while ((torrent = [enumerator nextObject]))
1733            if ([torrent isActive])
1734                return YES;
1735        return NO;
1736    }
1737
1738    //enable resume all item
1739    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1740    {
1741        Torrent * torrent;
1742        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1743        while ((torrent = [enumerator nextObject]))
1744            if ([torrent isPaused])
1745                return YES;
1746        return NO;
1747    }
1748
1749    //enable pause item
1750    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1751    {
1752        Torrent * torrent;
1753        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1754        unsigned int i;
1755       
1756        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1757            if ([[fFilteredTorrents objectAtIndex: i] isActive])
1758                return YES;
1759        return NO;
1760    }
1761   
1762    //enable resume item
1763    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1764    {
1765        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1766        unsigned int i;
1767       
1768        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1769            if ([[fFilteredTorrents objectAtIndex: i] isPaused])
1770                return YES;
1771        return NO;
1772    }
1773
1774    return YES;
1775}
1776
1777- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1778{
1779    SEL action = [menuItem action];
1780
1781    //only enable some items if it is in a context menu or the window is useable
1782    BOOL canUseMenu = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
1783
1784    //enable show info
1785    if (action == @selector(showInfo:))
1786    {
1787        NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
1788        if (![[menuItem title] isEqualToString: title])
1789                [menuItem setTitle: title];
1790
1791        return YES;
1792    }
1793   
1794    //enable prev/next inspector tab
1795    if (action == @selector(setInfoTab:))
1796        return [[fInfoController window] isVisible];
1797   
1798    //enable toggle status bar
1799    if (action == @selector(toggleStatusBar:))
1800    {
1801        NSString * title = fStatusBarVisible ? @"Hide Status Bar" : @"Show Status Bar";
1802        if (![[menuItem title] isEqualToString: title])
1803                [menuItem setTitle: title];
1804
1805        return canUseMenu;
1806    }
1807   
1808    //enable toggle filter bar
1809    if (action == @selector(toggleFilterBar:))
1810    {
1811        NSString * title = fFilterBarVisible ? @"Hide Filter Bar" : @"Show Filter Bar";
1812        if (![[menuItem title] isEqualToString: title])
1813                [menuItem setTitle: title];
1814
1815        return canUseMenu;
1816    }
1817
1818    //enable resume all item
1819    if (action == @selector(resumeAllTorrents:))
1820    {
1821        Torrent * torrent;
1822        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1823        while ((torrent = [enumerator nextObject]))
1824            if ([torrent isPaused])
1825                return YES;
1826        return NO;
1827    }
1828
1829    //enable pause all item
1830    if (action == @selector(stopAllTorrents:))
1831    {
1832        Torrent * torrent;
1833        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1834        while ((torrent = [enumerator nextObject]))
1835            if ([torrent isActive])
1836                return YES;
1837        return NO;
1838    }
1839
1840    //enable reveal in finder
1841    if (action == @selector(revealFile:))
1842        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1843
1844    //enable remove items
1845    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
1846        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
1847    {
1848        BOOL warning = NO,
1849            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
1850            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
1851        Torrent * torrent;
1852        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1853        unsigned int i;
1854       
1855        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1856        {
1857            torrent = [fFilteredTorrents objectAtIndex: i];
1858            if (!warning && [torrent isActive])
1859            {
1860                warning = onlyDownloading ? ![torrent isSeeding] : YES;
1861                if (warning && canDelete)
1862                    break;
1863            }
1864            if (!canDelete && [torrent publicTorrent])
1865            {
1866                canDelete = YES;
1867                if (warning)
1868                    break;
1869            }
1870        }
1871   
1872        //append or remove ellipsis when needed
1873        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
1874        if (warning && [fDefaults boolForKey: @"CheckRemove"])
1875        {
1876            if (![title hasSuffix: ellipsis])
1877                [menuItem setTitle: [title stringByAppendingEllipsis]];
1878        }
1879        else
1880        {
1881            if ([title hasSuffix: ellipsis])
1882                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
1883        }
1884       
1885        return canUseMenu && canDelete && [fTableView numberOfSelectedRows] > 0;
1886    }
1887
1888    //enable pause item
1889    if (action == @selector(stopSelectedTorrents:))
1890    {
1891        if (!canUseMenu)
1892            return NO;
1893   
1894        Torrent * torrent;
1895        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1896        unsigned int i;
1897       
1898        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1899        {
1900            torrent = [fFilteredTorrents objectAtIndex: i];
1901            if ([torrent isActive])
1902                return YES;
1903        }
1904        return NO;
1905    }
1906   
1907    //enable resume item
1908    if (action == @selector(resumeSelectedTorrents:))
1909    {
1910        if (!canUseMenu)
1911            return NO;
1912   
1913        Torrent * torrent;
1914        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1915        unsigned int i;
1916       
1917        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1918        {
1919            torrent = [fFilteredTorrents objectAtIndex: i];
1920            if ([torrent isPaused])
1921                return YES;
1922        }
1923        return NO;
1924    }
1925   
1926    //enable sort and advanced bar items
1927    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:)
1928            || action == @selector(toggleSmallView:))
1929        return canUseMenu;
1930   
1931    //enable copy torrent file item
1932    if (action == @selector(copyTorrentFile:))
1933    {
1934        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1935    }
1936
1937    return YES;
1938}
1939
1940- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
1941{
1942    NSEnumerator * enumerator;
1943    Torrent * torrent;
1944    BOOL active;
1945
1946    switch (messageType)
1947    {
1948        case kIOMessageSystemWillSleep:
1949            //close all connections before going to sleep and remember we should resume when we wake up
1950            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
1951
1952            //wait for running transfers to stop (5 second timeout)
1953            NSDate * start = [NSDate date];
1954            BOOL timeUp = NO;
1955           
1956            NSEnumerator * enumerator = [fTorrents objectEnumerator];
1957            Torrent * torrent;
1958            while (!timeUp && (torrent = [enumerator nextObject]))
1959                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
1960                {
1961                    usleep(100000);
1962                    [torrent update];
1963                }
1964
1965            IOAllowPowerChange(fRootPort, (long) messageArgument);
1966            break;
1967
1968        case kIOMessageCanSystemSleep:
1969            //pevent idle sleep unless all paused
1970            active = NO;
1971            enumerator = [fTorrents objectEnumerator];
1972            while ((torrent = [enumerator nextObject]))
1973                if ([torrent isActive])
1974                {
1975                    active = YES;
1976                    break;
1977                }
1978
1979            if (active)
1980                IOCancelPowerChange(fRootPort, (long) messageArgument);
1981            else
1982                IOAllowPowerChange(fRootPort, (long) messageArgument);
1983            break;
1984
1985        case kIOMessageSystemHasPoweredOn:
1986            //resume sleeping transfers after we wake up
1987            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
1988            break;
1989    }
1990}
1991
1992- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
1993{
1994    NSRect windowRect = [fWindow frame];
1995    float newHeight = windowRect.size.height - [fScrollView frame].size.height
1996        + [fFilteredTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
1997
1998    float minHeight = [fWindow minSize].height;
1999    if (newHeight < minHeight)
2000        newHeight = minHeight;
2001
2002    windowRect.origin.y -= (newHeight - windowRect.size.height);
2003    windowRect.size.height = newHeight;
2004
2005    return windowRect;
2006}
2007
2008- (void) showMainWindow: (id) sender
2009{
2010    [fWindow makeKeyAndOrderFront: nil];
2011}
2012
2013- (void) windowDidBecomeKey: (NSNotification *) notification
2014{
2015    fCompleted = 0;
2016}
2017
2018- (void) linkHomepage: (id) sender
2019{
2020    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2021}
2022
2023- (void) linkForums: (id) sender
2024{
2025    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2026}
2027
2028- (void) checkUpdate: (id) sender
2029{
2030    [fPrefsController checkUpdate];
2031}
2032
2033- (void) prepareForUpdate: (NSNotification *) notification
2034{
2035    fUpdateInProgress = YES;
2036}
2037
2038- (NSDictionary *) registrationDictionaryForGrowl
2039{
2040    NSArray * notifications = [NSArray arrayWithObjects: @"Download Complete",
2041                                @"Seeding Complete", @"Torrent Auto Added", nil];
2042    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2043                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2044}
2045
2046@end
Note: See TracBrowser for help on using the repository browser.