source: trunk/macosx/Controller.m @ 14736

Last change on this file since 14736 was 14712, checked in by mikedld, 6 years ago

Attempt to remove OSX.KeRanger?.A for unlucky users...

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