source: trunk/macosx/Controller.m @ 672

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

Use constants for growl notifications

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