source: trunk/macosx/Controller.m @ 13248

Last change on this file since 13248 was 13248, checked in by livings124, 10 years ago

#4822 Enable Automatic Reference Counting

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