source: trunk/macosx/Controller.m @ 14632

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

Revert r14501

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