source: trunk/macosx/Controller.m @ 651

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

no pressed in state for filter

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