source: trunk/macosx/Controller.m @ 740

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

Allow scheduling of speed limit.
Preference window saves when closing again.

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