source: branches/nat-traversal/macosx/Controller.m @ 880

Last change on this file since 880 was 880, checked in by livings124, 15 years ago

Simplified queue and autostart prefs

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