source: trunk/macosx/Controller.m @ 618

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

Lose focus before hiding to avoid weird overlay on status bar.

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