source: trunk/macosx/Controller.m @ 666

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

New awesome help by jah.

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