source: trunk/macosx/Controller.m @ 7795

Last change on this file since 7795 was 7795, checked in by livings124, 12 years ago

always fallback with sorting by name

  • Property svn:keywords set to Date Rev Author Id
File size: 153.0 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 7795 2009-01-24 19:26:16Z livings124 $
3 *
4 * Copyright (c) 2005-2009 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#import <IOKit/pwr_mgt/IOPMLib.h>
27
28#import "Controller.h"
29#import "Torrent.h"
30#import "TorrentGroup.h"
31#import "TorrentCell.h"
32#import "TorrentTableView.h"
33#import "CreatorWindowController.h"
34#import "StatsWindowController.h"
35#import "QuickLookController.h"
36#import "GroupsController.h"
37#import "AboutWindowController.h"
38#import "ButtonToolbarItem.h"
39#import "GroupToolbarItem.h"
40#import "ToolbarSegmentedCell.h"
41#import "BlocklistDownloader.h"
42#import "StatusBarView.h"
43#import "FilterButton.h"
44#import "BonjourController.h"
45#import "NSStringAdditions.h"
46#import "ExpandedPathToPathTransformer.h"
47#import "ExpandedPathToIconTransformer.h"
48#import "bencode.h"
49#import "utils.h"
50
51#import "UKKQueue.h"
52#import <Sparkle/Sparkle.h>
53
54#define TOOLBAR_CREATE                  @"Toolbar Create"
55#define TOOLBAR_OPEN_FILE               @"Toolbar Open"
56#define TOOLBAR_OPEN_WEB                @"Toolbar Open Web"
57#define TOOLBAR_REMOVE                  @"Toolbar Remove"
58#define TOOLBAR_INFO                    @"Toolbar Info"
59#define TOOLBAR_PAUSE_ALL               @"Toolbar Pause All"
60#define TOOLBAR_RESUME_ALL              @"Toolbar Resume All"
61#define TOOLBAR_PAUSE_RESUME_ALL        @"Toolbar Pause / Resume All"
62#define TOOLBAR_PAUSE_SELECTED          @"Toolbar Pause Selected"
63#define TOOLBAR_RESUME_SELECTED         @"Toolbar Resume Selected"
64#define TOOLBAR_PAUSE_RESUME_SELECTED   @"Toolbar Pause / Resume Selected"
65#define TOOLBAR_FILTER                  @"Toolbar Toggle Filter"
66#define TOOLBAR_QUICKLOOK               @"Toolbar QuickLook"
67
68typedef enum
69{
70    TOOLBAR_PAUSE_TAG = 0,
71    TOOLBAR_RESUME_TAG = 1
72} toolbarGroupTag;
73
74#define SORT_DATE       @"Date"
75#define SORT_NAME       @"Name"
76#define SORT_STATE      @"State"
77#define SORT_PROGRESS   @"Progress"
78#define SORT_TRACKER    @"Tracker"
79#define SORT_ORDER      @"Order"
80#define SORT_ACTIVITY   @"Activity"
81
82typedef enum
83{
84    SORT_ORDER_TAG = 0,
85    SORT_DATE_TAG = 1,
86    SORT_NAME_TAG = 2,
87    SORT_PROGRESS_TAG = 3,
88    SORT_STATE_TAG = 4,
89    SORT_TRACKER_TAG = 5,
90    SORT_ACTIVITY_TAG = 6
91} sortTag;
92
93#define FILTER_NONE     @"None"
94#define FILTER_ACTIVE   @"Active"
95#define FILTER_DOWNLOAD @"Download"
96#define FILTER_SEED     @"Seed"
97#define FILTER_PAUSE    @"Pause"
98
99#define FILTER_TYPE_NAME    @"Name"
100#define FILTER_TYPE_TRACKER @"Tracker"
101
102#define FILTER_TYPE_TAG_NAME    401
103#define FILTER_TYPE_TAG_TRACKER 402
104
105#define GROUP_FILTER_ALL_TAG    -2
106
107#define STATUS_RATIO_TOTAL      @"RatioTotal"
108#define STATUS_RATIO_SESSION    @"RatioSession"
109#define STATUS_TRANSFER_TOTAL   @"TransferTotal"
110#define STATUS_TRANSFER_SESSION @"TransferSession"
111
112typedef enum
113{
114    STATUS_RATIO_TOTAL_TAG = 0,
115    STATUS_RATIO_SESSION_TAG = 1,
116    STATUS_TRANSFER_TOTAL_TAG = 2,
117    STATUS_TRANSFER_SESSION_TAG = 3
118} statusTag;
119
120#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
121#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
122#define GROWL_AUTO_ADD          @"Torrent Auto Added"
123#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
124
125#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
126
127#define ROW_HEIGHT_REGULAR      62.0
128#define ROW_HEIGHT_SMALL        38.0
129#define WINDOW_REGULAR_WIDTH    468.0
130
131#define SEARCH_FILTER_MIN_WIDTH 48.0
132#define SEARCH_FILTER_MAX_WIDTH 95.0
133
134#define UPDATE_UI_SECONDS   1.0
135
136#define DOCK_SEEDING_TAG        101
137#define DOCK_DOWNLOADING_TAG    102
138
139#define SUPPORT_FOLDER  @"/Library/Application Support/Transmission/Transfers.plist"
140
141#define WEBSITE_URL @"http://www.transmissionbt.com/"
142#define FORUM_URL   @"http://forum.transmissionbt.com/"
143#define TRAC_URL   @"http://trac.transmissionbt.com/"
144#define DONATE_URL  @"http://www.transmissionbt.com/donate.php"
145
146static tr_rpc_callback_status rpcCallback(tr_session * handle UNUSED, tr_rpc_callback_type type, struct tr_torrent * torrentStruct, void * controller)
147{
148    [(Controller *)controller rpcCallback: type forTorrentStruct: torrentStruct];
149    return TR_RPC_NOREMOVE; //we'll do the remove manually
150}
151
152static void sleepCallback(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
153{
154    [(Controller *)controller sleepCallback: messageType argument: messageArgument];
155}
156
157@implementation Controller
158
159+ (void) initialize
160{
161    //make sure another Transmission.app isn't running already
162    NSString * bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
163    int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
164
165    for (NSDictionary * dic in [[NSWorkspace sharedWorkspace] launchedApplications])
166    {
167        if ([[dic objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]
168            && [[dic objectForKey: @"NSApplicationProcessIdentifier"] intValue] != processIdentifier)
169        {
170            NSAlert * alert = [[NSAlert alloc] init];
171            [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Transmission already running alert -> button")];
172            [alert setMessageText: NSLocalizedString(@"Transmission is already running.",
173                                                    "Transmission already running alert -> title")];
174            [alert setInformativeText: NSLocalizedString(@"There is already a copy of Transmission running. "
175                "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message")];
176            [alert setAlertStyle: NSWarningAlertStyle];
177           
178            [alert runModal];
179            [alert release];
180           
181            //kill ourselves right away
182            exit(0);
183        }
184    }
185   
186    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
187        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
188   
189    //set custom value transformers
190    ExpandedPathToPathTransformer * pathTransformer = [[[ExpandedPathToPathTransformer alloc] init] autorelease];
191    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
192   
193    ExpandedPathToIconTransformer * iconTransformer = [[[ExpandedPathToIconTransformer alloc] init] autorelease];
194    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
195}
196
197- (id) init
198{
199    if ((self = [super init]))
200    {
201        fDefaults = [NSUserDefaults standardUserDefaults];
202       
203        tr_benc settings;
204        tr_bencInitDict(&settings, 20);
205        tr_sessionGetDefaultSettings(&settings);
206       
207        tr_bencDictAddInt(&settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, [fDefaults boolForKey: @"Blocklist"]);
208       
209        #warning update when changing in prefs
210        tr_bencDictAddStr(&settings, TR_PREFS_KEY_DOWNLOAD_DIR, [[[fDefaults stringForKey: @"DownloadFolder"]
211                                                                    stringByExpandingTildeInPath] UTF8String]);
212       
213        tr_bencDictAddInt(&settings, TR_PREFS_KEY_MSGLEVEL, [fDefaults integerForKey: @"MessageLevel"]);
214        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, [fDefaults integerForKey: @"PeersTotal"]);
215        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_TORRENT, [fDefaults integerForKey: @"PeersTorrent"]);
216       
217        const BOOL randomPort = [fDefaults boolForKey: @"RandomPort"];
218        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_PORT_RANDOM_ENABLED, randomPort);
219        if (!randomPort)
220            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_PORT, [fDefaults integerForKey: @"BindPort"]);
221       
222        //hidden pref
223        if ([fDefaults objectForKey: @"PeerSocketTOS"])
224            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_SOCKET_TOS, [fDefaults integerForKey: @"PeerSocketTOS"]);
225       
226        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEX_ENABLED, [fDefaults boolForKey: @"PEXGlobal"]);
227        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PORT_FORWARDING, [fDefaults boolForKey: @"NatTraversal"]);
228        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PROXY_AUTH_ENABLED, [fDefaults boolForKey: @"ProxyAuthorize"]);
229        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PROXY_ENABLED, [fDefaults boolForKey: @"Proxy"]);
230        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PROXY_PORT, [fDefaults integerForKey: @"ProxyPort"]);
231        tr_bencDictAddStr(&settings, TR_PREFS_KEY_PROXY, [[fDefaults stringForKey: @"ProxyAddress"] UTF8String]);
232        tr_bencDictAddStr(&settings, TR_PREFS_KEY_PROXY_USERNAME,  [[fDefaults stringForKey: @"ProxyUsername"] UTF8String]);
233        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED,  [fDefaults boolForKey: @"RPCAuthorize"]);
234        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_ENABLED,  [fDefaults boolForKey: @"RPC"]);
235        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_PORT,  [fDefaults integerForKey: @"RPCPort"]);
236        tr_bencDictAddStr(&settings, TR_PREFS_KEY_RPC_USERNAME,  [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
237        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_WHITELIST_ENABLED,  [fDefaults boolForKey: @"RPCUseWhitelist"]);
238       
239        fLib = tr_sessionInit("macosx", tr_getDefaultConfigDir("Transmission"), YES, &settings);
240        tr_bencFree(&settings);
241       
242        [NSApp setDelegate: self];
243       
244        fTorrents = [[NSMutableArray alloc] init];
245        fDisplayedTorrents = [[NSMutableArray alloc] init];
246       
247        fMessageController = [[MessageWindowController alloc] init];
248        fInfoController = [[InfoWindowController alloc] init];
249       
250        [PrefsController setHandle: fLib];
251        fPrefsController = [[PrefsController alloc] init];
252       
253        [QuickLookController quickLookControllerInitializeWithController: self infoController: fInfoController];
254       
255        fSoundPlaying = NO;
256       
257        tr_sessionSetRPCCallback(fLib, rpcCallback, self);
258       
259        [GrowlApplicationBridge setGrowlDelegate: self];
260       
261        [[UKKQueue sharedFileWatcher] setDelegate: self];
262       
263        SUUpdater * updater = [SUUpdater sharedUpdater];
264        [updater setDelegate: self];
265        fUpdateInProgress = NO;
266    }
267    return self;
268}
269
270- (void) awakeFromNib
271{
272    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"TRMainToolbar"];
273    [toolbar setDelegate: self];
274    [toolbar setAllowsUserCustomization: YES];
275    [toolbar setAutosavesConfiguration: YES];
276    [toolbar setDisplayMode: NSToolbarDisplayModeIconOnly];
277    [fWindow setToolbar: toolbar];
278    [toolbar release];
279   
280    [fWindow setDelegate: self]; //do manually to avoid placement issue
281   
282    [fWindow makeFirstResponder: fTableView];
283    [fWindow setExcludedFromWindowsMenu: YES];
284   
285    //set table size
286    if ([fDefaults boolForKey: @"SmallView"])
287        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
288   
289    //window min height
290    NSSize contentMinSize = [fWindow contentMinSize];
291    contentMinSize.height = [[fWindow contentView] frame].size.height - [[fTableView enclosingScrollView] frame].size.height
292                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
293    [fWindow setContentMinSize: contentMinSize];
294    [fWindow setContentBorderThickness: [[fTableView enclosingScrollView] frame].origin.y forEdge: NSMinYEdge];
295       
296    [[fTotalTorrentsField cell] setBackgroundStyle: NSBackgroundStyleRaised];
297   
298    [self updateGroupsFilterButton];
299   
300    //set up filter bar
301    NSView * contentView = [fWindow contentView];
302    NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
303    [fFilterBar setHidden: YES];
304   
305    NSRect filterBarFrame = [fFilterBar frame];
306    filterBarFrame.size.width = windowSize.width;
307    [fFilterBar setFrame: filterBarFrame];
308   
309    [contentView addSubview: fFilterBar];
310    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
311
312    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
313   
314    //set up status bar
315    [fStatusBar setHidden: YES];
316   
317    [self updateSpeedFieldsToolTips];
318   
319    NSRect statusBarFrame = [fStatusBar frame];
320    statusBarFrame.size.width = windowSize.width;
321    [fStatusBar setFrame: statusBarFrame];
322   
323    [contentView addSubview: fStatusBar];
324    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
325    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
326   
327    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
328                                "Main window -> 1st bottom left button (action) tooltip")];
329    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
330                                "Main window -> 2nd bottom left button (turtle) tooltip")];
331   
332    [fTableView registerForDraggedTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE]];
333    [fWindow registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType, NSURLPboardType, nil]];
334
335    //register for sleep notifications
336    IONotificationPortRef notify;
337    io_object_t iterator;
338    if ((fRootPort = IORegisterForSystemPower(self, & notify, sleepCallback, &iterator)))
339        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
340    else
341        NSLog(@"Could not IORegisterForSystemPower");
342   
343    //load previous transfers
344    NSArray * history = [[NSArray alloc] initWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER]];
345   
346    //old version saved transfer info in prefs file
347    if (!history)
348    {
349        if ((history = [fDefaults arrayForKey: @"History"]))
350            [history retain];
351        [fDefaults removeObjectForKey: @"History"];
352    }
353   
354    if (history)
355    {
356        for (NSDictionary * historyItem in history)
357        {
358            Torrent * torrent;
359            if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
360            {
361                [fTorrents addObject: torrent];
362                [torrent release];
363            }
364        }
365        [history release];
366    }
367   
368    //set filter
369    NSString * filterType = [fDefaults stringForKey: @"Filter"];
370   
371    NSButton * currentFilterButton;
372    if ([filterType isEqualToString: FILTER_ACTIVE])
373        currentFilterButton = fActiveFilterButton;
374    else if ([filterType isEqualToString: FILTER_PAUSE])
375        currentFilterButton = fPauseFilterButton;
376    else if ([filterType isEqualToString: FILTER_SEED])
377        currentFilterButton = fSeedFilterButton;
378    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
379        currentFilterButton = fDownloadFilterButton;
380    else
381    {
382        //safety
383        if (![filterType isEqualToString: FILTER_NONE])
384            [fDefaults setObject: FILTER_NONE forKey: @"Filter"];
385        currentFilterButton = fNoFilterButton;
386    }
387    [currentFilterButton setState: NSOnState];
388   
389    //set filter search type
390    NSString * filterSearchType = [fDefaults stringForKey: @"FilterSearchType"];
391   
392    NSMenu * filterSearchMenu = [[fSearchFilterField cell] searchMenuTemplate];
393    NSString * filterSearchTypeTitle;
394    if ([filterSearchType isEqualToString: FILTER_TYPE_TRACKER])
395        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_TRACKER] title];
396    else
397    {
398        //safety
399        if (![filterType isEqualToString: FILTER_TYPE_NAME])
400            [fDefaults setObject: FILTER_TYPE_NAME forKey: @"FilterSearchType"];
401        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_NAME] title];
402    }
403    [[fSearchFilterField cell] setPlaceholderString: filterSearchTypeTitle];
404   
405    fBadger = [[Badger alloc] initWithLib: fLib];
406   
407    //observe notifications
408    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
409   
410    [nc addObserver: self selector: @selector(updateUI)
411                    name: @"UpdateUI" object: nil];
412   
413    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
414                    name: @"TorrentFinishedDownloading" object: nil];
415   
416    [nc addObserver: self selector: @selector(torrentRestartedDownloading:)
417                    name: @"TorrentRestartedDownloading" object: nil];
418   
419    //avoids need of setting delegate
420    [nc addObserver: self selector: @selector(torrentTableViewSelectionDidChange:)
421                    name: NSOutlineViewSelectionDidChangeNotification object: fTableView];
422   
423    [nc addObserver: self selector: @selector(autoSpeedLimitChange:)
424                    name: @"AutoSpeedLimitChange" object: nil];
425   
426    [nc addObserver: self selector: @selector(changeAutoImport)
427                    name: @"AutoImportSettingChange" object: nil];
428   
429    [nc addObserver: self selector: @selector(setWindowSizeToFit)
430                    name: @"AutoSizeSettingChange" object: nil];
431   
432    [nc addObserver: self selector: @selector(updateForExpandCollape)
433                    name: @"OutlineExpandCollapse" object: nil];
434   
435    [nc addObserver: fWindow selector: @selector(makeKeyWindow)
436                    name: @"MakeWindowKey" object: nil];
437   
438    //check if torrent should now start
439    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
440                    name: @"TorrentStoppedForRatio" object: nil];
441   
442    [nc addObserver: self selector: @selector(updateTorrentsInQueue)
443                    name: @"UpdateQueue" object: nil];
444   
445    //open newly created torrent file
446    [nc addObserver: self selector: @selector(beginCreateFile:)
447                    name: @"BeginCreateTorrentFile" object: nil];
448   
449    //open newly created torrent file
450    [nc addObserver: self selector: @selector(openCreatedFile:)
451                    name: @"OpenCreatedTorrentFile" object: nil];
452   
453    //update when groups change
454    [nc addObserver: self selector: @selector(updateGroupsFilters:)
455                    name: @"UpdateGroups" object: nil];
456   
457    //update when speed limits are changed
458    [nc addObserver: self selector: @selector(updateSpeedFieldsToolTips)
459                    name: @"SpeedLimitUpdate" object: nil];
460
461    //timer to update the interface every second
462    [self updateUI];
463    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
464                selector: @selector(updateUI) userInfo: nil repeats: YES];
465    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
466    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
467   
468    [self applyFilter: nil];
469   
470    [fWindow makeKeyAndOrderFront: nil];
471   
472    if ([fDefaults boolForKey: @"InfoVisible"])
473        [self showInfo: nil];
474   
475    //set up the speed limit
476    [self autoSpeedLimitChange: nil];
477}
478
479- (void) applicationDidFinishLaunching: (NSNotification *) notification
480{
481    [NSApp setServicesProvider: self];
482   
483    //register for dock icon drags
484    [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:)
485        forEventClass: kCoreEventClass andEventID: kAEOpenContents];
486   
487    //auto importing
488    [self checkAutoImportDirectory];
489   
490    //registering the Web UI to Bonjour
491    if ([fDefaults boolForKey: @"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"])
492        [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]];
493}
494
495- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
496{
497    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
498        [fWindow makeKeyAndOrderFront: nil];
499    return NO;
500}
501
502- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
503{
504    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
505    {
506        NSInteger active = 0, downloading = 0;
507        for (Torrent * torrent  in fTorrents)
508            if ([torrent isActive] && ![torrent isStalled])
509            {
510                active++;
511                if (![torrent allDownloaded])
512                    downloading++;
513            }
514       
515        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
516        {
517            NSString * message = active == 1
518                ? NSLocalizedString(@"There is an active transfer that will be paused on quit."
519                    " The transfer will automatically resume on the next launch.", "Confirm Quit panel -> message")
520                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers that will be paused on quit."
521                    " The transfers will automatically resume on the next launch.", "Confirm Quit panel -> message"), active];
522
523            NSBeginAlertSheet(NSLocalizedString(@"Are you sure you want to quit?", "Confirm Quit panel -> title"),
524                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
525                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
526                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
527            return NSTerminateLater;
528        }
529    }
530   
531    return NSTerminateNow;
532}
533
534- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
535{
536    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
537}
538
539- (void) applicationWillTerminate: (NSNotification *) notification
540{
541    //stop the Bonjour service
542    [[BonjourController defaultController] stop];
543
544    //stop blocklist download
545    if ([BlocklistDownloader isRunning])
546        [[BlocklistDownloader downloader] cancelDownload];
547   
548    //stop timers and notification checking
549    [[NSNotificationCenter defaultCenter] removeObserver: self];
550   
551    [fTimer invalidate];
552    [fSpeedLimitTimer invalidate];
553   
554    if (fAutoImportTimer)
555    {   
556        if ([fAutoImportTimer isValid])
557            [fAutoImportTimer invalidate];
558        [fAutoImportTimer release];
559    }
560   
561    [fBadger setQuitting];
562   
563    //remove all torrent downloads
564    if (fPendingTorrentDownloads)
565    {
566        for (NSDictionary * downloadDict in fPendingTorrentDownloads)
567        {
568            NSURLDownload * download = [downloadDict objectForKey: @"Download"];
569            [download cancel];
570            [download release];
571        }
572        [fPendingTorrentDownloads removeAllObjects];
573    }
574   
575    //remember window states and close all windows
576    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
577    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
578    [self showStatusBar: NO animate: NO];
579    [self showFilterBar: NO animate: NO];
580   
581    //save history
582    [self updateTorrentHistory];
583    [fTableView saveCollapsedGroups];
584   
585    //remaining calls the same as dealloc
586    [fInfoController release];
587    [fMessageController release];
588    [fPrefsController release];
589   
590    [fTorrents release];
591    [fDisplayedTorrents release];
592   
593    [fOverlayWindow release];
594    [fBadger release];
595   
596    [fAutoImportedNames release];
597    [fPendingTorrentDownloads release];
598   
599    //complete cleanup
600    tr_sessionClose(fLib);
601}
602
603- (void) handleOpenContentsEvent: (NSAppleEventDescriptor *) event replyEvent: (NSAppleEventDescriptor *) replyEvent
604{
605    NSString * urlString = nil;
606
607    NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject];
608    if ([directObject descriptorType] == typeAEList)
609    {
610        for (NSUInteger i = 1; i <= [directObject numberOfItems]; i++)
611            if ((urlString = [[directObject descriptorAtIndex: i] stringValue]))
612                break;
613    }
614    else
615        urlString = [directObject stringValue];
616   
617    if (urlString)
618        [self openURL: [NSURL URLWithString: urlString]];
619}
620
621- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) suggestedName
622{
623    if ([[suggestedName pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
624    {
625        [download cancel];
626       
627        NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title"),
628            [NSString stringWithFormat: NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.",
629            "Download not a torrent -> message"), suggestedName,
630            [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]],
631            NSLocalizedString(@"OK", "Download not a torrent -> button"), nil, nil);
632       
633        [download release];
634    }
635    else
636        [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: [suggestedName lastPathComponent]]
637                    allowOverwrite: NO];
638}
639
640-(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path
641{
642    if (!fPendingTorrentDownloads)
643        fPendingTorrentDownloads = [[NSMutableDictionary alloc] init];
644   
645    [fPendingTorrentDownloads setObject: [NSDictionary dictionaryWithObjectsAndKeys:
646                    path, @"Path", download, @"Download", nil] forKey: [[download request] URL]];
647}
648
649- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error
650{
651    NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Torrent download error -> title"),
652        [NSString stringWithFormat: NSLocalizedString(@"The torrent could not be downloaded from %@: %@.",
653        "Torrent download failed -> message"),
654        [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
655        [error localizedDescription]], NSLocalizedString(@"OK", "Torrent download failed -> button"), nil, nil);
656   
657    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
658    if ([fPendingTorrentDownloads count] == 0)
659    {
660        [fPendingTorrentDownloads release];
661        fPendingTorrentDownloads = nil;
662    }
663   
664    [download release];
665}
666
667- (void) downloadDidFinish: (NSURLDownload *) download
668{
669    NSString * path = [[fPendingTorrentDownloads objectForKey: [[download request] URL]] objectForKey: @"Path"];
670   
671    [self openFiles: [NSArray arrayWithObject: path] addType: ADD_URL forcePath: nil];
672   
673    //delete the torrent file after opening
674    [[NSFileManager defaultManager] removeItemAtPath: path error: NULL];
675   
676    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
677    if ([fPendingTorrentDownloads count] == 0)
678    {
679        [fPendingTorrentDownloads release];
680        fPendingTorrentDownloads = nil;
681    }
682   
683    [download release];
684}
685
686- (void) application: (NSApplication *) app openFiles: (NSArray *) filenames
687{
688    [self openFiles: filenames addType: ADD_MANUAL forcePath: nil];
689}
690
691- (void) openFiles: (NSArray *) filenames addType: (addType) type forcePath: (NSString *) path
692{
693    #warning checks could probably be removed, since location is checked when starting
694    if (!path && [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]
695        && access([[[fDefaults stringForKey: @"IncompleteDownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
696    {
697        NSOpenPanel * panel = [NSOpenPanel openPanel];
698       
699        [panel setPrompt: NSLocalizedString(@"Select", "Default incomplete folder cannot be used alert -> prompt")];
700        [panel setAllowsMultipleSelection: NO];
701        [panel setCanChooseFiles: NO];
702        [panel setCanChooseDirectories: YES];
703        [panel setCanCreateDirectories: YES];
704
705        [panel setMessage: NSLocalizedString(@"The incomplete folder cannot be used. Choose a new location or cancel for none.",
706                                        "Default incomplete folder cannot be used alert -> message")];
707       
708        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: filenames, @"Filenames",
709                                                        [NSNumber numberWithInt: type], @"AddType", nil];
710       
711        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
712                didEndSelector: @selector(incompleteChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
713        return;
714    }
715   
716    if (!path && [fDefaults boolForKey: @"DownloadLocationConstant"]
717        && access([[[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
718    {
719        NSOpenPanel * panel = [NSOpenPanel openPanel];
720       
721        [panel setPrompt: NSLocalizedString(@"Select", "Default folder cannot be used alert -> prompt")];
722        [panel setAllowsMultipleSelection: NO];
723        [panel setCanChooseFiles: NO];
724        [panel setCanChooseDirectories: YES];
725        [panel setCanCreateDirectories: YES];
726
727        [panel setMessage: NSLocalizedString(@"The download folder cannot be used. Choose a new location.",
728                                        "Default folder cannot be used alert -> message")];
729       
730        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: filenames, @"Filenames",
731                                                        [NSNumber numberWithInt: type], @"AddType", nil];
732       
733        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
734                didEndSelector: @selector(downloadChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
735        return;
736    }
737   
738    torrentFileState deleteTorrentFile;
739    switch (type)
740    {
741        case ADD_CREATED:
742            deleteTorrentFile = TORRENT_FILE_SAVE;
743            break;
744        case ADD_URL:
745            deleteTorrentFile = TORRENT_FILE_DELETE;
746            break;
747        default:
748            deleteTorrentFile = TORRENT_FILE_DEFAULT;
749    }
750   
751    tr_info info;
752    for (NSString * torrentPath in filenames)
753    {
754        //ensure torrent doesn't already exist
755        tr_ctor * ctor = tr_ctorNew(fLib);
756        tr_ctorSetMetainfoFromFile(ctor, [torrentPath UTF8String]);
757        int result = tr_torrentParse(fLib, ctor, &info);
758        if (result != TR_OK)
759        {
760            if (result == TR_EDUPLICATE)
761                [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
762            else if (result == TR_EINVALID)
763            {
764                if (type != ADD_AUTO)
765                    [self invalidOpenAlert: [torrentPath lastPathComponent]];
766            }
767            else //this shouldn't happen
768                NSLog(@"Unknown error code (%d) when attempting to open \"%@\"", result, torrentPath);
769           
770            tr_ctorFree(ctor);
771            tr_metainfoFree(&info);
772            continue;
773        }
774       
775        tr_ctorFree(ctor);
776       
777        //determine download location
778        NSString * location;
779        BOOL lockDestination = NO; //don't override the location with a group location if it has a hardcoded path
780        if (path)
781        {
782            location = [path stringByExpandingTildeInPath];
783            lockDestination = YES;
784        }
785        else if ([fDefaults boolForKey: @"DownloadLocationConstant"])
786            location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
787        else if (type != ADD_URL)
788            location = [torrentPath stringByDeletingLastPathComponent];
789        else
790            location = nil;
791       
792        //determine to show the options window
793        BOOL showWindow = type == ADD_SHOW_OPTIONS || ([fDefaults boolForKey: @"DownloadAsk"]
794                            && (info.isMultifile || ![fDefaults boolForKey: @"DownloadAskMulti"])
795                            && (type != ADD_AUTO || ![fDefaults boolForKey: @"DownloadAskManual"]));
796        tr_metainfoFree(&info);
797       
798        Torrent * torrent;
799        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath location: location
800                            deleteTorrentFile: showWindow ? TORRENT_FILE_SAVE : deleteTorrentFile lib: fLib]))
801            continue;
802       
803        //change the location if the group calls for it (this has to wait until after the torrent is create)
804        if (!lockDestination && [[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
805        {
806            location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
807            [torrent changeDownloadFolder: location];
808        }
809       
810        //verify the data right away if it was newly created
811        if (type == ADD_CREATED)
812            [torrent resetCache];
813       
814        //add it to the "File -> Open Recent" menu
815        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
816       
817        //show the add window or add directly
818        if (showWindow || !location)
819        {
820            AddWindowController * addController = [[AddWindowController alloc] initWithTorrent: torrent destination: location
821                                                    lockDestination: lockDestination controller: self deleteTorrent: deleteTorrentFile];
822            [addController showWindow: self];
823        }
824        else
825        {
826            [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
827           
828            [torrent update];
829            [fTorrents addObject: torrent];
830            [torrent release];
831        }
832    }
833
834    [self updateTorrentsInQueue];
835}
836
837- (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add
838{
839    Torrent * torrent = [addController torrent];
840    [addController release];
841   
842    if (add)
843    {
844        [torrent update];
845        [fTorrents addObject: torrent];
846        [torrent release];
847       
848        [self updateTorrentsInQueue];
849    }
850    else
851    {
852        [torrent closeRemoveTorrent];
853        [torrent release];
854    }
855}
856
857- (void) openCreatedFile: (NSNotification *) notification
858{
859    NSDictionary * dict = [notification userInfo];
860    [self openFiles: [NSArray arrayWithObject: [dict objectForKey: @"File"]] addType: ADD_CREATED
861                        forcePath: [dict objectForKey: @"Path"]];
862    [dict release];
863}
864
865- (void) incompleteChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
866{
867    if (code == NSOKButton)
868        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
869    else
870        [fDefaults setBool: NO forKey: @"UseIncompleteDownloadFolder"];
871   
872    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
873}
874
875- (void) downloadChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
876{
877    if (code == NSOKButton)
878    {
879        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"DownloadFolder"];
880        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
881    }
882    else
883        [dictionary release];
884}
885
886- (void) openFilesWithDict: (NSDictionary *) dictionary
887{
888    [self openFiles: [dictionary objectForKey: @"Filenames"] addType: [[dictionary objectForKey: @"AddType"] intValue] forcePath: nil];
889   
890    [dictionary release];
891}
892
893//called on by applescript
894- (void) open: (NSArray *) files
895{
896    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: files, @"Filenames",
897                                [NSNumber numberWithInt: ADD_MANUAL], @"AddType", nil];
898    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dict waitUntilDone: NO];
899}
900
901- (void) openShowSheet: (id) sender
902{
903    NSOpenPanel * panel = [NSOpenPanel openPanel];
904
905    [panel setAllowsMultipleSelection: YES];
906    [panel setCanChooseFiles: YES];
907    [panel setCanChooseDirectories: NO];
908
909    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"org.bittorrent.torrent"]
910        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
911        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
912}
913
914- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSNumber *) useOptions
915{
916    if (code == NSOKButton)
917    {
918        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: [panel filenames], @"Filenames",
919            [NSNumber numberWithInt: [useOptions boolValue] ? ADD_SHOW_OPTIONS : ADD_MANUAL], @"AddType", nil];
920        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
921    }
922}
923
924- (void) invalidOpenAlert: (NSString *) filename
925{
926    if (![fDefaults boolForKey: @"WarningInvalidOpen"])
927        return;
928   
929    NSAlert * alert = [[NSAlert alloc] init];
930    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"\"%@\" is not a valid torrent file.",
931                            "Open invalid alert -> title"), filename]];
932    [alert setInformativeText:
933            NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.",
934                            "Open invalid alert -> message")];
935    [alert setAlertStyle: NSWarningAlertStyle];
936    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open invalid alert -> button")];
937   
938    [alert runModal];
939    if ([[alert suppressionButton] state] == NSOnState)
940        [fDefaults setBool: NO forKey: @"WarningInvalidOpen"];
941    [alert release];
942}
943
944- (void) duplicateOpenAlert: (NSString *) name
945{
946    if (![fDefaults boolForKey: @"WarningDuplicate"])
947        return;
948   
949    NSAlert * alert = [[NSAlert alloc] init];
950    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.",
951                            "Open duplicate alert -> title"), name]];
952    [alert setInformativeText:
953            NSLocalizedString(@"The torrent file cannot be opened because it is a duplicate of an already added transfer.",
954                            "Open duplicate alert -> message")];
955    [alert setAlertStyle: NSWarningAlertStyle];
956    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate alert -> button")];
957    [alert setShowsSuppressionButton: YES];
958   
959    [alert runModal];
960    if ([[alert suppressionButton] state])
961        [fDefaults setBool: NO forKey: @"WarningDuplicate"];
962    [alert release];
963}
964
965- (void) openURL: (NSURL *) url
966{
967    [[NSURLDownload alloc] initWithRequest: [NSURLRequest requestWithURL: url] delegate: self];
968}
969
970- (void) openURLShowSheet: (id) sender
971{
972    [NSApp beginSheet: fURLSheetWindow modalForWindow: fWindow modalDelegate: self
973            didEndSelector: @selector(urlSheetDidEnd:returnCode:contextInfo:) contextInfo: nil];
974}
975
976- (void) openURLEndSheet: (id) sender
977{
978    [fURLSheetWindow orderOut: sender];
979    [NSApp endSheet: fURLSheetWindow returnCode: 1];
980}
981
982- (void) openURLCancelEndSheet: (id) sender
983{
984    [fURLSheetWindow orderOut: sender];
985    [NSApp endSheet: fURLSheetWindow returnCode: 0];
986}
987
988- (void) controlTextDidChange: (NSNotification *) notification
989{
990    if ([notification object] != fURLSheetTextField)
991        return;
992   
993    NSString * string = [fURLSheetTextField stringValue];
994    BOOL enable = YES;
995    if ([string isEqualToString: @""])
996        enable = NO;
997    else
998    {
999        NSRange prefixRange = [string rangeOfString: @"://"];
1000        if (prefixRange.location != NSNotFound && [string length] == NSMaxRange(prefixRange))
1001            enable = NO;
1002    }
1003   
1004    [fURLSheetOpenButton setEnabled: enable];
1005}
1006
1007- (void) urlSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
1008{
1009    [fURLSheetTextField selectText: self];
1010    if (returnCode != 1)
1011        return;
1012   
1013    NSString * urlString = [fURLSheetTextField stringValue];
1014    if ([urlString rangeOfString: @"://"].location == NSNotFound)
1015    {
1016        if ([urlString rangeOfString: @"."].location == NSNotFound)
1017        {
1018            NSInteger beforeCom;
1019            if ((beforeCom = [urlString rangeOfString: @"/"].location) != NSNotFound)
1020                urlString = [NSString stringWithFormat: @"http://www.%@.com/%@",
1021                                [urlString substringToIndex: beforeCom],
1022                                [urlString substringFromIndex: beforeCom + 1]];
1023            else
1024                urlString = [NSString stringWithFormat: @"http://www.%@.com/", urlString];
1025        }
1026        else
1027            urlString = [@"http://" stringByAppendingString: urlString];
1028    }
1029   
1030    NSURL * url = [NSURL URLWithString: urlString];
1031    [self performSelectorOnMainThread: @selector(openURL:) withObject: url waitUntilDone: NO];
1032}
1033
1034- (void) createFile: (id) sender
1035{
1036    [CreatorWindowController createTorrentFile: fLib];
1037}
1038
1039- (void) resumeSelectedTorrents: (id) sender
1040{
1041    [self resumeTorrents: [fTableView selectedTorrents]];
1042}
1043
1044- (void) resumeAllTorrents: (id) sender
1045{
1046    [self resumeTorrents: fTorrents];
1047}
1048
1049- (void) resumeTorrents: (NSArray *) torrents
1050{
1051    for (Torrent * torrent in torrents)
1052        [torrent setWaitToStart: YES];
1053   
1054    [self updateTorrentsInQueue];
1055}
1056
1057- (void) resumeSelectedTorrentsNoWait:  (id) sender
1058{
1059    [self resumeTorrentsNoWait: [fTableView selectedTorrents]];
1060}
1061
1062- (void) resumeWaitingTorrents: (id) sender
1063{
1064    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1065   
1066    for (Torrent * torrent in fTorrents)
1067        if (![torrent isActive] && [torrent waitingToStart])
1068            [torrents addObject: torrent];
1069   
1070    [self resumeTorrentsNoWait: torrents];
1071}
1072
1073- (void) resumeTorrentsNoWait: (NSArray *) torrents
1074{
1075    //iterate through instead of all at once to ensure no conflicts
1076    for (Torrent * torrent in torrents)
1077        [torrent startTransfer];
1078   
1079    [self updateUI];
1080    [self applyFilter: nil];
1081    [self updateTorrentHistory];
1082}
1083
1084- (void) stopSelectedTorrents: (id) sender
1085{
1086    [self stopTorrents: [fTableView selectedTorrents]];
1087}
1088
1089- (void) stopAllTorrents: (id) sender
1090{
1091    [self stopTorrents: fTorrents];
1092}
1093
1094- (void) stopTorrents: (NSArray *) torrents
1095{
1096    //don't want any of these starting then stopping
1097    for (Torrent * torrent in torrents)
1098        [torrent setWaitToStart: NO];
1099
1100    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
1101   
1102    [self updateUI];
1103    [self applyFilter: nil];
1104    [self updateTorrentHistory];
1105}
1106
1107- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
1108{
1109    [torrents retain];
1110    NSInteger active = 0, downloading = 0;
1111
1112    if ([fDefaults boolForKey: @"CheckRemove"])
1113    {
1114        for (Torrent * torrent in torrents)
1115            if ([torrent isActive])
1116            {
1117                active++;
1118                if (![torrent isSeeding])
1119                    downloading++;
1120            }
1121
1122        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
1123        {
1124            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
1125                                    torrents, @"Torrents",
1126                                    [NSNumber numberWithBool: deleteData], @"DeleteData",
1127                                    [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
1128           
1129            NSString * title, * message;
1130           
1131            NSInteger selected = [torrents count];
1132            if (selected == 1)
1133            {
1134                NSString * torrentName = [[torrents objectAtIndex: 0] name];
1135               
1136                if (!deleteData && !deleteTorrent)
1137                    title = [NSString stringWithFormat:
1138                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1139                                "Removal confirm panel -> title"), torrentName];
1140                else if (deleteData && !deleteTorrent)
1141                    title = [NSString stringWithFormat:
1142                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1143                                " and trash the data file?", "Removal confirm panel -> title"), torrentName];
1144                else if (!deleteData && deleteTorrent)
1145                    title = [NSString stringWithFormat:
1146                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1147                                " and trash the torrent file?", "Removal confirm panel -> title"), torrentName];
1148                else
1149                    title = [NSString stringWithFormat:
1150                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1151                                " and trash both the data and torrent files?", "Removal confirm panel -> title"), torrentName];
1152               
1153                message = NSLocalizedString(@"This transfer is active."
1154                            " Once removed, continuing the transfer will require the torrent file.",
1155                            "Removal confirm panel -> message");
1156            }
1157            else
1158            {
1159                if (!deleteData && !deleteTorrent)
1160                    title = [NSString stringWithFormat:
1161                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list?",
1162                                "Removal confirm panel -> title"), selected];
1163                else if (deleteData && !deleteTorrent)
1164                    title = [NSString stringWithFormat:
1165                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1166                                " and trash the data file?", "Removal confirm panel -> title"), selected];
1167                else if (!deleteData && deleteTorrent)
1168                    title = [NSString stringWithFormat:
1169                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1170                                " and trash the torrent file?", "Removal confirm panel -> title"), selected];
1171                else
1172                    title = [NSString stringWithFormat:
1173                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1174                                " and trash both the data and torrent files?", "Removal confirm panel -> title"), selected];
1175               
1176                if (selected == active)
1177                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
1178                                "Removal confirm panel -> message part 1"), active];
1179                else
1180                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
1181                                "Removal confirm panel -> message part 1"), selected, active];
1182                message = [message stringByAppendingFormat: @" %@",
1183                                NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files.",
1184                                "Removal confirm panel -> message part 2")];
1185            }
1186           
1187            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
1188                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
1189                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
1190            return;
1191        }
1192    }
1193   
1194    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
1195}
1196
1197- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (NSDictionary *) dict
1198{
1199    NSArray * torrents = [dict objectForKey: @"Torrents"];
1200    if (returnCode == NSAlertDefaultReturn)
1201        [self confirmRemoveTorrents: torrents deleteData: [[dict objectForKey: @"DeleteData"] boolValue]
1202                deleteTorrent: [[dict objectForKey: @"DeleteTorrent"] boolValue]];
1203    else
1204        [torrents release];
1205   
1206    [dict release];
1207}
1208
1209- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
1210{
1211    //don't want any of these starting then stopping
1212    for (Torrent * torrent in torrents)
1213        [torrent setWaitToStart: NO];
1214   
1215    [fTorrents removeObjectsInArray: torrents];
1216   
1217    for (Torrent * torrent in torrents)
1218    {
1219        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1220        [fTableView removeCollapsedGroup: [torrent groupValue]];
1221       
1222        if (deleteData)
1223            [torrent trashData];
1224        if (deleteTorrent)
1225            [torrent trashTorrent];
1226       
1227        [torrent closeRemoveTorrent];
1228    }
1229   
1230    [torrents release];
1231   
1232    [fTableView deselectAll: nil];
1233   
1234    [self updateTorrentsInQueue];
1235}
1236
1237- (void) removeNoDelete: (id) sender
1238{
1239    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: NO];
1240}
1241
1242- (void) removeDeleteData: (id) sender
1243{
1244    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: NO];
1245}
1246
1247- (void) removeDeleteTorrent: (id) sender
1248{
1249    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: YES];
1250}
1251
1252- (void) removeDeleteDataAndTorrent: (id) sender
1253{
1254    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: YES];
1255}
1256
1257- (void) moveDataFilesSelected: (id) sender
1258{
1259    [self moveDataFiles: [fTableView selectedTorrents]];
1260}
1261
1262- (void) moveDataFiles: (NSArray *) torrents
1263{
1264    NSOpenPanel * panel = [NSOpenPanel openPanel];
1265    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1266    [panel setAllowsMultipleSelection: NO];
1267    [panel setCanChooseFiles: NO];
1268    [panel setCanChooseDirectories: YES];
1269    [panel setCanCreateDirectories: YES];
1270   
1271    torrents = [torrents retain];
1272    NSInteger count = [torrents count];
1273    if (count == 1)
1274        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1275                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1276    else
1277        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1278                            "Move torrent -> select destination folder"), count]];
1279       
1280    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1281        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1282}
1283
1284- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) torrents
1285{
1286    if (code == NSOKButton)
1287    {
1288        for (Torrent * torrent in torrents)
1289            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1290    }
1291   
1292    [torrents release];
1293}
1294
1295- (void) copyTorrentFiles: (id) sender
1296{
1297    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1298}
1299
1300- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1301{
1302    if ([torrents count] <= 0)
1303    {
1304        [torrents release];
1305        return;
1306    }
1307
1308    Torrent * torrent = [torrents objectAtIndex: 0];
1309
1310    //warn user if torrent file can't be found
1311    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1312    {
1313        NSAlert * alert = [[NSAlert alloc] init];
1314        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1315        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1316                                "Torrent file copy alert -> title"), [torrent name]]];
1317        [alert setInformativeText: [NSString stringWithFormat:
1318                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1319                                    [torrent torrentLocation]]];
1320        [alert setAlertStyle: NSWarningAlertStyle];
1321       
1322        [alert runModal];
1323        [alert release];
1324       
1325        [torrents removeObjectAtIndex: 0];
1326        [self copyTorrentFileForTorrents: torrents];
1327    }
1328    else
1329    {
1330        NSSavePanel * panel = [NSSavePanel savePanel];
1331        [panel setRequiredFileType: @"org.bittorrent.torrent"];
1332        [panel setCanSelectHiddenExtension: YES];
1333       
1334        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1335            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1336    }
1337}
1338
1339- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSMutableArray *) torrents
1340{
1341    //copy torrent to new location with name of data file
1342    if (code == NSOKButton)
1343        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1344   
1345    [torrents removeObjectAtIndex: 0];
1346    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1347}
1348
1349- (void) revealFile: (id) sender
1350{
1351    for (Torrent * torrent in [fTableView selectedTorrents])
1352        [torrent revealData];
1353}
1354
1355- (void) announceSelectedTorrents: (id) sender
1356{
1357    for (Torrent * torrent in [fTableView selectedTorrents])
1358    {
1359        if ([torrent canManualAnnounce])
1360            [torrent manualAnnounce];
1361    }
1362}
1363
1364- (void) verifySelectedTorrents: (id) sender
1365{
1366    [self verifyTorrents: [fTableView selectedTorrents]];
1367}
1368
1369- (void) verifyTorrents: (NSArray *) torrents
1370{
1371    for (Torrent * torrent in torrents)
1372        [torrent resetCache];
1373   
1374    [self applyFilter: nil];
1375}
1376
1377- (void) showPreferenceWindow: (id) sender
1378{
1379    NSWindow * window = [fPrefsController window];
1380    if (![window isVisible])
1381        [window center];
1382
1383    [window makeKeyAndOrderFront: nil];
1384}
1385
1386- (void) showAboutWindow: (id) sender
1387{
1388    [[AboutWindowController aboutController] showWindow: nil];
1389}
1390
1391- (void) showInfo: (id) sender
1392{
1393    if ([[fInfoController window] isVisible])
1394        [fInfoController close];
1395    else
1396    {
1397        [fInfoController updateInfoStats];
1398        [[fInfoController window] orderFront: nil];
1399    }
1400}
1401
1402- (void) resetInfo
1403{
1404    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1405    [[QuickLookController quickLook] updateQuickLook];
1406}
1407
1408- (void) setInfoTab: (id) sender
1409{
1410    if (sender == fNextInfoTabItem)
1411        [fInfoController setNextTab];
1412    else
1413        [fInfoController setPreviousTab];
1414}
1415
1416- (void) showMessageWindow: (id) sender
1417{
1418    [fMessageController showWindow: nil];
1419}
1420
1421- (void) showStatsWindow: (id) sender
1422{
1423    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1424}
1425
1426- (void) updateUI
1427{
1428    [fTorrents makeObjectsPerformSelector: @selector(update)];
1429   
1430    if (![NSApp isHidden])
1431    {
1432        if ([fWindow isVisible])
1433        {
1434            [self sortTorrents];
1435           
1436            //update status bar
1437            if (![fStatusBar isHidden])
1438            {
1439                //set rates
1440                [fTotalDLField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_DOWN)]];
1441                [fTotalULField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_UP)]];
1442               
1443                //set status button text
1444                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1445                BOOL total;
1446                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1447                {
1448                    tr_session_stats stats;
1449                    if (total)
1450                        tr_sessionGetCumulativeStats(fLib, &stats);
1451                    else
1452                        tr_sessionGetStats(fLib, &stats);
1453                   
1454                    statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") stringByAppendingFormat: @": %@",
1455                                    [NSString stringForRatio: stats.ratio]];
1456                }
1457                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1458                {
1459                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1460                   
1461                    tr_session_stats stats;
1462                    if (total)
1463                        tr_sessionGetCumulativeStats(fLib, &stats);
1464                    else
1465                        tr_sessionGetStats(fLib, &stats);
1466                   
1467                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1468                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1469                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1470                }
1471               
1472                [fStatusButton setTitle: statusString];
1473                [self resizeStatusButton];
1474            }
1475        }
1476
1477        //update non-constant parts of info window
1478        if ([[fInfoController window] isVisible])
1479            [fInfoController updateInfoStats];
1480    }
1481   
1482    //badge dock
1483    [fBadger updateBadge];
1484}
1485
1486- (void) resizeStatusButton
1487{
1488    [fStatusButton sizeToFit];
1489   
1490    //width ends up being too long
1491    NSRect statusFrame = [fStatusButton frame];
1492    statusFrame.size.width -= 25.0;
1493   
1494    CGFloat difference = NSMaxX(statusFrame) + 5.0 - [fTotalDLImageView frame].origin.x;
1495    if (difference > 0)
1496        statusFrame.size.width -= difference;
1497   
1498    [fStatusButton setFrame: statusFrame];
1499}
1500
1501- (void) setBottomCountText: (BOOL) filtering
1502{
1503    NSString * totalTorrentsString;
1504    NSInteger totalCount = [fTorrents count];
1505    if (totalCount != 1)
1506        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1507    else
1508        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1509   
1510    if (filtering)
1511    {
1512        NSInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1513        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1514            count -= [fDisplayedTorrents count];
1515       
1516        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d of %@", "Status bar transfer count"),
1517                                count, totalTorrentsString];
1518    }
1519   
1520    [fTotalTorrentsField setStringValue: totalTorrentsString];
1521}
1522
1523- (void) updateSpeedFieldsToolTips
1524{
1525    NSString * uploadText, * downloadText;
1526   
1527    if ([fDefaults boolForKey: @"SpeedLimit"])
1528    {
1529        NSString * speedString = [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1530                                    NSLocalizedString(@"Speed Limit", "Status Bar -> speed tooltip")];
1531       
1532        uploadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]];
1533        downloadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]];
1534    }
1535    else
1536    {
1537        if ([fDefaults boolForKey: @"CheckUpload"])
1538            uploadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1539                            [fDefaults integerForKey: @"UploadLimit"]];
1540        else
1541            uploadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1542       
1543        if ([fDefaults boolForKey: @"CheckDownload"])
1544            downloadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1545                            [fDefaults integerForKey: @"DownloadLimit"]];
1546        else
1547            downloadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1548    }
1549   
1550    uploadText = [NSLocalizedString(@"Total upload rate", "Status Bar -> speed tooltip")
1551                    stringByAppendingFormat: @": %@", uploadText];
1552    downloadText = [NSLocalizedString(@"Total download rate", "Status Bar -> speed tooltip")
1553                    stringByAppendingFormat: @": %@", downloadText];
1554   
1555    [fTotalULField setToolTip: uploadText];
1556    [fTotalDLField setToolTip: downloadText];
1557}
1558
1559- (void) updateTorrentsInQueue
1560{
1561    BOOL download = [fDefaults boolForKey: @"Queue"],
1562        seed = [fDefaults boolForKey: @"QueueSeed"];
1563   
1564    NSInteger desiredDownloadActive = [self numToStartFromQueue: YES],
1565        desiredSeedActive = [self numToStartFromQueue: NO];
1566   
1567    for (Torrent * torrent in fTorrents)
1568    {
1569        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1570        {
1571            if (![torrent allDownloaded])
1572            {
1573                if (!download || desiredDownloadActive > 0)
1574                {
1575                    [torrent startTransfer];
1576                    if ([torrent isActive])
1577                        desiredDownloadActive--;
1578                    [torrent update];
1579                }
1580            }
1581            else
1582            {
1583                if (!seed || desiredSeedActive > 0)
1584                {
1585                    [torrent startTransfer];
1586                    if ([torrent isActive])
1587                        desiredSeedActive--;
1588                    [torrent update];
1589                }
1590            }
1591        }
1592    }
1593   
1594    [self updateUI];
1595    [self applyFilter: nil];
1596    [self updateTorrentHistory];
1597}
1598
1599- (NSInteger) numToStartFromQueue: (BOOL) downloadQueue
1600{
1601    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1602        return 0;
1603   
1604    NSInteger desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1605       
1606    for (Torrent * torrent in fTorrents)
1607    {
1608        if ([torrent isChecking])
1609        {
1610            desired--;
1611            if (desired <= 0)
1612                return 0;
1613        }
1614        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1615        {
1616            if ([torrent allDownloaded] != downloadQueue)
1617            {
1618                desired--;
1619                if (desired <= 0)
1620                    return 0;
1621            }
1622        }
1623        else;
1624    }
1625   
1626    return desired;
1627}
1628
1629- (void) torrentFinishedDownloading: (NSNotification *) notification
1630{
1631    Torrent * torrent = [notification object];
1632   
1633    if ([torrent isActive])
1634    {
1635        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1636        {
1637            NSSound * sound;
1638            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1639            {
1640                [sound setDelegate: self];
1641                fSoundPlaying = YES;
1642                [sound play];
1643            }
1644        }
1645       
1646        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1647                                        [torrent dataLocation] , @"Location", nil];
1648        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1649                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1650                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1651       
1652        if (![fWindow isMainWindow])
1653            [fBadger incrementCompleted];
1654       
1655        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1656        {
1657            [torrent stopTransfer];
1658            [torrent setWaitToStart: YES];
1659        }
1660    }
1661   
1662    [self updateTorrentsInQueue];
1663}
1664
1665- (void) torrentRestartedDownloading: (NSNotification *) notification
1666{
1667    Torrent * torrent = [notification object];
1668    if ([torrent isActive])
1669    {
1670        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1671        {
1672            [torrent stopTransfer];
1673            [torrent setWaitToStart: YES];
1674        }
1675    }
1676   
1677    [self updateTorrentsInQueue];
1678}
1679
1680- (void) torrentStoppedForRatio: (NSNotification *) notification
1681{
1682    Torrent * torrent = [notification object];
1683   
1684    [self updateTorrentsInQueue];
1685   
1686    if ([[fTableView selectedTorrents] containsObject: torrent])
1687    {
1688        [fInfoController updateInfoStats];
1689        [fInfoController updateOptions];
1690    }
1691   
1692    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1693    {
1694        NSSound * sound;
1695        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1696        {
1697            [sound setDelegate: self];
1698            fSoundPlaying = YES;
1699            [sound play];
1700        }
1701    }
1702   
1703    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
1704                                    [torrent dataLocation], @"Location", nil];
1705    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1706                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1707                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1708}
1709
1710- (void) updateTorrentHistory
1711{
1712    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1713   
1714    for (Torrent * torrent in fTorrents)
1715        [history addObject: [torrent history]];
1716   
1717    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER] atomically: YES];
1718}
1719
1720- (void) setSort: (id) sender
1721{
1722    NSString * sortType;
1723    switch ([sender tag])
1724    {
1725        case SORT_ORDER_TAG:
1726            sortType = SORT_ORDER;
1727            [fDefaults setBool: NO forKey: @"SortReverse"];
1728            break;
1729        case SORT_DATE_TAG:
1730            sortType = SORT_DATE;
1731            break;
1732        case SORT_NAME_TAG:
1733            sortType = SORT_NAME;
1734            break;
1735        case SORT_PROGRESS_TAG:
1736            sortType = SORT_PROGRESS;
1737            break;
1738        case SORT_STATE_TAG:
1739            sortType = SORT_STATE;
1740            break;
1741        case SORT_TRACKER_TAG:
1742            sortType = SORT_TRACKER;
1743            break;
1744        case SORT_ACTIVITY_TAG:
1745            sortType = SORT_ACTIVITY;
1746            break;
1747        default:
1748            return;
1749    }
1750   
1751    [fDefaults setObject: sortType forKey: @"Sort"];
1752    [self sortTorrents];
1753}
1754
1755- (void) setSortByGroup: (id) sender
1756{
1757    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1758    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1759   
1760    //expand all groups
1761    if (sortByGroup)
1762        [fTableView removeAllCollapsedGroups];
1763   
1764    [self applyFilter: nil];
1765}
1766
1767- (void) setSortReverse: (id) sender
1768{
1769    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1770    [self sortTorrents];
1771}
1772
1773- (void) sortTorrents
1774{
1775    NSArray * selectedValues = [fTableView selectedValues];
1776   
1777    [self sortTorrentsIgnoreSelected]; //actually sort
1778   
1779    [fTableView selectValues: selectedValues];
1780}
1781
1782- (void) sortTorrentsIgnoreSelected
1783{
1784    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1785    const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1786   
1787    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1788                                            selector: @selector(compareFinder:)] autorelease];
1789   
1790    NSArray * descriptors = nil;
1791    if ([sortType isEqualToString: SORT_NAME])
1792        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, nil];
1793    else if ([sortType isEqualToString: SORT_STATE])
1794    {
1795        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1796                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1797                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1798       
1799        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1800                                                            nameDescriptor, nil];
1801    }
1802    else if ([sortType isEqualToString: SORT_PROGRESS])
1803    {
1804        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1805                        * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1806                                                        ascending: asc] autorelease],
1807                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1808       
1809        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1810                                                            nameDescriptor, nil];
1811    }
1812    else if ([sortType isEqualToString: SORT_TRACKER])
1813    {
1814        NSSortDescriptor * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddressAnnounce" ascending: asc
1815                                                selector: @selector(localizedCaseInsensitiveCompare:)] autorelease];
1816       
1817        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, nil];
1818    }
1819    else if ([sortType isEqualToString: SORT_ACTIVITY])
1820    {
1821        NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1822        NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1823                                                    autorelease];
1824       
1825        descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
1826    }
1827    else if ([sortType isEqualToString: SORT_DATE])
1828    {
1829        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1830   
1831        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
1832    }
1833    else; //no need to sort by queue order
1834   
1835    //actually sort
1836    if (descriptors)
1837    {
1838        if ([fDefaults boolForKey: @"SortByGroup"])
1839        {
1840            for (TorrentGroup * group in fDisplayedTorrents)
1841                [[group torrents] sortUsingDescriptors: descriptors];
1842        }
1843        else
1844            [fDisplayedTorrents sortUsingDescriptors: descriptors];
1845       
1846        [descriptors release];
1847    }
1848   
1849    [fTableView reloadData];
1850}
1851
1852- (void) applyFilter: (id) sender
1853{
1854    //get all the torrents in the table
1855    NSMutableArray * previousTorrents;
1856    if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1857    {
1858        previousTorrents = [NSMutableArray array];
1859       
1860        for (TorrentGroup * group in fDisplayedTorrents)
1861            [previousTorrents addObjectsFromArray: [group torrents]];
1862    }
1863    else
1864        previousTorrents = fDisplayedTorrents;
1865   
1866    NSArray * selectedValues = [fTableView selectedValues];
1867   
1868    NSInteger active = 0, downloading = 0, seeding = 0, paused = 0;
1869    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1870    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1871    if ([filterType isEqualToString: FILTER_ACTIVE])
1872        filterActive = YES;
1873    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1874        filterDownload = YES;
1875    else if ([filterType isEqualToString: FILTER_SEED])
1876        filterSeed = YES;
1877    else if ([filterType isEqualToString: FILTER_PAUSE])
1878        filterPause = YES;
1879    else
1880        filterStatus = NO;
1881   
1882    NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
1883    BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
1884   
1885    NSString * searchString = [fSearchFilterField stringValue];
1886    BOOL filterText = [searchString length] > 0,
1887        filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
1888   
1889    NSMutableArray * allTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1890   
1891    //get count of each type
1892    for (Torrent * torrent in fTorrents)
1893    {
1894        //check status
1895        if ([torrent isActive] && ![torrent isCheckingWaiting])
1896        {
1897            if ([torrent isSeeding])
1898            {
1899                seeding++;
1900                BOOL isActive = ![torrent isStalled];
1901                if (isActive)
1902                    active++;
1903               
1904                if (filterStatus && !((filterActive && isActive) || filterSeed))
1905                    continue;
1906            }
1907            else
1908            {
1909                downloading++;
1910                BOOL isActive = ![torrent isStalled];
1911                if (isActive)
1912                    active++;
1913               
1914                if (filterStatus && !((filterActive && isActive) || filterDownload))
1915                    continue;
1916            }
1917        }
1918        else
1919        {
1920            paused++;
1921            if (filterStatus && !filterPause)
1922                continue;
1923        }
1924       
1925        //checkGroup
1926        if (filterGroup)
1927            if ([torrent groupValue] != groupFilterValue)
1928                continue;
1929       
1930        //check text field
1931        if (filterText)
1932        {
1933            if (filterTracker)
1934            {
1935                BOOL removeTextField = YES;
1936                for (NSString * tracker in [torrent allTrackers: NO])
1937                {
1938                    if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1939                    {
1940                        removeTextField = NO;
1941                        break;
1942                    }
1943                }
1944               
1945                if (removeTextField)
1946                    continue;
1947            }
1948            else
1949            {
1950                if ([[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound)
1951                    continue;
1952            }
1953        }
1954       
1955        [allTorrents addObject: torrent];
1956    }
1957   
1958    //set button tooltips
1959    [fNoFilterButton setCount: [fTorrents count]];
1960    [fActiveFilterButton setCount: active];
1961    [fDownloadFilterButton setCount: downloading];
1962    [fSeedFilterButton setCount: seeding];
1963    [fPauseFilterButton setCount: paused];
1964   
1965    //clear display cache for not-shown torrents
1966    [previousTorrents removeObjectsInArray: allTorrents];
1967    for (Torrent * torrent in previousTorrents)
1968        [torrent setPreviousFinishedPieces: nil];
1969   
1970    //place torrents into groups
1971    const BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"];
1972    if (groupRows)
1973    {
1974        NSMutableArray * oldTorrentGroups = [NSMutableArray array];
1975        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1976            [oldTorrentGroups addObjectsFromArray: fDisplayedTorrents];
1977       
1978        [fDisplayedTorrents removeAllObjects];
1979       
1980        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
1981        [allTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
1982       
1983        NSMutableArray * groupTorrents;
1984        NSInteger lastGroupValue = -2, currentOldGroupIndex = 0;
1985        for (Torrent * torrent in allTorrents)
1986        {
1987            NSInteger groupValue = [torrent groupValue];
1988            if (groupValue != lastGroupValue)
1989            {
1990                lastGroupValue = groupValue;
1991               
1992                TorrentGroup * group = nil;
1993               
1994                //try to see if the group already exists
1995                for (; currentOldGroupIndex < [oldTorrentGroups count]; currentOldGroupIndex++)
1996                {
1997                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
1998                    const NSInteger currentGroupValue = [currentGroup groupIndex];
1999                    if (currentGroupValue == groupValue)
2000                    {
2001                        group = currentGroup;
2002                        [[currentGroup torrents] removeAllObjects];
2003                       
2004                        currentOldGroupIndex++;
2005                    }
2006                   
2007                    if (currentGroupValue >= groupValue)
2008                        break;
2009                }
2010               
2011                if (!group)
2012                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2013                [fDisplayedTorrents addObject: group];
2014               
2015                groupTorrents = [group torrents];
2016            }
2017           
2018            [groupTorrents addObject: torrent];
2019        }
2020    }
2021    else
2022        [fDisplayedTorrents setArray: allTorrents];
2023   
2024    //actually sort
2025    [self sortTorrentsIgnoreSelected];
2026   
2027    //reset expanded/collapsed rows
2028    if (groupRows)
2029    {
2030        for (TorrentGroup * group in fDisplayedTorrents)
2031        {
2032            if ([fTableView isGroupCollapsed: [group groupIndex]])
2033                [fTableView collapseItem: group];
2034            else
2035                [fTableView expandItem: group];
2036        }
2037    }
2038   
2039    [fTableView selectValues: selectedValues];
2040    [self resetInfo]; //if group is already selected, but the torrents in it change
2041   
2042    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2043   
2044    [self setWindowSizeToFit];
2045}
2046
2047//resets filter and sorts torrents
2048- (void) setFilter: (id) sender
2049{
2050    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2051   
2052    NSButton * prevFilterButton;
2053    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2054        prevFilterButton = fPauseFilterButton;
2055    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2056        prevFilterButton = fActiveFilterButton;
2057    else if ([oldFilterType isEqualToString: FILTER_SEED])
2058        prevFilterButton = fSeedFilterButton;
2059    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2060        prevFilterButton = fDownloadFilterButton;
2061    else
2062        prevFilterButton = fNoFilterButton;
2063   
2064    if (sender != prevFilterButton)
2065    {
2066        [prevFilterButton setState: NSOffState];
2067        [sender setState: NSOnState];
2068
2069        NSString * filterType;
2070        if (sender == fActiveFilterButton)
2071            filterType = FILTER_ACTIVE;
2072        else if (sender == fDownloadFilterButton)
2073            filterType = FILTER_DOWNLOAD;
2074        else if (sender == fPauseFilterButton)
2075            filterType = FILTER_PAUSE;
2076        else if (sender == fSeedFilterButton)
2077            filterType = FILTER_SEED;
2078        else
2079            filterType = FILTER_NONE;
2080
2081        [fDefaults setObject: filterType forKey: @"Filter"];
2082    }
2083    else
2084        [sender setState: NSOnState];
2085
2086    [self applyFilter: nil];
2087}
2088
2089- (void) setFilterSearchType: (id) sender
2090{
2091    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2092   
2093    NSInteger prevTag, currentTag = [sender tag];
2094    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2095        prevTag = FILTER_TYPE_TAG_TRACKER;
2096    else
2097        prevTag = FILTER_TYPE_TAG_NAME;
2098   
2099    if (currentTag != prevTag)
2100    {
2101        NSString * filterType;
2102        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2103            filterType = FILTER_TYPE_TRACKER;
2104        else
2105            filterType = FILTER_TYPE_NAME;
2106       
2107        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2108       
2109        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2110    }
2111   
2112    [self applyFilter: nil];
2113}
2114
2115- (void) switchFilter: (id) sender
2116{
2117    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2118   
2119    NSButton * button;
2120    if ([filterType isEqualToString: FILTER_NONE])
2121        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2122    else if ([filterType isEqualToString: FILTER_ACTIVE])
2123        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2124    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2125        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2126    else if ([filterType isEqualToString: FILTER_SEED])
2127        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2128    else if ([filterType isEqualToString: FILTER_PAUSE])
2129        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2130    else
2131        button = fNoFilterButton;
2132   
2133    [self setFilter: button];
2134}
2135
2136- (void) setStatusLabel: (id) sender
2137{
2138    NSString * statusLabel;
2139    switch ([sender tag])
2140    {
2141        case STATUS_RATIO_TOTAL_TAG:
2142            statusLabel = STATUS_RATIO_TOTAL;
2143            break;
2144        case STATUS_RATIO_SESSION_TAG:
2145            statusLabel = STATUS_RATIO_SESSION;
2146            break;
2147        case STATUS_TRANSFER_TOTAL_TAG:
2148            statusLabel = STATUS_TRANSFER_TOTAL;
2149            break;
2150        case STATUS_TRANSFER_SESSION_TAG:
2151            statusLabel = STATUS_TRANSFER_SESSION;
2152            break;
2153        default:
2154            return;
2155    }
2156   
2157    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2158    [self updateUI];
2159}
2160
2161- (void) menuNeedsUpdate: (NSMenu *) menu
2162{
2163    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu || menu == fGroupFilterMenu)
2164    {
2165        const BOOL filter = menu == fGroupFilterMenu;
2166       
2167        const NSInteger remaining = filter ? 3 : 0;
2168        for (NSInteger i = [menu numberOfItems]-1; i >= remaining; i--)
2169            [menu removeItemAtIndex: i];
2170       
2171        NSMenu * groupMenu;
2172        if (!filter)
2173            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2174        else
2175            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:) isSmall: YES];
2176       
2177        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2178        for (NSInteger i = 0; i < groupMenuCount; i++)
2179        {
2180            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2181            [groupMenu removeItemAtIndex: 0];
2182            [menu addItem: item];
2183            [item release];
2184        }
2185    }
2186    else if (menu == fUploadMenu || menu == fDownloadMenu)
2187    {
2188        if ([menu numberOfItems] > 3)
2189            return;
2190       
2191        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, -1 };
2192       
2193        NSMenuItem * item;
2194        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2195        {
2196            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2197                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2198                    keyEquivalent: @""];
2199            [item setTarget: self];
2200            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2201            [menu addItem: item];
2202            [item release];
2203        }
2204    }
2205    else if (menu == fRatioStopMenu)
2206    {
2207        if ([menu numberOfItems] > 3)
2208            return;
2209       
2210        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2211       
2212        NSMenuItem * item;
2213        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2214        {
2215            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2216                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2217            [item setTarget: self];
2218            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2219            [menu addItem: item];
2220            [item release];
2221        }
2222    }
2223    else;
2224}
2225
2226- (void) setGroup: (id) sender
2227{
2228    for (Torrent * torrent in [fTableView selectedTorrents])
2229    {
2230        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2231       
2232        [torrent setGroupValue: [sender tag]];
2233    }
2234   
2235    [self applyFilter: nil];
2236    [self updateUI];
2237    [self updateTorrentHistory];
2238}
2239
2240- (void) setGroupFilter: (id) sender
2241{
2242    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2243    [self updateGroupsFilterButton];
2244    [self applyFilter: nil];
2245}
2246
2247- (void) updateGroupsFilterButton
2248{
2249    NSInteger groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2250   
2251    NSImage * icon;
2252    NSString * toolTip;
2253    if (groupIndex == GROUP_FILTER_ALL_TAG)
2254    {
2255        icon = [NSImage imageNamed: @"PinTemplate.png"];
2256        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2257    }
2258    else
2259    {
2260        icon = [[GroupsController groups] imageForIndex: groupIndex];
2261        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2262                                                : NSLocalizedString(@"None", "Groups -> Button");
2263        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2264    }
2265   
2266    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2267    [fGroupsButton setToolTip: toolTip];
2268}
2269
2270- (void) updateGroupsFilters: (NSNotification *) notification
2271{
2272    [self updateGroupsFilterButton];
2273    [self applyFilter: nil];
2274}
2275
2276- (void) toggleSpeedLimit: (id) sender
2277{
2278    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2279    [self speedLimitChanged: sender];
2280}
2281
2282- (void) speedLimitChanged: (id) sender
2283{
2284    [fPrefsController applySpeedSettings: nil];
2285}
2286
2287- (void) autoSpeedLimitChange: (NSNotification *) notification
2288{
2289    //clear timer here in case it's not being reset
2290    [fSpeedLimitTimer invalidate];
2291    fSpeedLimitTimer = nil;
2292   
2293    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2294        return;
2295   
2296    NSCalendar * calendar = [NSCalendar currentCalendar];
2297    NSDateComponents * nowComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2298                    * onComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2299                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]],
2300                    * offComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2301                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]];
2302   
2303    //check if should be on if within range
2304    NSInteger onTime = [onComponents hour] * 60 + [onComponents minute],
2305        offTime = [offComponents hour] * 60 + [offComponents minute],
2306        nowTime = [nowComponents hour] * 60 + [nowComponents minute];
2307   
2308    BOOL shouldBeOn = NO;
2309    if (onTime < offTime)
2310        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2311    else if (onTime > offTime)
2312        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2313    else;
2314   
2315    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2316        [self toggleSpeedLimit: nil];
2317   
2318    //no need to set the timer if both times are equal
2319    if (onTime == offTime)
2320        return;
2321   
2322    [self setAutoSpeedLimitTimer: !shouldBeOn];
2323}
2324
2325//only called by fSpeedLimitTimer
2326- (void) autoSpeedLimit: (NSTimer *) timer
2327{
2328    BOOL shouldLimit = [[timer userInfo] boolValue];
2329   
2330    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldLimit)
2331    {
2332        [self toggleSpeedLimit: nil];
2333       
2334        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2335                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2336                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2337            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2338            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2339    }
2340   
2341    [self setAutoSpeedLimitTimer: !shouldLimit];
2342}
2343
2344- (void) setAutoSpeedLimitTimer: (BOOL) nextIsLimit
2345{
2346    NSDate * timerDate = [fDefaults objectForKey: nextIsLimit ? @"SpeedLimitAutoOnDate" : @"SpeedLimitAutoOffDate"];
2347   
2348    //create date with combination of the current date and the date to go off
2349    NSCalendar * calendar = [NSCalendar currentCalendar];
2350    NSDateComponents * nowComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
2351                                        | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2352                    * timerComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: timerDate];
2353   
2354    //check if should be the next day
2355    NSInteger nowTime = [nowComponents hour] * 60 + [nowComponents minute],
2356        timerTime = [timerComponents hour] * 60 + [timerComponents minute];
2357    if (timerTime < nowTime)
2358        [nowComponents setDay: [nowComponents day] + 1]; //properly goes to next month when appropriate
2359   
2360    [nowComponents setHour: [timerComponents hour]];
2361    [nowComponents setMinute: [timerComponents minute]];
2362    [nowComponents setSecond: 0];
2363   
2364    NSDate * dateToUse = [calendar dateFromComponents: nowComponents];
2365   
2366    fSpeedLimitTimer = [[NSTimer alloc] initWithFireDate: dateToUse interval: 0 target: self selector: @selector(autoSpeedLimit:)
2367                        userInfo: [NSNumber numberWithBool: nextIsLimit] repeats: NO];
2368   
2369    NSRunLoop * loop = [NSRunLoop mainRunLoop];
2370    [loop addTimer: fSpeedLimitTimer forMode: NSDefaultRunLoopMode];
2371    [loop addTimer: fSpeedLimitTimer forMode: NSModalPanelRunLoopMode];
2372    [loop addTimer: fSpeedLimitTimer forMode: NSEventTrackingRunLoopMode];
2373    [fSpeedLimitTimer release];
2374}
2375
2376- (void) setLimitGlobalEnabled: (id) sender
2377{
2378    BOOL upload = [sender menu] == fUploadMenu;
2379    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2380   
2381    [fPrefsController applySpeedSettings: nil];
2382}
2383
2384- (void) setQuickLimitGlobal: (id) sender
2385{
2386    BOOL upload = [sender menu] == fUploadMenu;
2387    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2388    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2389   
2390    [fPrefsController updateLimitFields];
2391    [fPrefsController applySpeedSettings: nil];
2392}
2393
2394- (void) setRatioGlobalEnabled: (id) sender
2395{
2396    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2397}
2398
2399- (void) setQuickRatioGlobal: (id) sender
2400{
2401    [fDefaults setBool: YES forKey: @"RatioCheck"];
2402    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2403   
2404    [fPrefsController updateRatioStopField];
2405}
2406
2407- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2408{
2409    fSoundPlaying = NO;
2410}
2411
2412- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2413{
2414    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2415    {
2416        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2417            return;
2418       
2419        if (fAutoImportTimer)
2420        {
2421            if ([fAutoImportTimer isValid])
2422                [fAutoImportTimer invalidate];
2423            [fAutoImportTimer release];
2424            fAutoImportTimer = nil;
2425        }
2426       
2427        //check again in 10 seconds in case torrent file wasn't complete
2428        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2429            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2430       
2431        [self checkAutoImportDirectory];
2432    }
2433}
2434
2435- (void) changeAutoImport
2436{
2437    if (fAutoImportTimer)
2438    {
2439        if ([fAutoImportTimer isValid])
2440            [fAutoImportTimer invalidate];
2441        [fAutoImportTimer release];
2442        fAutoImportTimer = nil;
2443    }
2444   
2445    if (fAutoImportedNames)
2446    {
2447        [fAutoImportedNames release];
2448        fAutoImportedNames = nil;
2449    }
2450   
2451    [self checkAutoImportDirectory];
2452}
2453
2454- (void) checkAutoImportDirectory
2455{
2456    NSString * path;
2457    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2458        return;
2459   
2460    path = [path stringByExpandingTildeInPath];
2461   
2462    NSArray * importedNames;
2463    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2464        return;
2465   
2466    //only check files that have not been checked yet
2467    NSMutableArray * newNames = [importedNames mutableCopy];
2468   
2469    if (fAutoImportedNames)
2470        [newNames removeObjectsInArray: fAutoImportedNames];
2471    else
2472        fAutoImportedNames = [[NSMutableArray alloc] init];
2473    [fAutoImportedNames setArray: importedNames];
2474   
2475    for (NSInteger i = [newNames count] - 1; i >= 0; i--)
2476    {
2477        NSString * file = [newNames objectAtIndex: i];
2478        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2479            [newNames removeObjectAtIndex: i];
2480        else
2481            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2482    }
2483   
2484    for (NSString * file in newNames)
2485    {
2486        tr_ctor * ctor = tr_ctorNew(fLib);
2487        tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2488       
2489        switch (tr_torrentParse(fLib, ctor, NULL))
2490        {
2491            case TR_OK:
2492                [self openFiles: [NSArray arrayWithObject: file] addType: ADD_AUTO forcePath: nil];
2493               
2494                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2495                    description: [file lastPathComponent] notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2496                    clickContext: nil];
2497                break;
2498           
2499            case TR_EINVALID:
2500                [fAutoImportedNames removeObject: [file lastPathComponent]];
2501        }
2502       
2503        tr_ctorFree(ctor);
2504    }
2505   
2506    [newNames release];
2507}
2508
2509- (void) beginCreateFile: (NSNotification *) notification
2510{
2511    if (![fDefaults boolForKey: @"AutoImport"])
2512        return;
2513   
2514    NSString * location = [notification object],
2515            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2516   
2517    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2518                                    isEqualToString: [path stringByExpandingTildeInPath]])
2519        [fAutoImportedNames addObject: [location lastPathComponent]];
2520}
2521
2522- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2523{
2524    if (item)
2525        return [[item torrents] count];
2526    else
2527        return [fDisplayedTorrents count];
2528}
2529
2530- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2531{
2532    if (item)
2533        return [[item torrents] objectAtIndex: index];
2534    else
2535        return [fDisplayedTorrents objectAtIndex: index];
2536}
2537
2538- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2539{
2540    return ![item isKindOfClass: [Torrent class]];
2541}
2542
2543- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2544{
2545    if ([item isKindOfClass: [Torrent class]])
2546        return [item hashString];
2547    else
2548    {
2549        NSString * ident = [tableColumn identifier];
2550        if ([ident isEqualToString: @"Group"])
2551        {
2552            NSInteger group = [item groupIndex];
2553            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2554                                : NSLocalizedString(@"No Group", "Group table row");
2555        }
2556        else if ([ident isEqualToString: @"Color"])
2557        {
2558            NSInteger group = [item groupIndex];
2559            return [[GroupsController groups] imageForIndex: group];
2560        }
2561        else if ([ident isEqualToString: @"DL Image"])
2562            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2563        else if ([ident isEqualToString: @"UL Image"])
2564            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2565                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2566        else
2567        {
2568            TorrentGroup * group = (TorrentGroup *)item;
2569           
2570            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2571                return [NSString stringForRatio: [group ratio]];
2572            else
2573            {
2574                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2575                return [NSString stringForSpeed: rate];
2576            }
2577        }
2578    }
2579}
2580
2581- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2582{
2583    //only allow reordering of rows if sorting by order
2584    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2585    {
2586        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2587        for (id torrent in items)
2588        {
2589            if (![torrent isKindOfClass: [Torrent class]])
2590                return NO;
2591           
2592            [indexSet addIndex: [fTableView rowForItem: torrent]];
2593        }
2594       
2595        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2596        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2597        return YES;
2598    }
2599    return NO;
2600}
2601
2602- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2603    proposedChildIndex: (NSInteger) index
2604{
2605    NSPasteboard * pasteboard = [info draggingPasteboard];
2606    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2607    {
2608        if ([fDefaults boolForKey: @"SortByGroup"])
2609        {
2610            if (!item)
2611                return NSDragOperationNone;
2612           
2613            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2614            {
2615                if ([item isKindOfClass: [Torrent class]])
2616                {
2617                    TorrentGroup * group = [fTableView parentForItem: item];
2618                    index = [[group torrents] indexOfObject: item] + 1;
2619                    item = group;
2620                }
2621            }
2622            else
2623            {
2624                if ([item isKindOfClass: [Torrent class]])
2625                    item = [fTableView parentForItem: item];
2626                index = NSOutlineViewDropOnItemIndex;
2627            }
2628        }
2629        else
2630        {
2631            if (item)
2632            {
2633                index = [fTableView rowForItem: item] + 1;
2634                item = nil;
2635            }
2636        }
2637       
2638        [fTableView setDropItem: item dropChildIndex: index];
2639        return NSDragOperationGeneric;
2640    }
2641   
2642    return NSDragOperationNone;
2643}
2644
2645- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2646    childIndex: (NSInteger) newRow
2647{
2648    NSPasteboard * pasteboard = [info draggingPasteboard];
2649    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2650    {
2651        //remember selected rows
2652        NSArray * selectedValues = [fTableView selectedValues];
2653   
2654        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2655       
2656        //get the torrents to move
2657        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2658        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2659            [movingTorrents addObject: [fTableView itemAtRow: i]];
2660       
2661        //reset groups
2662        if (item)
2663        {
2664            //change groups
2665            NSInteger groupValue = [item groupIndex];
2666            for (Torrent * torrent in movingTorrents)
2667            {
2668                //have to reset objects here to avoid weird crash
2669                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2670                [[item torrents] addObject: torrent];
2671               
2672                [torrent setGroupValue: groupValue];
2673            }
2674            //part 2 of avoiding weird crash
2675            [fTableView reloadItem: nil reloadChildren: YES];
2676        }
2677       
2678        //reorder queue order
2679        if (newRow != NSOutlineViewDropOnItemIndex)
2680        {
2681            //find torrent to place under
2682            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2683            Torrent * topTorrent = nil;
2684            for (NSInteger i = newRow-1; i >= 0; i--)
2685            {
2686                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2687                if (![movingTorrents containsObject: tempTorrent])
2688                {
2689                    topTorrent = tempTorrent;
2690                    break;
2691                }
2692            }
2693           
2694            //remove objects to reinsert
2695            [fTorrents removeObjectsInArray: movingTorrents];
2696           
2697            //insert objects at new location
2698            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2699            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2700            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2701        }
2702       
2703        [self applyFilter: nil];
2704        [fTableView selectValues: selectedValues];
2705    }
2706   
2707    return YES;
2708}
2709
2710- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2711{
2712    [self resetInfo];
2713}
2714
2715- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2716{
2717    NSPasteboard * pasteboard = [info draggingPasteboard];
2718    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2719    {
2720        //check if any torrent files can be added
2721        BOOL torrent = NO;
2722        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2723        for (NSString * file in files)
2724        {
2725            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2726            {
2727                tr_ctor * ctor = tr_ctorNew(fLib);
2728                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2729                switch (tr_torrentParse(fLib, ctor, NULL))
2730                {
2731                    case TR_OK:
2732                        if (!fOverlayWindow)
2733                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2734                        [fOverlayWindow setTorrents: files];
2735                       
2736                        return NSDragOperationCopy;
2737                   
2738                    case TR_EDUPLICATE:
2739                        torrent = YES;
2740                }
2741                tr_ctorFree(ctor);
2742            }
2743        }
2744       
2745        //create a torrent file if a single file
2746        if (!torrent && [files count] == 1)
2747        {
2748            if (!fOverlayWindow)
2749                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2750            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2751           
2752            return NSDragOperationCopy;
2753        }
2754    }
2755    else if ([[pasteboard types] containsObject: NSURLPboardType])
2756    {
2757        if (!fOverlayWindow)
2758            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2759        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2760       
2761        return NSDragOperationCopy;
2762    }
2763    else;
2764   
2765    return NSDragOperationNone;
2766}
2767
2768- (void) draggingExited: (id <NSDraggingInfo>) info
2769{
2770    if (fOverlayWindow)
2771        [fOverlayWindow fadeOut];
2772}
2773
2774- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2775{
2776    if (fOverlayWindow)
2777        [fOverlayWindow fadeOut];
2778   
2779    NSPasteboard * pasteboard = [info draggingPasteboard];
2780    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2781    {
2782        BOOL torrent = NO, accept = YES;
2783       
2784        //create an array of files that can be opened
2785        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2786        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2787        for (NSString * file in files)
2788        {
2789            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2790            {
2791                tr_ctor * ctor = tr_ctorNew(fLib);
2792                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2793                switch (tr_torrentParse(fLib, ctor, NULL))
2794                {
2795                    case TR_OK:
2796                        [filesToOpen addObject: file];
2797                        torrent = YES;
2798                        break;
2799                       
2800                    case TR_EDUPLICATE:
2801                        torrent = YES;
2802                }
2803                tr_ctorFree(ctor);
2804            }
2805        }
2806       
2807        if ([filesToOpen count] > 0)
2808            [self application: NSApp openFiles: filesToOpen];
2809        else
2810        {
2811            if (!torrent && [files count] == 1)
2812                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2813            else
2814                accept = NO;
2815        }
2816        [filesToOpen release];
2817       
2818        return accept;
2819    }
2820    else if ([[pasteboard types] containsObject: NSURLPboardType])
2821    {
2822        NSURL * url;
2823        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2824        {
2825            [self openURL: url];
2826            return YES;
2827        }
2828    }
2829    else;
2830   
2831    return NO;
2832}
2833
2834- (void) toggleSmallView: (id) sender
2835{
2836    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2837    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2838   
2839    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2840   
2841    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2842   
2843    //window min height
2844    NSSize contentMinSize = [fWindow contentMinSize],
2845            contentSize = [[fWindow contentView] frame].size;
2846    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2847                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2848    [fWindow setContentMinSize: contentMinSize];
2849   
2850    //resize for larger min height if not set to auto size
2851    if (![fDefaults boolForKey: @"AutoSize"])
2852    {
2853        if (!makeSmall && contentSize.height < contentMinSize.height)
2854        {
2855            NSRect frame = [fWindow frame];
2856            CGFloat heightChange = contentMinSize.height - contentSize.height;
2857            frame.size.height += heightChange;
2858            frame.origin.y -= heightChange;
2859           
2860            [fWindow setFrame: frame display: YES];
2861        }
2862    }
2863    else
2864        [self setWindowSizeToFit];
2865}
2866
2867- (void) togglePiecesBar: (id) sender
2868{
2869    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2870    [fTableView togglePiecesBar];
2871}
2872
2873- (void) toggleAvailabilityBar: (id) sender
2874{
2875    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2876    [fTableView display];
2877}
2878
2879- (void) toggleStatusString: (id) sender
2880{
2881    if ([fDefaults boolForKey: @"SmallView"])
2882        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2883    else
2884        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2885   
2886    [fTableView reloadData];
2887}
2888
2889- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2890{
2891    NSScrollView * scrollView = [fTableView enclosingScrollView];
2892   
2893    //convert pixels to points
2894    NSRect windowFrame = [fWindow frame];
2895    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2896    windowSize.height += height;
2897   
2898    if (check)
2899    {
2900        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2901       
2902        if (windowSize.height < minSize.height)
2903            windowSize.height = minSize.height;
2904        else
2905        {
2906            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2907            if ([fStatusBar isHidden])
2908                maxSize.height -= [fStatusBar frame].size.height;
2909            if ([fFilterBar isHidden])
2910                maxSize.height -= [fFilterBar frame].size.height;
2911            if (windowSize.height > maxSize.height)
2912                windowSize.height = maxSize.height;
2913        }
2914    }
2915
2916    //convert points to pixels
2917    windowSize = [scrollView convertSize: windowSize toView: nil];
2918
2919    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2920    windowFrame.size.height = windowSize.height;
2921    return windowFrame;
2922}
2923
2924- (void) toggleStatusBar: (id) sender
2925{
2926    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2927    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2928}
2929
2930//doesn't save shown state
2931- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2932{
2933    if (show != [fStatusBar isHidden])
2934        return;
2935
2936    if (show)
2937        [fStatusBar setHidden: NO];
2938
2939    NSRect frame;
2940    CGFloat heightChange = [fStatusBar frame].size.height;
2941    if (!show)
2942        heightChange *= -1;
2943   
2944    //allow bar to show even if not enough room
2945    if (show && ![fDefaults boolForKey: @"AutoSize"])
2946    {
2947        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2948        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2949        if (change < 0.0)
2950        {
2951            frame = [fWindow frame];
2952            frame.size.height += change;
2953            frame.origin.y -= change;
2954            [fWindow setFrame: frame display: NO animate: NO];
2955        }
2956    }
2957
2958    [self updateUI];
2959   
2960    NSScrollView * scrollView = [fTableView enclosingScrollView];
2961   
2962    //set views to not autoresize
2963    NSUInteger statsMask = [fStatusBar autoresizingMask];
2964    NSUInteger filterMask = [fFilterBar autoresizingMask];
2965    NSUInteger scrollMask = [scrollView autoresizingMask];
2966    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2967    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2968    [scrollView setAutoresizingMask: NSViewNotSizable];
2969   
2970    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2971    [fWindow setFrame: frame display: YES animate: animate];
2972   
2973    //re-enable autoresize
2974    [fStatusBar setAutoresizingMask: statsMask];
2975    [fFilterBar setAutoresizingMask: filterMask];
2976    [scrollView setAutoresizingMask: scrollMask];
2977   
2978    //change min size
2979    NSSize minSize = [fWindow contentMinSize];
2980    minSize.height += heightChange;
2981    [fWindow setContentMinSize: minSize];
2982   
2983    if (!show)
2984        [fStatusBar setHidden: YES];
2985}
2986
2987- (void) toggleFilterBar: (id) sender
2988{
2989    //disable filtering when hiding
2990    if (![fFilterBar isHidden])
2991    {
2992        [fSearchFilterField setStringValue: @""];
2993        [self setFilter: fNoFilterButton];
2994        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
2995    }
2996
2997    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2998    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2999}
3000
3001//doesn't save shown state
3002- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3003{
3004    if (show != [fFilterBar isHidden])
3005        return;
3006
3007    if (show)
3008        [fFilterBar setHidden: NO];
3009
3010    NSRect frame;
3011    CGFloat heightChange = [fFilterBar frame].size.height;
3012    if (!show)
3013        heightChange *= -1;
3014   
3015    //allow bar to show even if not enough room
3016    if (show && ![fDefaults boolForKey: @"AutoSize"])
3017    {
3018        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3019        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3020        if (change < 0.0)
3021        {
3022            frame = [fWindow frame];
3023            frame.size.height += change;
3024            frame.origin.y -= change;
3025            [fWindow setFrame: frame display: NO animate: NO];
3026        }
3027    }
3028   
3029    NSScrollView * scrollView = [fTableView enclosingScrollView];
3030
3031    //set views to not autoresize
3032    NSUInteger filterMask = [fFilterBar autoresizingMask];
3033    NSUInteger scrollMask = [scrollView autoresizingMask];
3034    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3035    [scrollView setAutoresizingMask: NSViewNotSizable];
3036   
3037    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3038    [fWindow setFrame: frame display: YES animate: animate];
3039   
3040    //re-enable autoresize
3041    [fFilterBar setAutoresizingMask: filterMask];
3042    [scrollView setAutoresizingMask: scrollMask];
3043   
3044    //change min size
3045    NSSize minSize = [fWindow contentMinSize];
3046    minSize.height += heightChange;
3047    [fWindow setContentMinSize: minSize];
3048   
3049    if (!show)
3050    {
3051        [fFilterBar setHidden: YES];
3052        [fWindow makeFirstResponder: fTableView];
3053    }
3054}
3055
3056- (void) focusFilterField
3057{
3058    [fWindow makeFirstResponder: fSearchFilterField];
3059    if ([fFilterBar isHidden])
3060        [self toggleFilterBar: self];
3061}
3062
3063- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3064{
3065    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3066   
3067    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3068    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3069    [button setStringValue: @""];
3070   
3071    [item setView: button];
3072    [button release];
3073   
3074    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3075    [item setMinSize: buttonSize];
3076    [item setMaxSize: buttonSize];
3077   
3078    return [item autorelease];
3079}
3080
3081- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3082{
3083    if ([ident isEqualToString: TOOLBAR_CREATE])
3084    {
3085        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3086       
3087        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3088        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3089        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3090        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3091        [item setTarget: self];
3092        [item setAction: @selector(createFile:)];
3093        [item setAutovalidates: NO];
3094       
3095        return item;
3096    }
3097    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3098    {
3099        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3100       
3101        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3102        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3103        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3104        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3105        [item setTarget: self];
3106        [item setAction: @selector(openShowSheet:)];
3107        [item setAutovalidates: NO];
3108       
3109        return item;
3110    }
3111    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3112    {
3113        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3114       
3115        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3116        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3117        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3118        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3119        [item setTarget: self];
3120        [item setAction: @selector(openURLShowSheet:)];
3121        [item setAutovalidates: NO];
3122       
3123        return item;
3124    }
3125    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3126    {
3127        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3128       
3129        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3130        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3131        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3132        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3133        [item setTarget: self];
3134        [item setAction: @selector(removeNoDelete:)];
3135       
3136        return item;
3137    }
3138    else if ([ident isEqualToString: TOOLBAR_INFO])
3139    {
3140        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3141        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3142       
3143        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3144        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3145        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3146        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3147        [item setTarget: self];
3148        [item setAction: @selector(showInfo:)];
3149       
3150        return item;
3151    }
3152    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3153    {
3154        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3155       
3156        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3157        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3158        [groupItem setView: segmentedControl];
3159        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3160       
3161        [segmentedControl setSegmentCount: 2];
3162        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3163       
3164        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3165        [groupItem setMinSize: groupSize];
3166        [groupItem setMaxSize: groupSize];
3167       
3168        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3169        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3170        [groupItem setTarget: self];
3171        [groupItem setAction: @selector(allToolbarClicked:)];
3172       
3173        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3174       
3175        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3176        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3177        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3178                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3179       
3180        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3181        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3182        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3183                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3184       
3185        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3186                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3187       
3188        [segmentedControl release];
3189        return [groupItem autorelease];
3190    }
3191    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3192    {
3193        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3194       
3195        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3196        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3197        [groupItem setView: segmentedControl];
3198        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3199       
3200        [segmentedControl setSegmentCount: 2];
3201        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3202       
3203        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3204        [groupItem setMinSize: groupSize];
3205        [groupItem setMaxSize: groupSize];
3206       
3207        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3208        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3209        [groupItem setTarget: self];
3210        [groupItem setAction: @selector(selectedToolbarClicked:)];
3211       
3212        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3213       
3214        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3215        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3216        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3217                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3218       
3219        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3220        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3221        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3222                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3223       
3224        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3225                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3226       
3227        [segmentedControl release];
3228        return [groupItem autorelease];
3229    }
3230    else if ([ident isEqualToString: TOOLBAR_FILTER])
3231    {
3232        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3233        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3234       
3235        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3236        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3237        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3238        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3239        [item setTarget: self];
3240        [item setAction: @selector(toggleFilterBar:)];
3241       
3242        return item;
3243    }
3244    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3245    {
3246        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3247       
3248        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3249        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3250        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3251        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3252        [item setTarget: self];
3253        [item setAction: @selector(toggleQuickLook:)];
3254       
3255        return item;
3256    }
3257    else
3258        return nil;
3259}
3260
3261- (void) allToolbarClicked: (id) sender
3262{
3263    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3264                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3265    switch (tagValue)
3266    {
3267        case TOOLBAR_PAUSE_TAG:
3268            [self stopAllTorrents: sender];
3269            break;
3270        case TOOLBAR_RESUME_TAG:
3271            [self resumeAllTorrents: sender];
3272            break;
3273    }
3274}
3275
3276- (void) selectedToolbarClicked: (id) sender
3277{
3278    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3279                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3280    switch (tagValue)
3281    {
3282        case TOOLBAR_PAUSE_TAG:
3283            [self stopSelectedTorrents: sender];
3284            break;
3285        case TOOLBAR_RESUME_TAG:
3286            [self resumeSelectedTorrents: sender];
3287            break;
3288    }
3289}
3290
3291- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3292{
3293    return [NSArray arrayWithObjects:
3294            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3295            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3296            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3297            NSToolbarSeparatorItemIdentifier,
3298            NSToolbarSpaceItemIdentifier,
3299            NSToolbarFlexibleSpaceItemIdentifier,
3300            NSToolbarCustomizeToolbarItemIdentifier, nil];
3301}
3302
3303- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3304{
3305    return [NSArray arrayWithObjects:
3306            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSeparatorItemIdentifier,
3307            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3308            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3309}
3310
3311- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3312{
3313    NSString * ident = [toolbarItem itemIdentifier];
3314   
3315    //enable remove item
3316    if ([ident isEqualToString: TOOLBAR_REMOVE])
3317        return [fTableView numberOfSelectedRows] > 0;
3318
3319    //enable pause all item
3320    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3321    {
3322        for (Torrent * torrent in fTorrents)
3323            if ([torrent isActive] || [torrent waitingToStart])
3324                return YES;
3325        return NO;
3326    }
3327
3328    //enable resume all item
3329    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3330    {
3331        for (Torrent * torrent in fTorrents)
3332            if (![torrent isActive] && ![torrent waitingToStart])
3333                return YES;
3334        return NO;
3335    }
3336
3337    //enable pause item
3338    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3339    {
3340        for (Torrent * torrent in [fTableView selectedTorrents])
3341            if ([torrent isActive] || [torrent waitingToStart])
3342                return YES;
3343        return NO;
3344    }
3345   
3346    //enable resume item
3347    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3348    {
3349        for (Torrent * torrent in [fTableView selectedTorrents])
3350            if (![torrent isActive] && ![torrent waitingToStart])
3351                return YES;
3352        return NO;
3353    }
3354   
3355    //set info image
3356    if ([ident isEqualToString: TOOLBAR_INFO])
3357    {
3358        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3359        return YES;
3360    }
3361   
3362    //set filter image
3363    if ([ident isEqualToString: TOOLBAR_FILTER])
3364    {
3365        [(NSButton *)[toolbarItem view] setState: ![fFilterBar isHidden]];
3366        return YES;
3367    }
3368   
3369    //enable quicklook item
3370    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3371        return [[QuickLookController quickLook] canQuickLook];
3372
3373    return YES;
3374}
3375
3376- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3377{
3378    SEL action = [menuItem action];
3379   
3380    if (action == @selector(toggleSpeedLimit:))
3381    {
3382        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3383        return YES;
3384    }
3385   
3386    //only enable some items if it is in a context menu or the window is useable
3387    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3388
3389    //enable open items
3390    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3391        return [fWindow attachedSheet] == nil;
3392   
3393    //enable sort options
3394    if (action == @selector(setSort:))
3395    {
3396        NSString * sortType;
3397        switch ([menuItem tag])
3398        {
3399            case SORT_ORDER_TAG:
3400                sortType = SORT_ORDER;
3401                break;
3402            case SORT_DATE_TAG:
3403                sortType = SORT_DATE;
3404                break;
3405            case SORT_NAME_TAG:
3406                sortType = SORT_NAME;
3407                break;
3408            case SORT_PROGRESS_TAG:
3409                sortType = SORT_PROGRESS;
3410                break;
3411            case SORT_STATE_TAG:
3412                sortType = SORT_STATE;
3413                break;
3414            case SORT_TRACKER_TAG:
3415                sortType = SORT_TRACKER;
3416                break;
3417            case SORT_ACTIVITY_TAG:
3418                sortType = SORT_ACTIVITY;
3419        }
3420       
3421        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3422        return [fWindow isVisible];
3423    }
3424   
3425    //enable sort options
3426    if (action == @selector(setStatusLabel:))
3427    {
3428        NSString * statusLabel;
3429        switch ([menuItem tag])
3430        {
3431            case STATUS_RATIO_TOTAL_TAG:
3432                statusLabel = STATUS_RATIO_TOTAL;
3433                break;
3434            case STATUS_RATIO_SESSION_TAG:
3435                statusLabel = STATUS_RATIO_SESSION;
3436                break;
3437            case STATUS_TRANSFER_TOTAL_TAG:
3438                statusLabel = STATUS_TRANSFER_TOTAL;
3439                break;
3440            case STATUS_TRANSFER_SESSION_TAG:
3441                statusLabel = STATUS_TRANSFER_SESSION;
3442        }
3443       
3444        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3445        return YES;
3446    }
3447   
3448    if (action == @selector(setGroup:))
3449    {
3450        BOOL checked = NO;
3451       
3452        NSInteger index = [menuItem tag];
3453        for (Torrent * torrent in [fTableView selectedTorrents])
3454            if (index == [torrent groupValue])
3455            {
3456                checked = YES;
3457                break;
3458            }
3459       
3460        [menuItem setState: checked ? NSOnState : NSOffState];
3461        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3462    }
3463   
3464    if (action == @selector(setGroupFilter:))
3465    {
3466        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3467        return YES;
3468    }
3469   
3470    if (action == @selector(toggleSmallView:))
3471    {
3472        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3473        return [fWindow isVisible];
3474    }
3475   
3476    if (action == @selector(togglePiecesBar:))
3477    {
3478        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3479        return [fWindow isVisible];
3480    }
3481   
3482    if (action == @selector(toggleStatusString:))
3483    {
3484        if ([fDefaults boolForKey: @"SmallView"])
3485        {
3486            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3487            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3488        }
3489        else
3490        {
3491            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3492            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3493        }
3494       
3495        return [fWindow isVisible];
3496    }
3497   
3498    if (action == @selector(toggleAvailabilityBar:))
3499    {
3500        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3501        return [fWindow isVisible];
3502    }
3503   
3504    if (action == @selector(setLimitGlobalEnabled:))
3505    {
3506        BOOL upload = [menuItem menu] == fUploadMenu;
3507        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3508        if (limit)
3509            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3510                                    "Action menu -> upload/download limit"),
3511                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3512       
3513        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3514        return YES;
3515    }
3516   
3517    if (action == @selector(setRatioGlobalEnabled:))
3518    {
3519        BOOL check = menuItem == fCheckRatioItem;
3520        if (check)
3521            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3522                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3523       
3524        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3525        return YES;
3526    }
3527
3528    //enable show info
3529    if (action == @selector(showInfo:))
3530    {
3531        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3532                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3533        [menuItem setTitle: title];
3534
3535        return YES;
3536    }
3537   
3538    //enable prev/next inspector tab
3539    if (action == @selector(setInfoTab:))
3540        return [[fInfoController window] isVisible];
3541   
3542    //enable toggle status bar
3543    if (action == @selector(toggleStatusBar:))
3544    {
3545        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3546                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3547        [menuItem setTitle: title];
3548
3549        return [fWindow isVisible];
3550    }
3551   
3552    //enable toggle filter bar
3553    if (action == @selector(toggleFilterBar:))
3554    {
3555        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3556                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3557        [menuItem setTitle: title];
3558
3559        return [fWindow isVisible];
3560    }
3561   
3562    //enable prev/next filter button
3563    if (action == @selector(switchFilter:))
3564        return [fWindow isVisible] && ![fFilterBar isHidden];
3565   
3566    //enable quicklook item
3567    if (action == @selector(toggleQuickLook:))
3568        return [[QuickLookController quickLook] canQuickLook];
3569   
3570    //enable reveal in finder
3571    if (action == @selector(revealFile:))
3572        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3573
3574    //enable remove items
3575    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3576        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3577    {
3578        BOOL warning = NO,
3579            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3580            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3581       
3582        for (Torrent * torrent in [fTableView selectedTorrents])
3583        {
3584            if (!warning && [torrent isActive])
3585            {
3586                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3587                if (warning && canDelete)
3588                    break;
3589            }
3590            if (!canDelete && [torrent publicTorrent])
3591            {
3592                canDelete = YES;
3593                if (warning)
3594                    break;
3595            }
3596        }
3597   
3598        //append or remove ellipsis when needed
3599        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3600        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3601        {
3602            if (![title hasSuffix: ellipsis])
3603                [menuItem setTitle: [title stringByAppendingEllipsis]];
3604        }
3605        else
3606        {
3607            if ([title hasSuffix: ellipsis])
3608                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3609        }
3610       
3611        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3612    }
3613
3614    //enable pause all item
3615    if (action == @selector(stopAllTorrents:))
3616    {
3617        for (Torrent * torrent in fTorrents)
3618            if ([torrent isActive] || [torrent waitingToStart])
3619                return YES;
3620        return NO;
3621    }
3622   
3623    //enable resume all item
3624    if (action == @selector(resumeAllTorrents:))
3625    {
3626        for (Torrent * torrent in fTorrents)
3627            if (![torrent isActive] && ![torrent waitingToStart])
3628                return YES;
3629        return NO;
3630    }
3631   
3632    //enable resume all waiting item
3633    if (action == @selector(resumeWaitingTorrents:))
3634    {
3635        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3636            return NO;
3637   
3638        for (Torrent * torrent in fTorrents)
3639            if (![torrent isActive] && [torrent waitingToStart])
3640                return YES;
3641        return NO;
3642    }
3643   
3644    //enable resume selected waiting item
3645    if (action == @selector(resumeSelectedTorrentsNoWait:))
3646    {
3647        if (!canUseTable)
3648            return NO;
3649       
3650        for (Torrent * torrent in [fTableView selectedTorrents])
3651            if (![torrent isActive])
3652                return YES;
3653        return NO;
3654    }
3655
3656    //enable pause item
3657    if (action == @selector(stopSelectedTorrents:))
3658    {
3659        if (!canUseTable)
3660            return NO;
3661   
3662        for (Torrent * torrent in [fTableView selectedTorrents])
3663            if ([torrent isActive] || [torrent waitingToStart])
3664                return YES;
3665        return NO;
3666    }
3667   
3668    //enable resume item
3669    if (action == @selector(resumeSelectedTorrents:))
3670    {
3671        if (!canUseTable)
3672            return NO;
3673   
3674        for (Torrent * torrent in [fTableView selectedTorrents])
3675            if (![torrent isActive] && ![torrent waitingToStart])
3676                return YES;
3677        return NO;
3678    }
3679   
3680    //enable manual announce item
3681    if (action == @selector(announceSelectedTorrents:))
3682    {
3683        if (!canUseTable)
3684            return NO;
3685       
3686        for (Torrent * torrent in [fTableView selectedTorrents])
3687            if ([torrent canManualAnnounce])
3688                return YES;
3689        return NO;
3690    }
3691   
3692    //enable reset cache item
3693    if (action == @selector(verifySelectedTorrents:))
3694        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3695   
3696    //enable move torrent file item
3697    if (action == @selector(moveDataFilesSelected:))
3698        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3699   
3700    //enable copy torrent file item
3701    if (action == @selector(copyTorrentFiles:))
3702        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3703   
3704    //enable reverse sort item
3705    if (action == @selector(setSortReverse:))
3706    {
3707        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3708        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3709    }
3710   
3711    //enable group sort item
3712    if (action == @selector(setSortByGroup:))
3713    {
3714        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3715        return YES;
3716    }
3717   
3718    //check proper filter search item
3719    if (action == @selector(setFilterSearchType:))
3720    {
3721        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3722       
3723        BOOL state;
3724        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3725            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3726        else
3727            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3728       
3729        [menuItem setState: state ? NSOnState : NSOffState];
3730        return YES;
3731    }
3732   
3733    return YES;
3734}
3735
3736- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3737{
3738    switch (messageType)
3739    {
3740        case kIOMessageSystemWillSleep:
3741            //if there are any running transfers, wait 15 seconds for them to stop
3742            for (Torrent * torrent in fTorrents)
3743                if ([torrent isActive])
3744                {
3745                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3746                    [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3747                    sleep(15);
3748                    break;
3749                }
3750
3751            IOAllowPowerChange(fRootPort, (long) messageArgument);
3752            break;
3753
3754        case kIOMessageCanSystemSleep:
3755            if ([fDefaults boolForKey: @"SleepPrevent"])
3756            {
3757                //prevent idle sleep unless no torrents are active
3758                for (Torrent * torrent in fTorrents)
3759                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3760                    {
3761                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3762                        return;
3763                    }
3764            }
3765           
3766            IOAllowPowerChange(fRootPort, (long) messageArgument);
3767            break;
3768
3769        case kIOMessageSystemHasPoweredOn:
3770            //resume sleeping transfers after we wake up
3771            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3772            [self autoSpeedLimitChange: nil];
3773            break;
3774    }
3775}
3776
3777- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3778{
3779    NSInteger seeding = 0, downloading = 0;
3780    for (Torrent * torrent in fTorrents)
3781    {
3782        if ([torrent isSeeding])
3783            seeding++;
3784        else if ([torrent isActive])
3785            downloading++;
3786        else;
3787    }
3788   
3789    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3790            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3791   
3792    BOOL hasSeparator = seedingItem || downloadingItem;
3793   
3794    if (seeding > 0)
3795    {
3796        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3797        if (!seedingItem)
3798        {
3799            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3800            [seedingItem setTag: DOCK_SEEDING_TAG];
3801            [fDockMenu insertItem: seedingItem atIndex: 0];
3802        }
3803        else
3804            [seedingItem setTitle: title];
3805    }
3806    else
3807    {
3808        if (seedingItem)
3809            [fDockMenu removeItem: seedingItem];
3810    }
3811   
3812    if (downloading > 0)
3813    {
3814        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3815        if (!downloadingItem)
3816        {
3817            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3818            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3819            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3820        }
3821        else
3822            [downloadingItem setTitle: title];
3823    }
3824    else
3825    {
3826        if (downloadingItem)
3827            [fDockMenu removeItem: downloadingItem];
3828    }
3829   
3830    if (seeding > 0 || downloading > 0)
3831    {
3832        if (!hasSeparator)
3833            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3834    }
3835    else
3836    {
3837        if (hasSeparator)
3838            [fDockMenu removeItemAtIndex: 0];
3839    }
3840   
3841    return fDockMenu;
3842}
3843
3844- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3845{
3846    //if auto size is enabled, the current frame shouldn't need to change
3847    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3848   
3849    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3850    return frame;
3851}
3852
3853- (void) setWindowSizeToFit
3854{
3855    if ([fDefaults boolForKey: @"AutoSize"])
3856    {
3857        NSScrollView * scrollView = [fTableView enclosingScrollView];
3858       
3859        [scrollView setHasVerticalScroller: NO];
3860        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3861        [scrollView setHasVerticalScroller: YES];
3862       
3863        //hack to ensure scrollbars don't disappear after resizing
3864        [scrollView setAutohidesScrollers: NO];
3865        [scrollView setAutohidesScrollers: YES];
3866    }
3867}
3868
3869- (NSRect) sizedWindowFrame
3870{
3871    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3872                    ? [fDisplayedTorrents count] : 0;
3873   
3874    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3875                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3876                        - [[fTableView enclosingScrollView] frame].size.height;
3877   
3878    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3879}
3880
3881- (void) updateForExpandCollape
3882{
3883    [self setWindowSizeToFit];
3884    [self setBottomCountText: YES];
3885}
3886
3887- (void) showMainWindow: (id) sender
3888{
3889    [fWindow makeKeyAndOrderFront: nil];
3890}
3891
3892- (void) windowDidBecomeMain: (NSNotification *) notification
3893{
3894    [fBadger clearCompleted];
3895    [self updateUI];
3896}
3897
3898- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3899{
3900    //only resize horizontally if autosize is enabled
3901    if ([fDefaults boolForKey: @"AutoSize"])
3902        proposedFrameSize.height = [fWindow frame].size.height;
3903    return proposedFrameSize;
3904}
3905
3906- (void) windowDidResize: (NSNotification *) notification
3907{
3908    if (![fStatusBar isHidden])
3909        [self resizeStatusButton];
3910   
3911    if ([fFilterBar isHidden])
3912        return;
3913   
3914    //replace all buttons
3915    [fNoFilterButton sizeToFit];
3916    [fActiveFilterButton sizeToFit];
3917    [fDownloadFilterButton sizeToFit];
3918    [fSeedFilterButton sizeToFit];
3919    [fPauseFilterButton sizeToFit];
3920   
3921    NSRect allRect = [fNoFilterButton frame];
3922    NSRect activeRect = [fActiveFilterButton frame];
3923    NSRect downloadRect = [fDownloadFilterButton frame];
3924    NSRect seedRect = [fSeedFilterButton frame];
3925    NSRect pauseRect = [fPauseFilterButton frame];
3926   
3927    //size search filter to not overlap buttons
3928    NSRect searchFrame = [fSearchFilterField frame];
3929    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
3930    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
3931   
3932    //make sure it is not too long
3933    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
3934    {
3935        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
3936        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
3937    }
3938    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
3939    {
3940        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
3941        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
3942       
3943        //calculate width the buttons can take up
3944        const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x;
3945        const CGFloat currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect)
3946                                        + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons
3947        const CGFloat ratio = allowedWidth / currentWidth;
3948       
3949        //decrease button widths proportionally
3950        allRect.size.width  = NSWidth(allRect) * ratio;
3951        activeRect.size.width = NSWidth(activeRect) * ratio;
3952        downloadRect.size.width = NSWidth(downloadRect) * ratio;
3953        seedRect.size.width = NSWidth(seedRect) * ratio;
3954        pauseRect.size.width = NSWidth(pauseRect) * ratio;
3955    }
3956    else;
3957   
3958    activeRect.origin.x = NSMaxX(allRect) + 1.0;
3959    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
3960    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
3961    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
3962   
3963    [fNoFilterButton setFrame: allRect];
3964    [fActiveFilterButton setFrame: activeRect];
3965    [fDownloadFilterButton setFrame: downloadRect];
3966    [fSeedFilterButton setFrame: seedRect];
3967    [fPauseFilterButton setFrame: pauseRect];
3968   
3969    [fSearchFilterField setFrame: searchFrame];
3970}
3971
3972- (void) applicationWillUnhide: (NSNotification *) notification
3973{
3974    [self updateUI];
3975}
3976
3977- (NSArray *) quickLookURLs
3978{
3979    NSArray * selectedTorrents = [fTableView selectedTorrents];
3980    NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3981   
3982    for (Torrent * torrent in selectedTorrents)
3983        if ([self canQuickLookTorrent: torrent])
3984            [urlArray addObject: [NSURL fileURLWithPath: [torrent dataLocation]]];
3985   
3986    return urlArray;
3987}
3988
3989- (BOOL) canQuickLook
3990{
3991    for (Torrent * torrent in [fTableView selectedTorrents])
3992        if ([self canQuickLookTorrent: torrent])
3993            return YES;
3994   
3995    return NO;
3996}
3997
3998- (BOOL) canQuickLookTorrent: (Torrent *) torrent
3999{
4000    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent dataLocation]])
4001        return NO;
4002   
4003    return [torrent isFolder] || [torrent isComplete];
4004}
4005
4006- (NSRect) quickLookFrameWithURL: (NSURL *) url
4007{
4008    if ([fWindow isVisible])
4009    {
4010        NSString * fullPath = [url path];
4011        NSRange visibleRows = [fTableView rowsInRect: [fTableView bounds]];
4012       
4013        for (NSInteger row = 0; row < NSMaxRange(visibleRows); row++)
4014        {
4015            id item = [fTableView itemAtRow: row];
4016            if ([item isKindOfClass: [Torrent class]] && [[(Torrent *)item dataLocation] isEqualToString: fullPath])
4017            {
4018                NSRect frame = [fTableView iconRectForRow: row];
4019                frame.origin = [fTableView convertPoint: frame.origin toView: nil];
4020                frame.origin = [fWindow convertBaseToScreen: frame.origin];
4021                frame.origin.y -= frame.size.height;
4022                return frame;
4023            }
4024        }
4025    }
4026   
4027    return NSZeroRect;
4028}
4029
4030- (void) toggleQuickLook: (id) sender
4031{
4032    [[QuickLookController quickLook] toggleQuickLook];
4033}
4034
4035- (void) linkHomepage: (id) sender
4036{
4037    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4038}
4039
4040- (void) linkForums: (id) sender
4041{
4042    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4043}
4044
4045- (void) linkTrac: (id) sender
4046{
4047    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4048}
4049
4050- (void) linkDonate: (id) sender
4051{
4052    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4053}
4054
4055- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4056{
4057    fUpdateInProgress = YES;
4058}
4059
4060- (NSDictionary *) registrationDictionaryForGrowl
4061{
4062    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4063                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4064    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4065                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4066}
4067
4068- (void) growlNotificationWasClicked: (id) clickContext
4069{
4070    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4071        return;
4072   
4073    NSString * type = [clickContext objectForKey: @"Type"], * location;
4074    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4075            && (location = [clickContext objectForKey: @"Location"]))
4076        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4077}
4078
4079- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4080{
4081    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4082   
4083    //get the torrent
4084    Torrent * torrent = nil;
4085    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4086    {
4087        for (torrent in fTorrents)
4088            if (torrentStruct == [torrent torrentStruct])
4089            {
4090                [torrent retain];
4091                break;
4092            }
4093       
4094        if (!torrent)
4095        {
4096            [pool release];
4097           
4098            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4099            return;
4100        }
4101    }
4102   
4103    switch (type)
4104    {
4105        case TR_RPC_TORRENT_ADDED:
4106            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4107                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4108            break;
4109       
4110        case TR_RPC_TORRENT_STARTED:
4111        case TR_RPC_TORRENT_STOPPED:
4112            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4113            break;
4114       
4115        case TR_RPC_TORRENT_REMOVING:
4116            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4117            break;
4118       
4119        case TR_RPC_TORRENT_CHANGED:
4120            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4121            break;
4122       
4123        case TR_RPC_SESSION_CHANGED:
4124            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4125            break;
4126       
4127        default:
4128            NSLog(@"Unknown RPC command received!");
4129            [torrent release];
4130    }
4131   
4132    [pool release];
4133}
4134
4135- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4136{
4137    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4138    [torrentStructPtr release];
4139   
4140    NSString * location = nil;
4141    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4142        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4143   
4144    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4145   
4146    [torrent update];
4147    [fTorrents addObject: torrent];
4148    [torrent release];
4149   
4150    [self updateTorrentsInQueue];
4151}
4152
4153- (void) rpcRemoveTorrent: (Torrent *) torrent
4154{
4155    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO deleteTorrent: NO];
4156    [torrent release];
4157}
4158
4159- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4160{
4161    [torrent update];
4162    [torrent release];
4163   
4164    [self updateUI];
4165    [self applyFilter: nil];
4166    [self updateTorrentHistory];
4167}
4168
4169- (void) rpcChangedTorrent: (Torrent *) torrent
4170{
4171    [torrent update];
4172   
4173    if ([[fTableView selectedTorrents] containsObject: torrent])
4174    {
4175        [fInfoController updateInfoStats]; //this will reload the file table
4176        [fInfoController updateOptions];
4177    }
4178   
4179    [torrent release];
4180}
4181
4182@end
Note: See TracBrowser for help on using the repository browser.