source: trunk/macosx/Controller.m @ 745

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

show prefs window in Window menu / dock menu

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