source: trunk/macosx/Controller.m @ 752

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

Scheduler is now more automatic.

  • Property svn:keywords set to Date Rev Author Id
File size: 79.8 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 752 2006-08-11 22:58:14Z 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 rangeForOn = onHour < offHour;
1270    int min, max;
1271    if (rangeForOn)
1272    {
1273        min = onHour;
1274        max = offHour;
1275    }
1276    else
1277    {
1278        min = offHour;
1279        max = onHour;
1280    }
1281   
1282    int hour = [[NSCalendarDate calendarDate] hourOfDay];
1283    BOOL inRange = hour >= min && hour < max;
1284   
1285    if ((!fSpeedLimitEnabled && (rangeForOn == inRange)) || (fSpeedLimitEnabled && (rangeForOn != inRange)))
1286    {
1287        [self toggleSpeedLimit: nil];
1288       
1289        [GrowlApplicationBridge notifyWithTitle: [@"Speed Limit Auto " stringByAppendingString:
1290            fSpeedLimitEnabled ? @"Enabled" : @"Disabled"] description: @"Bandwidth settings changed"
1291            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1292    }
1293}
1294
1295- (void) setLimitGlobalEnabled: (id) sender
1296{
1297    [fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
1298        type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem) ? @"Upload" : @"Download"];
1299}
1300
1301- (void) setQuickLimitGlobal: (id) sender
1302{
1303    [fPrefsController setQuickLimit: [[sender title] intValue]
1304        type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
1305}
1306
1307- (void) limitGlobalChange: (NSNotification *) notification
1308{
1309    NSDictionary * dict = [notification object];
1310   
1311    NSMenuItem * limitItem, * noLimitItem;
1312    if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
1313    {
1314        limitItem = fUploadLimitItem;
1315        noLimitItem = fUploadNoLimitItem;
1316    }
1317    else
1318    {
1319        limitItem = fDownloadLimitItem;
1320        noLimitItem = fDownloadNoLimitItem;
1321    }
1322   
1323    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1324    [limitItem setState: enable ? NSOnState : NSOffState];
1325    [noLimitItem setState: !enable ? NSOnState : NSOffState];
1326   
1327    [limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
1328                            [[dict objectForKey: @"Limit"] intValue]]];
1329
1330    [dict release];
1331}
1332
1333- (void) setRatioGlobalEnabled: (id) sender
1334{
1335    [fPrefsController setRatioEnabled: sender == fRatioSetItem];
1336}
1337
1338- (void) setQuickRatioGlobal: (id) sender
1339{
1340    [fPrefsController setQuickRatio: [[sender title] floatValue]];
1341}
1342
1343- (void) ratioGlobalChange: (NSNotification *) notification
1344{
1345    NSDictionary * dict = [notification object];
1346   
1347    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1348    [fRatioSetItem setState: enable ? NSOnState : NSOffState];
1349    [fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
1350   
1351    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
1352                            [[dict objectForKey: @"Ratio"] floatValue]]];
1353
1354    [dict release];
1355}
1356
1357- (void) checkWaitingForStopped: (NSNotification *) notification
1358{
1359    [self checkToStartWaiting: [notification object]];
1360   
1361    [self updateUI: nil];
1362    [self applyFilter: nil];
1363    [fInfoController updateInfoStatsAndSettings];
1364    [self updateTorrentHistory];
1365}
1366
1367- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1368{
1369    //don't try to start a transfer if there should be none waiting
1370    if (![[fDefaults stringForKey: @"StartSetting"] isEqualToString: @"Wait"])
1371        return;
1372
1373    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1374   
1375    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1376    Torrent * torrent, * torrentToStart = nil;
1377    while ((torrent = [enumerator nextObject]))
1378    {
1379        //ignore the torrent just stopped
1380        if (torrent == finishedTorrent)
1381            continue;
1382   
1383        if ([torrent isActive])
1384        {
1385            if (![torrent isSeeding])
1386            {
1387                desiredActive--;
1388                if (desiredActive <= 0)
1389                    return;
1390            }
1391        }
1392        else
1393        {
1394            //use as next if it is waiting to start and either no previous or order value is lower
1395            if ([torrent waitingToStart] && (!torrentToStart
1396                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1397                torrentToStart = torrent;
1398        }
1399    }
1400   
1401    //since it hasn't returned, the queue amount has not been met
1402    if (torrentToStart)
1403    {
1404        [torrentToStart startTransfer];
1405       
1406        [self updateUI: nil];
1407        [self applyFilter: nil];
1408        [fInfoController updateInfoStatsAndSettings];
1409        [self updateTorrentHistory];
1410    }
1411}
1412
1413- (void) torrentStartSettingChange: (NSNotification *) notification
1414{
1415    [self attemptToStartMultipleAuto: [notification object]];
1416
1417    [self updateUI: nil];
1418    [self applyFilter: nil];
1419    [fInfoController updateInfoStatsAndSettings];
1420    [self updateTorrentHistory];
1421}
1422
1423- (void) globalStartSettingChange: (NSNotification *) notification
1424{
1425    [self attemptToStartMultipleAuto: fTorrents];
1426   
1427    [self updateUI: nil];
1428    [self applyFilter: nil];
1429    [fInfoController updateInfoStatsAndSettings];
1430    [self updateTorrentHistory];
1431}
1432
1433- (void) torrentStoppedForRatio: (NSNotification *) notification
1434{
1435    [self applyFilter: nil];
1436    [fInfoController updateInfoStatsAndSettings];
1437   
1438    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1439    {
1440        NSSound * sound;
1441        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1442            [sound play];
1443    }
1444   
1445    [GrowlApplicationBridge notifyWithTitle: @"Seeding Complete" description: [[notification object] name]
1446        notificationName: GROWL_SEEDING_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1447}
1448
1449- (void) attemptToStartAuto: (Torrent *) torrent
1450{
1451    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1452}
1453
1454//will try to start, taking into consideration the start preference
1455- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1456{
1457    NSString * startSetting = [fDefaults stringForKey: @"StartSetting"];
1458    if ([startSetting isEqualToString: @"Start"])
1459    {
1460        NSEnumerator * enumerator = [torrents objectEnumerator];
1461        Torrent * torrent;
1462        while ((torrent = [enumerator nextObject]))
1463            if ([torrent waitingToStart])
1464                [torrent startTransfer];
1465       
1466        return;
1467    }
1468    else if (![startSetting isEqualToString: @"Wait"])
1469        return;
1470    else;
1471   
1472    //determine the number of downloads needed to start
1473    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1474           
1475    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1476    Torrent * torrent;
1477    while ((torrent = [enumerator nextObject]))
1478        if ([torrent isActive] && ![torrent isSeeding])
1479        {
1480            desiredActive--;
1481            if (desiredActive <= 0)
1482                break;
1483        }
1484   
1485    //sort torrents by order value
1486    NSArray * sortedTorrents;
1487    if ([torrents count] > 1 && desiredActive > 0)
1488    {
1489        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1490                                                    @"orderValue" ascending: YES] autorelease];
1491        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1492       
1493        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1494        [descriptors release];
1495    }
1496    else
1497        sortedTorrents = torrents;
1498
1499    enumerator = [sortedTorrents objectEnumerator];
1500    while ((torrent = [enumerator nextObject]))
1501    {
1502        if ([torrent waitingToStart])
1503        {
1504            if ([torrent progress] >= 1.0)
1505                [torrent startTransfer];
1506            else if (desiredActive > 0)
1507            {
1508                [torrent startTransfer];
1509                desiredActive--;
1510            }
1511            else
1512                continue;
1513           
1514            [torrent update];
1515        }
1516    }
1517}
1518
1519- (void) reloadInspectorSettings: (NSNotification *) notification
1520{
1521    [fInfoController updateInfoStatsAndSettings];
1522}
1523
1524- (void) checkAutoImportDirectory: (NSTimer *) timer
1525{
1526    if (![fDefaults boolForKey: @"AutoImport"])
1527        return;
1528       
1529    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1530   
1531    //if folder cannot be found or the contents hasn't changed simply give up
1532    NSArray * allFileNames;
1533    if (!(allFileNames = [[NSFileManager defaultManager] directoryContentsAtPath: path])
1534            || [allFileNames isEqualToArray: fAutoImportedNames])
1535        return;
1536
1537    //try to add files that haven't already been added
1538    NSMutableArray * newFileNames = [NSMutableArray arrayWithArray: allFileNames];
1539    [newFileNames removeObjectsInArray: fAutoImportedNames];
1540   
1541    //save the current list of files
1542    [fAutoImportedNames setArray: allFileNames];
1543   
1544    NSEnumerator * enumerator = [newFileNames objectEnumerator];
1545    NSString * file;
1546    unsigned oldCount;
1547    while ((file = [enumerator nextObject]))
1548        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1549        {
1550            oldCount = [fTorrents count];
1551            [self openFiles: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1552           
1553            //import only actually happened if the torrent array is larger
1554            if (oldCount < [fTorrents count])
1555                [GrowlApplicationBridge notifyWithTitle: @"Torrent File Auto Added" description: file
1556                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1557        }
1558}
1559
1560- (void) autoImportChange: (NSNotification *) notification
1561{
1562    [fAutoImportedNames removeAllObjects];
1563    [self checkAutoImportDirectory: nil];
1564}
1565
1566- (int) numberOfRowsInTableView: (NSTableView *) t
1567{
1568    return [fDisplayedTorrents count];
1569}
1570
1571- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
1572    forTableColumn: (NSTableColumn *) tableColumn row: (int) row
1573{
1574    [cell setTorrent: [fDisplayedTorrents objectAtIndex: row]];
1575}
1576
1577- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1578    toPasteboard: (NSPasteboard *) pasteboard
1579{
1580    //only allow reordering of rows if sorting by order with no filter
1581    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1582            && [[fSearchFilterField stringValue] length] == 0)
1583    {
1584        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1585        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1586                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1587        return YES;
1588    }
1589    return NO;
1590}
1591
1592- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1593    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1594{
1595    NSPasteboard * pasteboard = [info draggingPasteboard];
1596    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1597    {
1598        //check if any files to add have "torrent" as an extension
1599        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1600        NSString * file;
1601        while ((file = [enumerator nextObject]))
1602            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1603            {
1604                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1605                return NSDragOperationGeneric;
1606            }
1607    }
1608    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1609    {
1610        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1611        return NSDragOperationGeneric;
1612    }
1613    else
1614        return NSDragOperationNone;
1615}
1616
1617- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1618    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1619{
1620    NSPasteboard * pasteboard = [info draggingPasteboard];
1621    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1622    {
1623        //create an array of files with the "torrent" extension
1624        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1625        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1626        NSString * file;
1627        while ((file = [enumerator nextObject]))
1628            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1629                [filesToOpen addObject: file];
1630   
1631        [self application: NSApp openFiles: filesToOpen];
1632        [filesToOpen release];
1633    }
1634    else
1635    {
1636        //remember selected rows if needed
1637        NSArray * selectedTorrents = nil;
1638        int numSelected = [fTableView numberOfSelectedRows];
1639        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1640            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1641   
1642        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1643                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1644       
1645        //move torrent in array
1646        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1647        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1648       
1649        //determine the insertion index now that transfers to move have been removed
1650        int i, decrease = 0;
1651        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1652            decrease++;
1653       
1654        //insert objects at new location
1655        for (i = 0; i < [movingTorrents count]; i++)
1656            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1657       
1658        [movingTorrents release];
1659       
1660        //redo order values
1661        int low = [indexes firstIndex], high = [indexes lastIndex];
1662        if (newRow < low)
1663            low = newRow;
1664        else if (newRow > high + 1)
1665            high = newRow - 1;
1666        else;
1667       
1668        for (i = low; i <= high; i++)
1669            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1670       
1671        [fTableView reloadData];
1672       
1673        //set selected rows if needed
1674        if (selectedTorrents)
1675        {
1676            Torrent * torrent;
1677            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1678            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1679            while ((torrent = [enumerator nextObject]))
1680                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1681           
1682            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1683            [indexSet release];
1684        }
1685    }
1686   
1687    return YES;
1688}
1689
1690- (void) tableViewSelectionDidChange: (NSNotification *) notification
1691{
1692    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1693}
1694
1695- (void) toggleSmallView: (id) sender
1696{
1697    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
1698   
1699    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1700    [fSmallViewItem setState: makeSmall];
1701   
1702    [fDefaults setBool: makeSmall forKey: @"SmallView"];
1703   
1704    //window min height
1705    NSSize contentMinSize = [fWindow contentMinSize],
1706            contentSize = [[fWindow contentView] frame].size;
1707    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1708                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1709    [fWindow setContentMinSize: contentMinSize];
1710   
1711    //resize for larger min height if not set to auto size
1712    if (![fDefaults boolForKey: @"AutoSize"])
1713    {
1714        if (!makeSmall && contentSize.height < contentMinSize.height)
1715        {
1716            NSRect frame = [fWindow frame];
1717            float heightChange = contentMinSize.height - contentSize.height;
1718            frame.size.height += heightChange;
1719            frame.origin.y -= heightChange;
1720           
1721            [fWindow setFrame: frame display: YES];
1722            [fTableView reloadData];
1723        }
1724    }
1725    else
1726        [self setWindowSizeToFit];
1727}
1728
1729- (void) toggleStatusBar: (id) sender
1730{
1731    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1732    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1733}
1734
1735- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1736{
1737    if (show != [fStatusBar isHidden])
1738        return;
1739
1740    if (show)
1741        [fStatusBar setHidden: NO];
1742
1743    NSRect frame = [fWindow frame];
1744    float heightChange = [fStatusBar frame].size.height;
1745    if (!show)
1746        heightChange *= -1;
1747
1748    frame.size.height += heightChange;
1749    frame.origin.y -= heightChange;
1750   
1751    [self updateUI: nil];
1752   
1753    //set views to not autoresize
1754    unsigned int statsMask = [fStatusBar autoresizingMask];
1755    unsigned int filterMask = [fFilterBar autoresizingMask];
1756    unsigned int scrollMask = [fScrollView autoresizingMask];
1757    [fStatusBar setAutoresizingMask: 0];
1758    [fFilterBar setAutoresizingMask: 0];
1759    [fScrollView setAutoresizingMask: 0];
1760   
1761    [fWindow setFrame: frame display: YES animate: animate];
1762   
1763    //re-enable autoresize
1764    [fStatusBar setAutoresizingMask: statsMask];
1765    [fFilterBar setAutoresizingMask: filterMask];
1766    [fScrollView setAutoresizingMask: scrollMask];
1767   
1768    //change min size
1769    NSSize minSize = [fWindow contentMinSize];
1770    minSize.height += heightChange;
1771    [fWindow setContentMinSize: minSize];
1772   
1773    if (!show)
1774        [fStatusBar setHidden: YES];
1775}
1776
1777- (void) toggleFilterBar: (id) sender
1778{
1779    //disable filtering when hiding
1780    if (![fFilterBar isHidden])
1781    {
1782        [fSearchFilterField setStringValue: @""];
1783        [self setFilter: fNoFilterButton];
1784    }
1785
1786    [self showFilterBar: [fFilterBar isHidden] animate: YES];
1787    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
1788}
1789
1790- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1791{
1792    if (show != [fFilterBar isHidden])
1793        return;
1794
1795    if (show)
1796        [fFilterBar setHidden: NO];
1797
1798    NSRect frame = [fWindow frame];
1799    float heightChange = [fFilterBar frame].size.height;
1800    if (!show)
1801        heightChange *= -1;
1802
1803    frame.size.height += heightChange;
1804    frame.origin.y -= heightChange;
1805   
1806    //set views to not autoresize
1807    unsigned int filterMask = [fFilterBar autoresizingMask];
1808    unsigned int scrollMask = [fScrollView autoresizingMask];
1809    [fFilterBar setAutoresizingMask: 0];
1810    [fScrollView setAutoresizingMask: 0];
1811   
1812    [fWindow setFrame: frame display: YES animate: animate];
1813   
1814    //re-enable autoresize
1815    [fFilterBar setAutoresizingMask: filterMask];
1816    [fScrollView setAutoresizingMask: scrollMask];
1817   
1818    //change min size
1819    NSSize minSize = [fWindow contentMinSize];
1820    minSize.height += heightChange;
1821    [fWindow setContentMinSize: minSize];
1822   
1823    if (!show)
1824    {
1825        [fFilterBar setHidden: YES];
1826        [fWindow makeFirstResponder: fTableView];
1827    }
1828}
1829
1830- (void) toggleAdvancedBar: (id) sender
1831{
1832    int state = ![fAdvancedBarItem state];
1833    [fAdvancedBarItem setState: state];
1834    [fDefaults setBool: state forKey: @"UseAdvancedBar"];
1835   
1836    [fTableView display];
1837}
1838
1839- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1840    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1841{
1842    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1843
1844    if ([ident isEqualToString: TOOLBAR_OPEN])
1845    {
1846        [item setLabel: @"Open"];
1847        [item setPaletteLabel: @"Open Torrent Files"];
1848        [item setToolTip: @"Open torrent files"];
1849        [item setImage: [NSImage imageNamed: @"Open.png"]];
1850        [item setTarget: self];
1851        [item setAction: @selector(openShowSheet:)];
1852    }
1853    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1854    {
1855        [item setLabel: @"Remove"];
1856        [item setPaletteLabel: @"Remove Selected"];
1857        [item setToolTip: @"Remove selected transfers"];
1858        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1859        [item setTarget: self];
1860        [item setAction: @selector(removeNoDelete:)];
1861    }
1862    else if ([ident isEqualToString: TOOLBAR_INFO])
1863    {
1864        [item setLabel: @"Inspector"];
1865        [item setPaletteLabel: @"Toggle Inspector"];
1866        [item setToolTip: @"Toggle the torrent inspector"];
1867        [item setImage: [NSImage imageNamed: @"Info.png"]];
1868        [item setTarget: self];
1869        [item setAction: @selector(showInfo:)];
1870    }
1871    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1872    {
1873        [item setLabel: @"Pause All"];
1874        [item setPaletteLabel: [item label]];
1875        [item setToolTip: @"Pause all transfers"];
1876        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1877        [item setTarget: self];
1878        [item setAction: @selector(stopAllTorrents:)];
1879    }
1880    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1881    {
1882        [item setLabel: @"Resume All"];
1883        [item setPaletteLabel: [item label]];
1884        [item setToolTip: @"Resume all transfers"];
1885        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1886        [item setTarget: self];
1887        [item setAction: @selector(resumeAllTorrents:)];
1888    }
1889    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1890    {
1891        [item setLabel: @"Pause"];
1892        [item setPaletteLabel: @"Pause Selected"];
1893        [item setToolTip: @"Pause selected transfers"];
1894        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1895        [item setTarget: self];
1896        [item setAction: @selector(stopSelectedTorrents:)];
1897    }
1898    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1899    {
1900        [item setLabel: @"Resume"];
1901        [item setPaletteLabel: @"Resume Selected"];
1902        [item setToolTip: @"Resume selected transfers"];
1903        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1904        [item setTarget: self];
1905        [item setAction: @selector(resumeSelectedTorrents:)];
1906    }
1907    else if ([ident isEqualToString: TOOLBAR_FILTER])
1908    {
1909        [item setLabel: @"Filter"];
1910        [item setPaletteLabel: @"Toggle Filter"];
1911        [item setToolTip: @"Toggle the filter bar"];
1912        [item setImage: [NSImage imageNamed: @"Filter.png"]];
1913        [item setTarget: self];
1914        [item setAction: @selector(toggleFilterBar:)];
1915    }
1916    else
1917    {
1918        [item release];
1919        return nil;
1920    }
1921
1922    return item;
1923}
1924
1925- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1926{
1927    return [NSArray arrayWithObjects:
1928            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1929            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1930            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
1931            NSToolbarSeparatorItemIdentifier,
1932            NSToolbarSpaceItemIdentifier,
1933            NSToolbarFlexibleSpaceItemIdentifier,
1934            NSToolbarCustomizeToolbarItemIdentifier, nil];
1935}
1936
1937- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1938{
1939    return [NSArray arrayWithObjects:
1940            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1941            NSToolbarSeparatorItemIdentifier,
1942            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1943            NSToolbarFlexibleSpaceItemIdentifier,
1944            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
1945}
1946
1947- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1948{
1949    NSString * ident = [toolbarItem itemIdentifier];
1950
1951    //enable remove item
1952    if ([ident isEqualToString: TOOLBAR_REMOVE])
1953        return [fTableView numberOfSelectedRows] > 0;
1954
1955    //enable pause all item
1956    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1957    {
1958        Torrent * torrent;
1959        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1960        while ((torrent = [enumerator nextObject]))
1961            if ([torrent isActive])
1962                return YES;
1963        return NO;
1964    }
1965
1966    //enable resume all item
1967    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1968    {
1969        Torrent * torrent;
1970        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1971        while ((torrent = [enumerator nextObject]))
1972            if ([torrent isPaused])
1973                return YES;
1974        return NO;
1975    }
1976
1977    //enable pause item
1978    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1979    {
1980        Torrent * torrent;
1981        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1982        unsigned int i;
1983       
1984        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1985            if ([[fDisplayedTorrents objectAtIndex: i] isActive])
1986                return YES;
1987        return NO;
1988    }
1989   
1990    //enable resume item
1991    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1992    {
1993        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1994        unsigned int i;
1995       
1996        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1997            if ([[fDisplayedTorrents objectAtIndex: i] isPaused])
1998                return YES;
1999        return NO;
2000    }
2001
2002    return YES;
2003}
2004
2005- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2006{
2007    SEL action = [menuItem action];
2008
2009    //only enable some items if it is in a context menu or the window is useable
2010    BOOL canUseMenu = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
2011
2012    //enable open items
2013    if (action == @selector(openShowSheet:))
2014        return [fWindow attachedSheet] == nil;
2015
2016    //enable show info
2017    if (action == @selector(showInfo:))
2018    {
2019        NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
2020        if (![[menuItem title] isEqualToString: title])
2021                [menuItem setTitle: title];
2022
2023        return YES;
2024    }
2025   
2026    //enable prev/next inspector tab
2027    if (action == @selector(setInfoTab:))
2028        return [[fInfoController window] isVisible];
2029   
2030    //enable toggle status bar
2031    if (action == @selector(toggleStatusBar:))
2032    {
2033        NSString * title = [fStatusBar isHidden] ? @"Show Status Bar" : @"Hide Status Bar";
2034        if (![[menuItem title] isEqualToString: title])
2035                [menuItem setTitle: title];
2036
2037        return canUseMenu;
2038    }
2039   
2040    //enable toggle filter bar
2041    if (action == @selector(toggleFilterBar:))
2042    {
2043        NSString * title = [fFilterBar isHidden] ? @"Show Filter Bar" : @"Hide Filter Bar";
2044        if (![[menuItem title] isEqualToString: title])
2045                [menuItem setTitle: title];
2046
2047        return canUseMenu;
2048    }
2049
2050    //enable reveal in finder
2051    if (action == @selector(revealFile:))
2052        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
2053
2054    //enable remove items
2055    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2056        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2057    {
2058        BOOL warning = NO,
2059            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2060            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2061        Torrent * torrent;
2062        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2063        unsigned int i;
2064       
2065        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2066        {
2067            torrent = [fDisplayedTorrents objectAtIndex: i];
2068            if (!warning && [torrent isActive])
2069            {
2070                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2071                if (warning && canDelete)
2072                    break;
2073            }
2074            if (!canDelete && [torrent publicTorrent])
2075            {
2076                canDelete = YES;
2077                if (warning)
2078                    break;
2079            }
2080        }
2081   
2082        //append or remove ellipsis when needed
2083        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2084        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2085        {
2086            if (![title hasSuffix: ellipsis])
2087                [menuItem setTitle: [title stringByAppendingEllipsis]];
2088        }
2089        else
2090        {
2091            if ([title hasSuffix: ellipsis])
2092                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2093        }
2094       
2095        return canUseMenu && canDelete && [fTableView numberOfSelectedRows] > 0;
2096    }
2097
2098    //enable pause all item
2099    if (action == @selector(stopAllTorrents:))
2100    {
2101        Torrent * torrent;
2102        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2103        while ((torrent = [enumerator nextObject]))
2104            if ([torrent isActive])
2105                return YES;
2106        return NO;
2107    }
2108   
2109    //enable resume all item
2110    if (action == @selector(resumeAllTorrents:))
2111    {
2112        Torrent * torrent;
2113        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2114        while ((torrent = [enumerator nextObject]))
2115            if ([torrent isPaused])
2116                return YES;
2117        return NO;
2118    }
2119   
2120    //enable resume waiting item
2121    if (action == @selector(resumeWaitingTorrents:))
2122    {
2123        if (![[fDefaults stringForKey: @"StartSetting"] isEqualToString: @"Wait"])
2124            return NO;
2125   
2126        Torrent * torrent;
2127        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2128        while ((torrent = [enumerator nextObject]))
2129            if ([torrent waitingToStart])
2130                return YES;
2131        return NO;
2132    }
2133
2134    //enable pause item
2135    if (action == @selector(stopSelectedTorrents:))
2136    {
2137        if (!canUseMenu)
2138            return NO;
2139   
2140        Torrent * torrent;
2141        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2142        unsigned int i;
2143       
2144        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2145        {
2146            torrent = [fDisplayedTorrents objectAtIndex: i];
2147            if ([torrent isActive])
2148                return YES;
2149        }
2150        return NO;
2151    }
2152   
2153    //enable resume item
2154    if (action == @selector(resumeSelectedTorrents:))
2155    {
2156        if (!canUseMenu)
2157            return NO;
2158   
2159        Torrent * torrent;
2160        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2161        unsigned int i;
2162       
2163        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2164        {
2165            torrent = [fDisplayedTorrents objectAtIndex: i];
2166            if ([torrent isPaused])
2167                return YES;
2168        }
2169        return NO;
2170    }
2171   
2172    //enable sort and advanced bar items
2173    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:)
2174            || action == @selector(toggleSmallView:))
2175        return canUseMenu;
2176   
2177    //enable copy torrent file item
2178    if (action == @selector(copyTorrentFile:))
2179        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
2180
2181    return YES;
2182}
2183
2184- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2185{
2186    NSEnumerator * enumerator;
2187    Torrent * torrent;
2188    BOOL active;
2189
2190    switch (messageType)
2191    {
2192        case kIOMessageSystemWillSleep:
2193            //close all connections before going to sleep and remember we should resume when we wake up
2194            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2195
2196            //wait for running transfers to stop (5 second timeout)
2197            NSDate * start = [NSDate date];
2198            BOOL timeUp = NO;
2199           
2200            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2201            Torrent * torrent;
2202            while (!timeUp && (torrent = [enumerator nextObject]))
2203                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2204                {
2205                    usleep(100000);
2206                    [torrent update];
2207                }
2208
2209            IOAllowPowerChange(fRootPort, (long) messageArgument);
2210            break;
2211
2212        case kIOMessageCanSystemSleep:
2213            //pevent idle sleep unless all paused
2214            active = NO;
2215            enumerator = [fTorrents objectEnumerator];
2216            while ((torrent = [enumerator nextObject]))
2217                if ([torrent isActive])
2218                {
2219                    active = YES;
2220                    break;
2221                }
2222
2223            if (active)
2224                IOCancelPowerChange(fRootPort, (long) messageArgument);
2225            else
2226                IOAllowPowerChange(fRootPort, (long) messageArgument);
2227            break;
2228
2229        case kIOMessageSystemHasPoweredOn:
2230            //resume sleeping transfers after we wake up
2231            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2232            break;
2233    }
2234}
2235
2236- (void) resetDockBadge: (NSNotification *) notification
2237{
2238    float downloadRate, uploadRate;
2239    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2240   
2241    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2242}
2243
2244- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2245{
2246    //if auto size is enabled, the current frame shouldn't need to change
2247    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2248   
2249    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2250    return frame;
2251}
2252
2253- (void) setWindowSizeToFit
2254{
2255    if ([fDefaults boolForKey: @"AutoSize"])
2256        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2257}
2258
2259- (NSRect) sizedWindowFrame
2260{
2261    NSRect frame = [fWindow frame];
2262    float newHeight = frame.size.height - [fScrollView frame].size.height
2263        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2264
2265    float minHeight = [fWindow minSize].height;
2266    if (newHeight < minHeight)
2267        newHeight = minHeight;
2268    else
2269    {
2270        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2271        if ([fStatusBar isHidden])
2272            maxHeight -= [fStatusBar frame].size.height;
2273        if ([fFilterBar isHidden])
2274            maxHeight -= [fFilterBar frame].size.height;
2275       
2276        if (newHeight > maxHeight)
2277            newHeight = maxHeight;
2278    }
2279
2280    frame.origin.y -= (newHeight - frame.size.height);
2281    frame.size.height = newHeight;
2282    return frame;
2283}
2284
2285- (void) showMainWindow: (id) sender
2286{
2287    [fWindow makeKeyAndOrderFront: nil];
2288}
2289
2290- (void) windowDidBecomeKey: (NSNotification *) notification
2291{
2292    //reset dock badge for completed
2293    if (fCompleted > 0)
2294    {
2295        fCompleted = 0;
2296        [self resetDockBadge: nil];
2297    }
2298}
2299
2300- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2301{
2302    //only resize horizontally if autosize is enabled
2303    if ([fDefaults boolForKey: @"AutoSize"])
2304        proposedFrameSize.height = [fWindow frame].size.height;
2305    return proposedFrameSize;
2306}
2307
2308- (void) windowDidResize: (NSNotification *) notification
2309{
2310    //hide search filter if it overlaps filter buttons
2311    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2312}
2313
2314- (void) linkHomepage: (id) sender
2315{
2316    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2317}
2318
2319- (void) linkForums: (id) sender
2320{
2321    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2322}
2323
2324- (void) checkUpdate: (id) sender
2325{
2326    [fPrefsController checkUpdate];
2327}
2328
2329- (void) prepareForUpdate: (NSNotification *) notification
2330{
2331    fUpdateInProgress = YES;
2332}
2333
2334- (NSDictionary *) registrationDictionaryForGrowl
2335{
2336    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2337                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2338    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2339                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2340}
2341
2342@end
Note: See TracBrowser for help on using the repository browser.