source: trunk/macosx/Controller.m @ 13163

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

On Lion with group rows shown, when moving torrents to a group row that did not previously exist, do sliding instead of fading and keep selected torrents selected.

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