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

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

Add "Pieces Viewer," accessible through the View menu. I swear this was my own idea. :-p

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