source: trunk/macosx/Controller.m @ 652

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

Sort in the action menu.

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