source: trunk/macosx/Controller.m @ 9197

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

first go at redoing the tracker inspector tab (some functionality is still missing)

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