source: trunk/macosx/Controller.m @ 9192

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

fix using the filter bar to filter by tracker; add options to make the filter text searching less strict

  • Property svn:keywords set to Date Rev Author Id
File size: 153.5 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 9192 2009-09-27 16:37:57Z 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 TRANSFER_PLIST  @"/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: TRANSFER_PLIST]];
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: TRANSFER_PLIST] 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 applyFilter: nil]; //better than calling sortTorrents because it will even apply to queue order
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 allTrackersFlat])
2028                {
2029                    if ([tracker rangeOfString: searchString options:
2030                            (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch)].location != NSNotFound)
2031                    {
2032                        removeTextField = NO;
2033                        break;
2034                    }
2035                }
2036               
2037                if (removeTextField)
2038                    continue;
2039            }
2040            else
2041            {
2042                if ([[torrent name] rangeOfString: searchString options:
2043                        (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch)].location == NSNotFound)
2044                    continue;
2045            }
2046        }
2047       
2048        [allTorrents addObject: torrent];
2049    }
2050   
2051    //set button tooltips
2052    [fNoFilterButton setCount: [fTorrents count]];
2053    [fActiveFilterButton setCount: active];
2054    [fDownloadFilterButton setCount: downloading];
2055    [fSeedFilterButton setCount: seeding];
2056    [fPauseFilterButton setCount: paused];
2057   
2058    //clear display cache for not-shown torrents
2059    [previousTorrents removeObjectsInArray: allTorrents];
2060    for (Torrent * torrent in previousTorrents)
2061        [torrent setPreviousFinishedPieces: nil];
2062   
2063    //place torrents into groups
2064    const BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"];
2065    if (groupRows)
2066    {
2067        NSMutableArray * oldTorrentGroups = [NSMutableArray array];
2068        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2069            [oldTorrentGroups addObjectsFromArray: fDisplayedTorrents];
2070       
2071        [fDisplayedTorrents removeAllObjects];
2072       
2073        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2074        [allTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2075       
2076        NSMutableArray * groupTorrents;
2077        NSInteger lastGroupValue = -2, currentOldGroupIndex = 0;
2078        for (Torrent * torrent in allTorrents)
2079        {
2080            NSInteger groupValue = [torrent groupValue];
2081            if (groupValue != lastGroupValue)
2082            {
2083                lastGroupValue = groupValue;
2084               
2085                TorrentGroup * group = nil;
2086               
2087                //try to see if the group already exists
2088                for (; currentOldGroupIndex < [oldTorrentGroups count]; currentOldGroupIndex++)
2089                {
2090                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
2091                    const NSInteger currentGroupValue = [currentGroup groupIndex];
2092                    if (currentGroupValue == groupValue)
2093                    {
2094                        group = currentGroup;
2095                        [[currentGroup torrents] removeAllObjects];
2096                       
2097                        currentOldGroupIndex++;
2098                    }
2099                   
2100                    if (currentGroupValue >= groupValue)
2101                        break;
2102                }
2103               
2104                if (!group)
2105                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2106                [fDisplayedTorrents addObject: group];
2107               
2108                groupTorrents = [group torrents];
2109            }
2110           
2111            [groupTorrents addObject: torrent];
2112        }
2113    }
2114    else
2115        [fDisplayedTorrents setArray: allTorrents];
2116   
2117    //actually sort
2118    [self sortTorrentsIgnoreSelected];
2119   
2120    //reset expanded/collapsed rows
2121    if (groupRows)
2122    {
2123        for (TorrentGroup * group in fDisplayedTorrents)
2124        {
2125            if ([fTableView isGroupCollapsed: [group groupIndex]])
2126                [fTableView collapseItem: group];
2127            else
2128                [fTableView expandItem: group];
2129        }
2130    }
2131   
2132    [fTableView selectValues: selectedValues];
2133    [self resetInfo]; //if group is already selected, but the torrents in it change
2134   
2135    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2136   
2137    [self setWindowSizeToFit];
2138}
2139
2140//resets filter and sorts torrents
2141- (void) setFilter: (id) sender
2142{
2143    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2144   
2145    NSButton * prevFilterButton;
2146    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2147        prevFilterButton = fPauseFilterButton;
2148    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2149        prevFilterButton = fActiveFilterButton;
2150    else if ([oldFilterType isEqualToString: FILTER_SEED])
2151        prevFilterButton = fSeedFilterButton;
2152    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2153        prevFilterButton = fDownloadFilterButton;
2154    else
2155        prevFilterButton = fNoFilterButton;
2156   
2157    if (sender != prevFilterButton)
2158    {
2159        [prevFilterButton setState: NSOffState];
2160        [sender setState: NSOnState];
2161
2162        NSString * filterType;
2163        if (sender == fActiveFilterButton)
2164            filterType = FILTER_ACTIVE;
2165        else if (sender == fDownloadFilterButton)
2166            filterType = FILTER_DOWNLOAD;
2167        else if (sender == fPauseFilterButton)
2168            filterType = FILTER_PAUSE;
2169        else if (sender == fSeedFilterButton)
2170            filterType = FILTER_SEED;
2171        else
2172            filterType = FILTER_NONE;
2173
2174        [fDefaults setObject: filterType forKey: @"Filter"];
2175    }
2176    else
2177        [sender setState: NSOnState];
2178
2179    [self applyFilter: nil];
2180}
2181
2182- (void) setFilterSearchType: (id) sender
2183{
2184    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2185   
2186    NSInteger prevTag, currentTag = [sender tag];
2187    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2188        prevTag = FILTER_TYPE_TAG_TRACKER;
2189    else
2190        prevTag = FILTER_TYPE_TAG_NAME;
2191   
2192    if (currentTag != prevTag)
2193    {
2194        NSString * filterType;
2195        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2196            filterType = FILTER_TYPE_TRACKER;
2197        else
2198            filterType = FILTER_TYPE_NAME;
2199       
2200        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2201       
2202        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2203    }
2204   
2205    [self applyFilter: nil];
2206}
2207
2208- (void) switchFilter: (id) sender
2209{
2210    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2211   
2212    NSButton * button;
2213    if ([filterType isEqualToString: FILTER_NONE])
2214        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2215    else if ([filterType isEqualToString: FILTER_ACTIVE])
2216        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2217    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2218        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2219    else if ([filterType isEqualToString: FILTER_SEED])
2220        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2221    else if ([filterType isEqualToString: FILTER_PAUSE])
2222        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2223    else
2224        button = fNoFilterButton;
2225   
2226    [self setFilter: button];
2227}
2228
2229- (void) setStatusLabel: (id) sender
2230{
2231    NSString * statusLabel;
2232    switch ([sender tag])
2233    {
2234        case STATUS_RATIO_TOTAL_TAG:
2235            statusLabel = STATUS_RATIO_TOTAL;
2236            break;
2237        case STATUS_RATIO_SESSION_TAG:
2238            statusLabel = STATUS_RATIO_SESSION;
2239            break;
2240        case STATUS_TRANSFER_TOTAL_TAG:
2241            statusLabel = STATUS_TRANSFER_TOTAL;
2242            break;
2243        case STATUS_TRANSFER_SESSION_TAG:
2244            statusLabel = STATUS_TRANSFER_SESSION;
2245            break;
2246        default:
2247            return;
2248    }
2249   
2250    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2251    [self updateUI];
2252}
2253
2254- (void) menuNeedsUpdate: (NSMenu *) menu
2255{
2256    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu || menu == fGroupFilterMenu)
2257    {
2258        const BOOL filter = menu == fGroupFilterMenu;
2259       
2260        const NSInteger remaining = filter ? 3 : 0;
2261        for (NSInteger i = [menu numberOfItems]-1; i >= remaining; i--)
2262            [menu removeItemAtIndex: i];
2263       
2264        NSMenu * groupMenu;
2265        if (!filter)
2266            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2267        else
2268            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:) isSmall: YES];
2269       
2270        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2271        for (NSInteger i = 0; i < groupMenuCount; i++)
2272        {
2273            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2274            [groupMenu removeItemAtIndex: 0];
2275            [menu addItem: item];
2276            [item release];
2277        }
2278    }
2279    else if (menu == fUploadMenu || menu == fDownloadMenu)
2280    {
2281        if ([menu numberOfItems] > 3)
2282            return;
2283       
2284        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2285       
2286        NSMenuItem * item;
2287        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2288        {
2289            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2290                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2291                    keyEquivalent: @""];
2292            [item setTarget: self];
2293            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2294            [menu addItem: item];
2295            [item release];
2296        }
2297    }
2298    else if (menu == fRatioStopMenu)
2299    {
2300        if ([menu numberOfItems] > 3)
2301            return;
2302       
2303        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2304       
2305        NSMenuItem * item;
2306        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2307        {
2308            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2309                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2310            [item setTarget: self];
2311            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2312            [menu addItem: item];
2313            [item release];
2314        }
2315    }
2316    else;
2317}
2318
2319- (void) setGroup: (id) sender
2320{
2321    for (Torrent * torrent in [fTableView selectedTorrents])
2322    {
2323        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2324       
2325        [torrent setGroupValue: [sender tag]];
2326    }
2327   
2328    [self applyFilter: nil];
2329    [self updateUI];
2330    [self updateTorrentHistory];
2331}
2332
2333- (void) setGroupFilter: (id) sender
2334{
2335    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2336    [self updateGroupsFilterButton];
2337    [self applyFilter: nil];
2338}
2339
2340- (void) updateGroupsFilterButton
2341{
2342    NSInteger groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2343   
2344    NSImage * icon;
2345    NSString * toolTip;
2346    if (groupIndex == GROUP_FILTER_ALL_TAG)
2347    {
2348        icon = [NSImage imageNamed: @"PinTemplate.png"];
2349        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2350    }
2351    else
2352    {
2353        icon = [[GroupsController groups] imageForIndex: groupIndex];
2354        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2355                                                : NSLocalizedString(@"None", "Groups -> Button");
2356        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2357    }
2358   
2359    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2360    [fGroupsButton setToolTip: toolTip];
2361}
2362
2363- (void) updateGroupsFilters: (NSNotification *) notification
2364{
2365    [self updateGroupsFilterButton];
2366    [self applyFilter: nil];
2367}
2368
2369- (void) toggleSpeedLimit: (id) sender
2370{
2371    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2372    [self speedLimitChanged: sender];
2373}
2374
2375- (void) speedLimitChanged: (id) sender
2376{
2377    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2378    [self updateSpeedFieldsToolTips];
2379}
2380
2381//dict has been retained
2382- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2383{
2384    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2385
2386    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2387    [self updateSpeedFieldsToolTips];
2388   
2389    if (![[dict objectForKey: @"ByUser"] boolValue])
2390        [GrowlApplicationBridge notifyWithTitle: isLimited
2391                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2392                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2393            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2394            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2395   
2396    [dict release];
2397}
2398
2399- (void) setLimitGlobalEnabled: (id) sender
2400{
2401    BOOL upload = [sender menu] == fUploadMenu;
2402    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2403   
2404    [fPrefsController applySpeedSettings: nil];
2405}
2406
2407- (void) setQuickLimitGlobal: (id) sender
2408{
2409    BOOL upload = [sender menu] == fUploadMenu;
2410    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2411    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2412   
2413    [fPrefsController updateLimitFields];
2414    [fPrefsController applySpeedSettings: nil];
2415}
2416
2417- (void) setRatioGlobalEnabled: (id) sender
2418{
2419    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2420   
2421    [fPrefsController applyRatioSetting: nil];
2422}
2423
2424- (void) setQuickRatioGlobal: (id) sender
2425{
2426    [fDefaults setBool: YES forKey: @"RatioCheck"];
2427    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2428   
2429    [fPrefsController updateRatioStopField];
2430}
2431
2432- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2433{
2434    fSoundPlaying = NO;
2435}
2436
2437- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2438{
2439    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2440    {
2441        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2442            return;
2443       
2444        if (fAutoImportTimer)
2445        {
2446            if ([fAutoImportTimer isValid])
2447                [fAutoImportTimer invalidate];
2448            [fAutoImportTimer release];
2449            fAutoImportTimer = nil;
2450        }
2451       
2452        //check again in 10 seconds in case torrent file wasn't complete
2453        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2454            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2455       
2456        [self checkAutoImportDirectory];
2457    }
2458}
2459
2460- (void) changeAutoImport
2461{
2462    if (fAutoImportTimer)
2463    {
2464        if ([fAutoImportTimer isValid])
2465            [fAutoImportTimer invalidate];
2466        [fAutoImportTimer release];
2467        fAutoImportTimer = nil;
2468    }
2469   
2470    if (fAutoImportedNames)
2471    {
2472        [fAutoImportedNames release];
2473        fAutoImportedNames = nil;
2474    }
2475   
2476    [self checkAutoImportDirectory];
2477}
2478
2479- (void) checkAutoImportDirectory
2480{
2481    NSString * path;
2482    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2483        return;
2484   
2485    path = [path stringByExpandingTildeInPath];
2486   
2487    NSArray * importedNames;
2488    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2489        return;
2490   
2491    //only check files that have not been checked yet
2492    NSMutableArray * newNames = [importedNames mutableCopy];
2493   
2494    if (fAutoImportedNames)
2495        [newNames removeObjectsInArray: fAutoImportedNames];
2496    else
2497        fAutoImportedNames = [[NSMutableArray alloc] init];
2498    [fAutoImportedNames setArray: importedNames];
2499   
2500    for (NSString * file in newNames)
2501    {
2502        if ([file hasPrefix: @"."])
2503            continue;
2504       
2505        NSString * fullFile = [path stringByAppendingPathComponent: file];
2506       
2507        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2508                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2509            continue;
2510       
2511        tr_ctor * ctor = tr_ctorNew(fLib);
2512        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2513       
2514        switch (tr_torrentParse(ctor, NULL))
2515        {
2516            case TR_PARSE_OK:
2517                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2518               
2519                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2520                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2521                    clickContext: nil];
2522                break;
2523           
2524            case TR_PARSE_ERR:
2525                [fAutoImportedNames removeObject: file];
2526        }
2527       
2528        tr_ctorFree(ctor);
2529    }
2530   
2531    [newNames release];
2532}
2533
2534- (void) beginCreateFile: (NSNotification *) notification
2535{
2536    if (![fDefaults boolForKey: @"AutoImport"])
2537        return;
2538   
2539    NSString * location = [notification object],
2540            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2541   
2542    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2543                                    isEqualToString: [path stringByExpandingTildeInPath]])
2544        [fAutoImportedNames addObject: [location lastPathComponent]];
2545}
2546
2547- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2548{
2549    if (item)
2550        return [[item torrents] count];
2551    else
2552        return [fDisplayedTorrents count];
2553}
2554
2555- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2556{
2557    if (item)
2558        return [[item torrents] objectAtIndex: index];
2559    else
2560        return [fDisplayedTorrents objectAtIndex: index];
2561}
2562
2563- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2564{
2565    return ![item isKindOfClass: [Torrent class]];
2566}
2567
2568- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2569{
2570    if ([item isKindOfClass: [Torrent class]])
2571        return [item hashString];
2572    else
2573    {
2574        NSString * ident = [tableColumn identifier];
2575        if ([ident isEqualToString: @"Group"])
2576        {
2577            NSInteger group = [item groupIndex];
2578            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2579                                : NSLocalizedString(@"No Group", "Group table row");
2580        }
2581        else if ([ident isEqualToString: @"Color"])
2582        {
2583            NSInteger group = [item groupIndex];
2584            return [[GroupsController groups] imageForIndex: group];
2585        }
2586        else if ([ident isEqualToString: @"DL Image"])
2587            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2588        else if ([ident isEqualToString: @"UL Image"])
2589            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2590                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2591        else
2592        {
2593            TorrentGroup * group = (TorrentGroup *)item;
2594           
2595            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2596                return [NSString stringForRatio: [group ratio]];
2597            else
2598            {
2599                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2600                return [NSString stringForSpeed: rate];
2601            }
2602        }
2603    }
2604}
2605
2606- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2607{
2608    //only allow reordering of rows if sorting by order
2609    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2610    {
2611        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2612        for (id torrent in items)
2613        {
2614            if (![torrent isKindOfClass: [Torrent class]])
2615                return NO;
2616           
2617            [indexSet addIndex: [fTableView rowForItem: torrent]];
2618        }
2619       
2620        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2621        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2622        return YES;
2623    }
2624    return NO;
2625}
2626
2627- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2628    proposedChildIndex: (NSInteger) index
2629{
2630    NSPasteboard * pasteboard = [info draggingPasteboard];
2631    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2632    {
2633        if ([fDefaults boolForKey: @"SortByGroup"])
2634        {
2635            if (!item)
2636                return NSDragOperationNone;
2637           
2638            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2639            {
2640                if ([item isKindOfClass: [Torrent class]])
2641                {
2642                    TorrentGroup * group = [fTableView parentForItem: item];
2643                    index = [[group torrents] indexOfObject: item] + 1;
2644                    item = group;
2645                }
2646            }
2647            else
2648            {
2649                if ([item isKindOfClass: [Torrent class]])
2650                    item = [fTableView parentForItem: item];
2651                index = NSOutlineViewDropOnItemIndex;
2652            }
2653        }
2654        else
2655        {
2656            if (item)
2657            {
2658                index = [fTableView rowForItem: item] + 1;
2659                item = nil;
2660            }
2661        }
2662       
2663        [fTableView setDropItem: item dropChildIndex: index];
2664        return NSDragOperationGeneric;
2665    }
2666   
2667    return NSDragOperationNone;
2668}
2669
2670- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2671    childIndex: (NSInteger) newRow
2672{
2673    NSPasteboard * pasteboard = [info draggingPasteboard];
2674    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2675    {
2676        //remember selected rows
2677        NSArray * selectedValues = [fTableView selectedValues];
2678   
2679        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2680       
2681        //get the torrents to move
2682        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2683        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2684            [movingTorrents addObject: [fTableView itemAtRow: i]];
2685       
2686        //reset groups
2687        if (item)
2688        {
2689            //change groups
2690            NSInteger groupValue = [item groupIndex];
2691            for (Torrent * torrent in movingTorrents)
2692            {
2693                //have to reset objects here to avoid weird crash
2694                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2695                [[item torrents] addObject: torrent];
2696               
2697                [torrent setGroupValue: groupValue];
2698            }
2699            //part 2 of avoiding weird crash
2700            [fTableView reloadItem: nil reloadChildren: YES];
2701        }
2702       
2703        //reorder queue order
2704        if (newRow != NSOutlineViewDropOnItemIndex)
2705        {
2706            //find torrent to place under
2707            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2708            Torrent * topTorrent = nil;
2709            for (NSInteger i = newRow-1; i >= 0; i--)
2710            {
2711                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2712                if (![movingTorrents containsObject: tempTorrent])
2713                {
2714                    topTorrent = tempTorrent;
2715                    break;
2716                }
2717            }
2718           
2719            //remove objects to reinsert
2720            [fTorrents removeObjectsInArray: movingTorrents];
2721           
2722            //insert objects at new location
2723            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2724            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2725            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2726        }
2727       
2728        [self applyFilter: nil];
2729        [fTableView selectValues: selectedValues];
2730    }
2731   
2732    return YES;
2733}
2734
2735- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2736{
2737    [self resetInfo];
2738}
2739
2740- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2741{
2742    NSPasteboard * pasteboard = [info draggingPasteboard];
2743    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2744    {
2745        //check if any torrent files can be added
2746        BOOL torrent = NO;
2747        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2748        for (NSString * file in files)
2749        {
2750            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2751                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2752            {
2753                torrent = YES;
2754                tr_ctor * ctor = tr_ctorNew(fLib);
2755                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2756                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2757                {
2758                    if (!fOverlayWindow)
2759                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2760                    [fOverlayWindow setTorrents: files];
2761                   
2762                    return NSDragOperationCopy;
2763                }
2764                tr_ctorFree(ctor);
2765            }
2766        }
2767       
2768        //create a torrent file if a single file
2769        if (!torrent && [files count] == 1)
2770        {
2771            if (!fOverlayWindow)
2772                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2773            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2774           
2775            return NSDragOperationCopy;
2776        }
2777    }
2778    else if ([[pasteboard types] containsObject: NSURLPboardType])
2779    {
2780        if (!fOverlayWindow)
2781            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2782        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2783       
2784        return NSDragOperationCopy;
2785    }
2786    else;
2787   
2788    return NSDragOperationNone;
2789}
2790
2791- (void) draggingExited: (id <NSDraggingInfo>) info
2792{
2793    if (fOverlayWindow)
2794        [fOverlayWindow fadeOut];
2795}
2796
2797- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2798{
2799    if (fOverlayWindow)
2800        [fOverlayWindow fadeOut];
2801   
2802    NSPasteboard * pasteboard = [info draggingPasteboard];
2803    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2804    {
2805        BOOL torrent = NO, accept = YES;
2806       
2807        //create an array of files that can be opened
2808        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2809        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
2810        for (NSString * file in files)
2811        {
2812            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2813                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2814            {
2815                torrent = YES;
2816                tr_ctor * ctor = tr_ctorNew(fLib);
2817                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2818                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2819                    [filesToOpen addObject: file];
2820                tr_ctorFree(ctor);
2821            }
2822        }
2823       
2824        if ([filesToOpen count] > 0)
2825            [self application: NSApp openFiles: filesToOpen];
2826        else
2827        {
2828            if (!torrent && [files count] == 1)
2829                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2830            else
2831                accept = NO;
2832        }
2833       
2834        return accept;
2835    }
2836    else if ([[pasteboard types] containsObject: NSURLPboardType])
2837    {
2838        NSURL * url;
2839        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2840        {
2841            [self openURL: url];
2842            return YES;
2843        }
2844    }
2845    else;
2846   
2847    return NO;
2848}
2849
2850- (void) toggleSmallView: (id) sender
2851{
2852    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2853    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2854   
2855    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2856   
2857    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2858   
2859    //window min height
2860    NSSize contentMinSize = [fWindow contentMinSize],
2861            contentSize = [[fWindow contentView] frame].size;
2862    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2863                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2864    [fWindow setContentMinSize: contentMinSize];
2865   
2866    //resize for larger min height if not set to auto size
2867    if (![fDefaults boolForKey: @"AutoSize"])
2868    {
2869        if (!makeSmall && contentSize.height < contentMinSize.height)
2870        {
2871            NSRect frame = [fWindow frame];
2872            CGFloat heightChange = contentMinSize.height - contentSize.height;
2873            frame.size.height += heightChange;
2874            frame.origin.y -= heightChange;
2875           
2876            [fWindow setFrame: frame display: YES];
2877        }
2878    }
2879    else
2880        [self setWindowSizeToFit];
2881}
2882
2883- (void) togglePiecesBar: (id) sender
2884{
2885    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2886    [fTableView togglePiecesBar];
2887}
2888
2889- (void) toggleAvailabilityBar: (id) sender
2890{
2891    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2892    [fTableView display];
2893}
2894
2895- (void) toggleStatusString: (id) sender
2896{
2897    if ([fDefaults boolForKey: @"SmallView"])
2898        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2899    else
2900        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2901   
2902    [fTableView reloadData];
2903}
2904
2905- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2906{
2907    NSScrollView * scrollView = [fTableView enclosingScrollView];
2908   
2909    //convert pixels to points
2910    NSRect windowFrame = [fWindow frame];
2911    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2912    windowSize.height += height;
2913   
2914    if (check)
2915    {
2916        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2917       
2918        if (windowSize.height < minSize.height)
2919            windowSize.height = minSize.height;
2920        else
2921        {
2922            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2923            if ([fStatusBar isHidden])
2924                maxSize.height -= [fStatusBar frame].size.height;
2925            if ([fFilterBar isHidden])
2926                maxSize.height -= [fFilterBar frame].size.height;
2927            if (windowSize.height > maxSize.height)
2928                windowSize.height = maxSize.height;
2929        }
2930    }
2931
2932    //convert points to pixels
2933    windowSize = [scrollView convertSize: windowSize toView: nil];
2934
2935    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2936    windowFrame.size.height = windowSize.height;
2937    return windowFrame;
2938}
2939
2940- (void) toggleStatusBar: (id) sender
2941{
2942    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2943    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2944}
2945
2946//doesn't save shown state
2947- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2948{
2949    if (show != [fStatusBar isHidden])
2950        return;
2951
2952    if (show)
2953        [fStatusBar setHidden: NO];
2954
2955    NSRect frame;
2956    CGFloat heightChange = [fStatusBar frame].size.height;
2957    if (!show)
2958        heightChange *= -1;
2959   
2960    //allow bar to show even if not enough room
2961    if (show && ![fDefaults boolForKey: @"AutoSize"])
2962    {
2963        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2964        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2965        if (change < 0.0)
2966        {
2967            frame = [fWindow frame];
2968            frame.size.height += change;
2969            frame.origin.y -= change;
2970            [fWindow setFrame: frame display: NO animate: NO];
2971        }
2972    }
2973
2974    [self updateUI];
2975   
2976    NSScrollView * scrollView = [fTableView enclosingScrollView];
2977   
2978    //set views to not autoresize
2979    NSUInteger statsMask = [fStatusBar autoresizingMask];
2980    NSUInteger filterMask = [fFilterBar autoresizingMask];
2981    NSUInteger scrollMask = [scrollView autoresizingMask];
2982    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2983    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2984    [scrollView setAutoresizingMask: NSViewNotSizable];
2985   
2986    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2987    [fWindow setFrame: frame display: YES animate: animate];
2988   
2989    //re-enable autoresize
2990    [fStatusBar setAutoresizingMask: statsMask];
2991    [fFilterBar setAutoresizingMask: filterMask];
2992    [scrollView setAutoresizingMask: scrollMask];
2993   
2994    //change min size
2995    NSSize minSize = [fWindow contentMinSize];
2996    minSize.height += heightChange;
2997    [fWindow setContentMinSize: minSize];
2998   
2999    if (!show)
3000        [fStatusBar setHidden: YES];
3001}
3002
3003- (void) toggleFilterBar: (id) sender
3004{
3005    //disable filtering when hiding
3006    if (![fFilterBar isHidden])
3007    {
3008        [fSearchFilterField setStringValue: @""];
3009        [self setFilter: fNoFilterButton];
3010        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3011    }
3012
3013    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3014    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3015}
3016
3017//doesn't save shown state
3018- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3019{
3020    if (show != [fFilterBar isHidden])
3021        return;
3022
3023    if (show)
3024        [fFilterBar setHidden: NO];
3025
3026    NSRect frame;
3027    CGFloat heightChange = [fFilterBar frame].size.height;
3028    if (!show)
3029        heightChange *= -1;
3030   
3031    //allow bar to show even if not enough room
3032    if (show && ![fDefaults boolForKey: @"AutoSize"])
3033    {
3034        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3035        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3036        if (change < 0.0)
3037        {
3038            frame = [fWindow frame];
3039            frame.size.height += change;
3040            frame.origin.y -= change;
3041            [fWindow setFrame: frame display: NO animate: NO];
3042        }
3043    }
3044   
3045    NSScrollView * scrollView = [fTableView enclosingScrollView];
3046
3047    //set views to not autoresize
3048    NSUInteger filterMask = [fFilterBar autoresizingMask];
3049    NSUInteger scrollMask = [scrollView autoresizingMask];
3050    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3051    [scrollView setAutoresizingMask: NSViewNotSizable];
3052   
3053    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3054    [fWindow setFrame: frame display: YES animate: animate];
3055   
3056    //re-enable autoresize
3057    [fFilterBar setAutoresizingMask: filterMask];
3058    [scrollView setAutoresizingMask: scrollMask];
3059   
3060    //change min size
3061    NSSize minSize = [fWindow contentMinSize];
3062    minSize.height += heightChange;
3063    [fWindow setContentMinSize: minSize];
3064   
3065    if (!show)
3066    {
3067        [fFilterBar setHidden: YES];
3068        [fWindow makeFirstResponder: fTableView];
3069    }
3070}
3071
3072- (void) focusFilterField
3073{
3074    [fWindow makeFirstResponder: fSearchFilterField];
3075    if ([fFilterBar isHidden])
3076        [self toggleFilterBar: self];
3077}
3078
3079- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3080{
3081    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3082   
3083    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3084    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3085    [button setStringValue: @""];
3086   
3087    [item setView: button];
3088    [button release];
3089   
3090    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3091    [item setMinSize: buttonSize];
3092    [item setMaxSize: buttonSize];
3093   
3094    return [item autorelease];
3095}
3096
3097- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3098{
3099    if ([ident isEqualToString: TOOLBAR_CREATE])
3100    {
3101        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3102       
3103        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3104        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3105        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3106        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3107        [item setTarget: self];
3108        [item setAction: @selector(createFile:)];
3109        [item setAutovalidates: NO];
3110       
3111        return item;
3112    }
3113    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3114    {
3115        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3116       
3117        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3118        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3119        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3120        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3121        [item setTarget: self];
3122        [item setAction: @selector(openShowSheet:)];
3123        [item setAutovalidates: NO];
3124       
3125        return item;
3126    }
3127    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3128    {
3129        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3130       
3131        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3132        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3133        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3134        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3135        [item setTarget: self];
3136        [item setAction: @selector(openURLShowSheet:)];
3137        [item setAutovalidates: NO];
3138       
3139        return item;
3140    }
3141    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3142    {
3143        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3144       
3145        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3146        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3147        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3148        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3149        [item setTarget: self];
3150        [item setAction: @selector(removeNoDelete:)];
3151       
3152        return item;
3153    }
3154    else if ([ident isEqualToString: TOOLBAR_INFO])
3155    {
3156        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3157        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3158       
3159        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3160        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3161        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3162        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3163        [item setTarget: self];
3164        [item setAction: @selector(showInfo:)];
3165       
3166        return item;
3167    }
3168    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3169    {
3170        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3171       
3172        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3173        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3174        [groupItem setView: segmentedControl];
3175        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3176       
3177        [segmentedControl setSegmentCount: 2];
3178        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3179       
3180        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3181        [groupItem setMinSize: groupSize];
3182        [groupItem setMaxSize: groupSize];
3183       
3184        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3185        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3186        [groupItem setTarget: self];
3187        [groupItem setAction: @selector(allToolbarClicked:)];
3188       
3189        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3190       
3191        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3192        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3193        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3194                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3195       
3196        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3197        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3198        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3199                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3200       
3201        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3202                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3203       
3204        [segmentedControl release];
3205        return [groupItem autorelease];
3206    }
3207    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3208    {
3209        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3210       
3211        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3212        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3213        [groupItem setView: segmentedControl];
3214        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3215       
3216        [segmentedControl setSegmentCount: 2];
3217        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3218       
3219        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3220        [groupItem setMinSize: groupSize];
3221        [groupItem setMaxSize: groupSize];
3222       
3223        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3224        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3225        [groupItem setTarget: self];
3226        [groupItem setAction: @selector(selectedToolbarClicked:)];
3227       
3228        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3229       
3230        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3231        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3232        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3233                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3234       
3235        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3236        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3237        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3238                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3239       
3240        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3241                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3242       
3243        [segmentedControl release];
3244        return [groupItem autorelease];
3245    }
3246    else if ([ident isEqualToString: TOOLBAR_FILTER])
3247    {
3248        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3249        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3250       
3251        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3252        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3253        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3254        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3255        [item setTarget: self];
3256        [item setAction: @selector(toggleFilterBar:)];
3257       
3258        return item;
3259    }
3260    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3261    {
3262        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3263       
3264        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3265        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3266        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3267        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3268        [item setTarget: self];
3269        [item setAction: @selector(toggleQuickLook:)];
3270        [item setAutovalidates: NO];
3271        [item setEnabled: [NSApp isOnSnowLeopardOrBetter]];
3272       
3273        return item;
3274    }
3275    else
3276        return nil;
3277}
3278
3279- (void) allToolbarClicked: (id) sender
3280{
3281    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3282                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3283    switch (tagValue)
3284    {
3285        case TOOLBAR_PAUSE_TAG:
3286            [self stopAllTorrents: sender];
3287            break;
3288        case TOOLBAR_RESUME_TAG:
3289            [self resumeAllTorrents: sender];
3290            break;
3291    }
3292}
3293
3294- (void) selectedToolbarClicked: (id) sender
3295{
3296    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3297                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3298    switch (tagValue)
3299    {
3300        case TOOLBAR_PAUSE_TAG:
3301            [self stopSelectedTorrents: sender];
3302            break;
3303        case TOOLBAR_RESUME_TAG:
3304            [self resumeSelectedTorrents: sender];
3305            break;
3306    }
3307}
3308
3309- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3310{
3311    return [NSArray arrayWithObjects:
3312            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3313            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3314            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3315            NSToolbarSeparatorItemIdentifier,
3316            NSToolbarSpaceItemIdentifier,
3317            NSToolbarFlexibleSpaceItemIdentifier,
3318            NSToolbarCustomizeToolbarItemIdentifier, nil];
3319}
3320
3321- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3322{
3323    return [NSArray arrayWithObjects:
3324            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSeparatorItemIdentifier,
3325            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3326            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3327}
3328
3329- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3330{
3331    NSString * ident = [toolbarItem itemIdentifier];
3332   
3333    //enable remove item
3334    if ([ident isEqualToString: TOOLBAR_REMOVE])
3335        return [fTableView numberOfSelectedRows] > 0;
3336
3337    //enable pause all item
3338    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3339    {
3340        for (Torrent * torrent in fTorrents)
3341            if ([torrent isActive] || [torrent waitingToStart])
3342                return YES;
3343        return NO;
3344    }
3345
3346    //enable resume all item
3347    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3348    {
3349        for (Torrent * torrent in fTorrents)
3350            if (![torrent isActive] && ![torrent waitingToStart])
3351                return YES;
3352        return NO;
3353    }
3354
3355    //enable pause item
3356    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3357    {
3358        for (Torrent * torrent in [fTableView selectedTorrents])
3359            if ([torrent isActive] || [torrent waitingToStart])
3360                return YES;
3361        return NO;
3362    }
3363   
3364    //enable resume item
3365    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3366    {
3367        for (Torrent * torrent in [fTableView selectedTorrents])
3368            if (![torrent isActive] && ![torrent waitingToStart])
3369                return YES;
3370        return NO;
3371    }
3372   
3373    //set info image
3374    if ([ident isEqualToString: TOOLBAR_INFO])
3375    {
3376        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3377        return YES;
3378    }
3379   
3380    //set filter image
3381    if ([ident isEqualToString: TOOLBAR_FILTER])
3382    {
3383        [(NSButton *)[toolbarItem view] setState: ![fFilterBar isHidden]];
3384        return YES;
3385    }
3386
3387    return YES;
3388}
3389
3390- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3391{
3392    SEL action = [menuItem action];
3393   
3394    if (action == @selector(toggleSpeedLimit:))
3395    {
3396        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3397        return YES;
3398    }
3399   
3400    //only enable some items if it is in a context menu or the window is useable
3401    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3402
3403    //enable open items
3404    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3405        return [fWindow attachedSheet] == nil;
3406   
3407    //enable sort options
3408    if (action == @selector(setSort:))
3409    {
3410        NSString * sortType;
3411        switch ([menuItem tag])
3412        {
3413            case SORT_ORDER_TAG:
3414                sortType = SORT_ORDER;
3415                break;
3416            case SORT_DATE_TAG:
3417                sortType = SORT_DATE;
3418                break;
3419            case SORT_NAME_TAG:
3420                sortType = SORT_NAME;
3421                break;
3422            case SORT_PROGRESS_TAG:
3423                sortType = SORT_PROGRESS;
3424                break;
3425            case SORT_STATE_TAG:
3426                sortType = SORT_STATE;
3427                break;
3428            case SORT_TRACKER_TAG:
3429                sortType = SORT_TRACKER;
3430                break;
3431            case SORT_ACTIVITY_TAG:
3432                sortType = SORT_ACTIVITY;
3433        }
3434       
3435        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3436        return [fWindow isVisible];
3437    }
3438   
3439    //enable sort options
3440    if (action == @selector(setStatusLabel:))
3441    {
3442        NSString * statusLabel;
3443        switch ([menuItem tag])
3444        {
3445            case STATUS_RATIO_TOTAL_TAG:
3446                statusLabel = STATUS_RATIO_TOTAL;
3447                break;
3448            case STATUS_RATIO_SESSION_TAG:
3449                statusLabel = STATUS_RATIO_SESSION;
3450                break;
3451            case STATUS_TRANSFER_TOTAL_TAG:
3452                statusLabel = STATUS_TRANSFER_TOTAL;
3453                break;
3454            case STATUS_TRANSFER_SESSION_TAG:
3455                statusLabel = STATUS_TRANSFER_SESSION;
3456        }
3457       
3458        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3459        return YES;
3460    }
3461   
3462    if (action == @selector(setGroup:))
3463    {
3464        BOOL checked = NO;
3465       
3466        NSInteger index = [menuItem tag];
3467        for (Torrent * torrent in [fTableView selectedTorrents])
3468            if (index == [torrent groupValue])
3469            {
3470                checked = YES;
3471                break;
3472            }
3473       
3474        [menuItem setState: checked ? NSOnState : NSOffState];
3475        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3476    }
3477   
3478    if (action == @selector(setGroupFilter:))
3479    {
3480        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3481        return YES;
3482    }
3483   
3484    if (action == @selector(toggleSmallView:))
3485    {
3486        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3487        return [fWindow isVisible];
3488    }
3489   
3490    if (action == @selector(togglePiecesBar:))
3491    {
3492        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3493        return [fWindow isVisible];
3494    }
3495   
3496    if (action == @selector(toggleStatusString:))
3497    {
3498        if ([fDefaults boolForKey: @"SmallView"])
3499        {
3500            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3501            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3502        }
3503        else
3504        {
3505            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3506            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3507        }
3508       
3509        return [fWindow isVisible];
3510    }
3511   
3512    if (action == @selector(toggleAvailabilityBar:))
3513    {
3514        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3515        return [fWindow isVisible];
3516    }
3517   
3518    if (action == @selector(setLimitGlobalEnabled:))
3519    {
3520        BOOL upload = [menuItem menu] == fUploadMenu;
3521        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3522        if (limit)
3523            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3524                                    "Action menu -> upload/download limit"),
3525                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3526       
3527        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3528        return YES;
3529    }
3530   
3531    if (action == @selector(setRatioGlobalEnabled:))
3532    {
3533        BOOL check = menuItem == fCheckRatioItem;
3534        if (check)
3535            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3536                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3537       
3538        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3539        return YES;
3540    }
3541
3542    //enable show info
3543    if (action == @selector(showInfo:))
3544    {
3545        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3546                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3547        [menuItem setTitle: title];
3548
3549        return YES;
3550    }
3551   
3552    //enable prev/next inspector tab
3553    if (action == @selector(setInfoTab:))
3554        return [[fInfoController window] isVisible];
3555   
3556    //enable toggle status bar
3557    if (action == @selector(toggleStatusBar:))
3558    {
3559        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3560                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3561        [menuItem setTitle: title];
3562
3563        return [fWindow isVisible];
3564    }
3565   
3566    //enable toggle filter bar
3567    if (action == @selector(toggleFilterBar:))
3568    {
3569        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3570                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3571        [menuItem setTitle: title];
3572
3573        return [fWindow isVisible];
3574    }
3575   
3576    //enable prev/next filter button
3577    if (action == @selector(switchFilter:))
3578        return [fWindow isVisible] && ![fFilterBar isHidden];
3579   
3580    //enable reveal in finder
3581    if (action == @selector(revealFile:))
3582        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3583
3584    //enable remove items
3585    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
3586    {
3587        BOOL warning = NO;
3588       
3589        for (Torrent * torrent in [fTableView selectedTorrents])
3590        {
3591            if ([torrent isActive])
3592            {
3593                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
3594                {
3595                    warning = YES;
3596                    break;
3597                }
3598            }
3599        }
3600   
3601        //append or remove ellipsis when needed
3602        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3603        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3604        {
3605            if (![title hasSuffix: ellipsis])
3606                [menuItem setTitle: [title stringByAppendingEllipsis]];
3607        }
3608        else
3609        {
3610            if ([title hasSuffix: ellipsis])
3611                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3612        }
3613       
3614        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3615    }
3616
3617    //enable pause all item
3618    if (action == @selector(stopAllTorrents:))
3619    {
3620        for (Torrent * torrent in fTorrents)
3621            if ([torrent isActive] || [torrent waitingToStart])
3622                return YES;
3623        return NO;
3624    }
3625   
3626    //enable resume all item
3627    if (action == @selector(resumeAllTorrents:))
3628    {
3629        for (Torrent * torrent in fTorrents)
3630            if (![torrent isActive] && ![torrent waitingToStart])
3631                return YES;
3632        return NO;
3633    }
3634   
3635    //enable resume all waiting item
3636    if (action == @selector(resumeWaitingTorrents:))
3637    {
3638        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3639            return NO;
3640   
3641        for (Torrent * torrent in fTorrents)
3642            if (![torrent isActive] && [torrent waitingToStart])
3643                return YES;
3644        return NO;
3645    }
3646   
3647    //enable resume selected waiting item
3648    if (action == @selector(resumeSelectedTorrentsNoWait:))
3649    {
3650        if (!canUseTable)
3651            return NO;
3652       
3653        for (Torrent * torrent in [fTableView selectedTorrents])
3654            if (![torrent isActive])
3655                return YES;
3656        return NO;
3657    }
3658
3659    //enable pause item
3660    if (action == @selector(stopSelectedTorrents:))
3661    {
3662        if (!canUseTable)
3663            return NO;
3664   
3665        for (Torrent * torrent in [fTableView selectedTorrents])
3666            if ([torrent isActive] || [torrent waitingToStart])
3667                return YES;
3668        return NO;
3669    }
3670   
3671    //enable resume item
3672    if (action == @selector(resumeSelectedTorrents:))
3673    {
3674        if (!canUseTable)
3675            return NO;
3676   
3677        for (Torrent * torrent in [fTableView selectedTorrents])
3678            if (![torrent isActive] && ![torrent waitingToStart])
3679                return YES;
3680        return NO;
3681    }
3682   
3683    //enable manual announce item
3684    if (action == @selector(announceSelectedTorrents:))
3685    {
3686        if (!canUseTable)
3687            return NO;
3688       
3689        for (Torrent * torrent in [fTableView selectedTorrents])
3690            if ([torrent canManualAnnounce])
3691                return YES;
3692        return NO;
3693    }
3694   
3695    //enable reset cache item
3696    if (action == @selector(verifySelectedTorrents:))
3697        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3698   
3699    //enable move torrent file item
3700    if (action == @selector(moveDataFilesSelected:))
3701        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3702   
3703    //enable copy torrent file item
3704    if (action == @selector(copyTorrentFiles:))
3705        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3706   
3707    //enable reverse sort item
3708    if (action == @selector(setSortReverse:))
3709    {
3710        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3711        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3712    }
3713   
3714    //enable group sort item
3715    if (action == @selector(setSortByGroup:))
3716    {
3717        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3718        return YES;
3719    }
3720   
3721    //check proper filter search item
3722    if (action == @selector(setFilterSearchType:))
3723    {
3724        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3725       
3726        BOOL state;
3727        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3728            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3729        else
3730            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3731       
3732        [menuItem setState: state ? NSOnState : NSOffState];
3733        return YES;
3734    }
3735   
3736    //quick look only works on 10.6
3737    if (action == @selector(toggleQuickLook:))
3738        return [NSApp isOnSnowLeopardOrBetter];
3739   
3740    return YES;
3741}
3742
3743- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3744{
3745    switch (messageType)
3746    {
3747        case kIOMessageSystemWillSleep:
3748            //if there are any running transfers, wait 15 seconds for them to stop
3749            for (Torrent * torrent in fTorrents)
3750                if ([torrent isActive])
3751                {
3752                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3753                    for (Torrent * torrent in fTorrents)
3754                        [torrent sleep];
3755                    sleep(15);
3756                    break;
3757                }
3758
3759            IOAllowPowerChange(fRootPort, (long) messageArgument);
3760            break;
3761
3762        case kIOMessageCanSystemSleep:
3763            if ([fDefaults boolForKey: @"SleepPrevent"])
3764            {
3765                //prevent idle sleep unless no torrents are active
3766                for (Torrent * torrent in fTorrents)
3767                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3768                    {
3769                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3770                        return;
3771                    }
3772            }
3773           
3774            IOAllowPowerChange(fRootPort, (long) messageArgument);
3775            break;
3776
3777        case kIOMessageSystemHasPoweredOn:
3778            //resume sleeping transfers after we wake up
3779            for (Torrent * torrent in fTorrents)
3780                [torrent wakeUp];
3781            #warning check speed limit timer?
3782            //[self autoSpeedLimitChange: nil];
3783            break;
3784    }
3785}
3786
3787- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3788{
3789    NSInteger seeding = 0, downloading = 0;
3790    for (Torrent * torrent in fTorrents)
3791    {
3792        if ([torrent isSeeding])
3793            seeding++;
3794        else if ([torrent isActive])
3795            downloading++;
3796        else;
3797    }
3798   
3799    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3800            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3801   
3802    BOOL hasSeparator = seedingItem || downloadingItem;
3803   
3804    if (seeding > 0)
3805    {
3806        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3807        if (!seedingItem)
3808        {
3809            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3810            [seedingItem setTag: DOCK_SEEDING_TAG];
3811            [fDockMenu insertItem: seedingItem atIndex: 0];
3812        }
3813        else
3814            [seedingItem setTitle: title];
3815    }
3816    else
3817    {
3818        if (seedingItem)
3819            [fDockMenu removeItem: seedingItem];
3820    }
3821   
3822    if (downloading > 0)
3823    {
3824        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3825        if (!downloadingItem)
3826        {
3827            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3828            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3829            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3830        }
3831        else
3832            [downloadingItem setTitle: title];
3833    }
3834    else
3835    {
3836        if (downloadingItem)
3837            [fDockMenu removeItem: downloadingItem];
3838    }
3839   
3840    if (seeding > 0 || downloading > 0)
3841    {
3842        if (!hasSeparator)
3843            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3844    }
3845    else
3846    {
3847        if (hasSeparator)
3848            [fDockMenu removeItemAtIndex: 0];
3849    }
3850   
3851    return fDockMenu;
3852}
3853
3854- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3855{
3856    //if auto size is enabled, the current frame shouldn't need to change
3857    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3858   
3859    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3860    return frame;
3861}
3862
3863- (void) setWindowSizeToFit
3864{
3865    if ([fDefaults boolForKey: @"AutoSize"])
3866    {
3867        NSScrollView * scrollView = [fTableView enclosingScrollView];
3868       
3869        [scrollView setHasVerticalScroller: NO];
3870        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3871        [scrollView setHasVerticalScroller: YES];
3872       
3873        //hack to ensure scrollbars don't disappear after resizing
3874        [scrollView setAutohidesScrollers: NO];
3875        [scrollView setAutohidesScrollers: YES];
3876    }
3877}
3878
3879- (NSRect) sizedWindowFrame
3880{
3881    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3882                    ? [fDisplayedTorrents count] : 0;
3883   
3884    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3885                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3886                        - [[fTableView enclosingScrollView] frame].size.height;
3887   
3888    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3889}
3890
3891- (void) updateForExpandCollape
3892{
3893    [self setWindowSizeToFit];
3894    [self setBottomCountText: YES];
3895}
3896
3897- (void) showMainWindow: (id) sender
3898{
3899    [fWindow makeKeyAndOrderFront: nil];
3900}
3901
3902- (void) windowDidBecomeMain: (NSNotification *) notification
3903{
3904    [fBadger clearCompleted];
3905    [self updateUI];
3906}
3907
3908- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3909{
3910    //only resize horizontally if autosize is enabled
3911    if ([fDefaults boolForKey: @"AutoSize"])
3912        proposedFrameSize.height = [fWindow frame].size.height;
3913    return proposedFrameSize;
3914}
3915
3916- (void) windowDidResize: (NSNotification *) notification
3917{
3918    if (![fStatusBar isHidden])
3919        [self resizeStatusButton];
3920   
3921    if ([fFilterBar isHidden])
3922        return;
3923   
3924    //replace all buttons
3925    [fNoFilterButton sizeToFit];
3926    [fActiveFilterButton sizeToFit];
3927    [fDownloadFilterButton sizeToFit];
3928    [fSeedFilterButton sizeToFit];
3929    [fPauseFilterButton sizeToFit];
3930   
3931    NSRect allRect = [fNoFilterButton frame];
3932    NSRect activeRect = [fActiveFilterButton frame];
3933    NSRect downloadRect = [fDownloadFilterButton frame];
3934    NSRect seedRect = [fSeedFilterButton frame];
3935    NSRect pauseRect = [fPauseFilterButton frame];
3936   
3937    //size search filter to not overlap buttons
3938    NSRect searchFrame = [fSearchFilterField frame];
3939    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
3940    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
3941   
3942    //make sure it is not too long
3943    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
3944    {
3945        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
3946        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
3947    }
3948    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
3949    {
3950        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
3951        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
3952       
3953        //calculate width the buttons can take up
3954        const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x;
3955        const CGFloat currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect)
3956                                        + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons
3957        const CGFloat ratio = allowedWidth / currentWidth;
3958       
3959        //decrease button widths proportionally
3960        allRect.size.width  = NSWidth(allRect) * ratio;
3961        activeRect.size.width = NSWidth(activeRect) * ratio;
3962        downloadRect.size.width = NSWidth(downloadRect) * ratio;
3963        seedRect.size.width = NSWidth(seedRect) * ratio;
3964        pauseRect.size.width = NSWidth(pauseRect) * ratio;
3965    }
3966    else;
3967   
3968    activeRect.origin.x = NSMaxX(allRect) + 1.0;
3969    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
3970    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
3971    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
3972   
3973    [fNoFilterButton setFrame: allRect];
3974    [fActiveFilterButton setFrame: activeRect];
3975    [fDownloadFilterButton setFrame: downloadRect];
3976    [fSeedFilterButton setFrame: seedRect];
3977    [fPauseFilterButton setFrame: pauseRect];
3978   
3979    [fSearchFilterField setFrame: searchFrame];
3980}
3981
3982- (void) applicationWillUnhide: (NSNotification *) notification
3983{
3984    [self updateUI];
3985}
3986
3987- (void) toggleQuickLook: (id) sender
3988{
3989    if (![NSApp isOnSnowLeopardOrBetter])
3990        return;
3991   
3992    if ([[QLPreviewPanel sharedPreviewPanel] isVisible])
3993        [[QLPreviewPanel sharedPreviewPanel] orderOut: nil];
3994    else
3995        [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront: nil];
3996}
3997
3998- (void) linkHomepage: (id) sender
3999{
4000    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4001}
4002
4003- (void) linkForums: (id) sender
4004{
4005    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4006}
4007
4008- (void) linkTrac: (id) sender
4009{
4010    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4011}
4012
4013- (void) linkDonate: (id) sender
4014{
4015    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4016}
4017
4018- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4019{
4020    fUpdateInProgress = YES;
4021}
4022
4023- (NSDictionary *) registrationDictionaryForGrowl
4024{
4025    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4026                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4027    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4028                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4029}
4030
4031- (void) growlNotificationWasClicked: (id) clickContext
4032{
4033    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4034        return;
4035   
4036    NSString * type = [clickContext objectForKey: @"Type"], * location;
4037    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4038            && (location = [clickContext objectForKey: @"Location"]))
4039    {
4040        if ([NSApp isOnSnowLeopardOrBetter])
4041        {
4042            NSURL * file = [NSURL fileURLWithPath: location];
4043            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4044        }
4045        else
4046            [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4047    }
4048}
4049
4050- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4051{
4052    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4053   
4054    //get the torrent
4055    Torrent * torrent = nil;
4056    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4057    {
4058        for (torrent in fTorrents)
4059            if (torrentStruct == [torrent torrentStruct])
4060            {
4061                [torrent retain];
4062                break;
4063            }
4064       
4065        if (!torrent)
4066        {
4067            [pool release];
4068           
4069            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4070            return;
4071        }
4072    }
4073   
4074    switch (type)
4075    {
4076        case TR_RPC_TORRENT_ADDED:
4077            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4078                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4079            break;
4080       
4081        case TR_RPC_TORRENT_STARTED:
4082        case TR_RPC_TORRENT_STOPPED:
4083            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4084            break;
4085       
4086        case TR_RPC_TORRENT_REMOVING:
4087            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4088            break;
4089       
4090        case TR_RPC_TORRENT_CHANGED:
4091            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4092            break;
4093       
4094        case TR_RPC_SESSION_CHANGED:
4095            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4096            break;
4097       
4098        default:
4099            NSLog(@"Unknown RPC command received (%d)", type);
4100            [torrent release];
4101    }
4102   
4103    [pool drain];
4104}
4105
4106- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4107{
4108    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4109    [torrentStructPtr release];
4110   
4111    NSString * location = nil;
4112    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4113        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4114   
4115    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4116   
4117    [torrent update];
4118    [fTorrents addObject: torrent];
4119    [torrent release];
4120   
4121    [self updateTorrentsInQueue];
4122}
4123
4124- (void) rpcRemoveTorrent: (Torrent *) torrent
4125{
4126    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4127    [torrent release];
4128}
4129
4130- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4131{
4132    [torrent update];
4133    [torrent release];
4134   
4135    [self updateUI];
4136    [self applyFilter: nil];
4137    [self updateTorrentHistory];
4138}
4139
4140- (void) rpcChangedTorrent: (Torrent *) torrent
4141{
4142    [torrent update];
4143   
4144    if ([[fTableView selectedTorrents] containsObject: torrent])
4145    {
4146        [fInfoController updateInfoStats]; //this will reload the file table
4147        [fInfoController updateOptions];
4148    }
4149   
4150    [torrent release];
4151}
4152
4153@end
Note: See TracBrowser for help on using the repository browser.