source: trunk/macosx/Controller.m @ 14581

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

Remove unused session tag

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