source: trunk/macosx/Controller.m @ 753

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

Streamlined autoenable function a little.

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