source: trunk/macosx/Controller.m @ 8386

Last change on this file since 8386 was 8386, checked in by livings124, 13 years ago

#2045 hold down option key on launch to start with all torrents paused

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