source: trunk/macosx/Controller.m @ 9096

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

last commit would break 10.5-compatibility if it weren't already broken

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