source: trunk/macosx/Controller.m @ 855

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

Use tableView:objectValueForTableColumn:row: instead of tableView:willDisplayCell:...

This required passing in a dictionary of values to display, but should make it 10.5 compatible and potentially a little more efficient. Those using Leopard please report any issues, because I don't have it to test.

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