source: trunk/macosx/Controller.m @ 742

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

Growl for auto speed limit

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