source: trunk/macosx/Controller.m @ 14662

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

#6042: Remove dead code now that we build for OS X 10.7+ (patch by mattrajca)

In addition to the patch,

  • remove unused global actions menu (popover is used instead)
  • remove *Lion class macros, use NSPopover and NSDataDetector directly
  • Property svn:keywords set to Date Rev Author Id
File size: 183.7 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 14662 2016-01-06 11:05:37Z 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    //miscellaneous
1478    for (Torrent * torrent in torrents)
1479    {
1480        //don't want any of these starting then stopping
1481        if ([torrent waitingToStart])
1482            [torrent stopTransfer];
1483       
1484        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1485        [fTableView removeCollapsedGroup: [torrent groupValue]];
1486       
1487        //we can't assume the window is active - RPC removal, for example
1488        [fBadger removeTorrent: torrent];
1489    }
1490   
1491    //#5106 - don't try to remove torrents that have already been removed (fix for a bug, but better safe than crash anyway)
1492    NSIndexSet * indexesToRemove = [torrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(Torrent * torrent, NSUInteger idx, BOOL * stop) {
1493        return [fTorrents indexOfObjectIdenticalTo: torrent] != NSNotFound;
1494    }];
1495    if ([torrents count] != [indexesToRemove count])
1496    {
1497        NSLog(@"trying to remove %ld transfers, but %ld have already been removed", [torrents count], [torrents count] - [indexesToRemove count]);
1498        torrents = [torrents objectsAtIndexes: indexesToRemove];
1499       
1500        if ([indexesToRemove count] == 0)
1501        {
1502            [self fullUpdateUI];
1503            return;
1504        }
1505    }
1506   
1507    [fTorrents removeObjectsInArray: torrents];
1508   
1509    //set up helpers to remove from the table
1510    __block BOOL beganUpdate = NO;
1511   
1512    void (^doTableRemoval)(NSMutableArray *, id) = ^(NSMutableArray * displayedTorrents, id parent) {
1513        NSIndexSet * indexes = [displayedTorrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^(id obj, NSUInteger idx, BOOL * stop) {
1514            return [torrents containsObject: obj];
1515        }];
1516       
1517        if ([indexes count] > 0)
1518        {
1519            if (!beganUpdate)
1520            {
1521                [NSAnimationContext beginGrouping]; //this has to be before we set the completion handler (#4874)
1522               
1523                //we can't closeRemoveTorrent: until it's no longer in the GUI at all
1524                [[NSAnimationContext currentContext] setCompletionHandler: ^{
1525                    for (Torrent * torrent in torrents)
1526                        [torrent closeRemoveTorrent: deleteData];
1527                }];
1528               
1529                [fTableView beginUpdates];
1530                beganUpdate = YES;
1531            }
1532           
1533            [fTableView removeItemsAtIndexes: indexes inParent: parent withAnimation: NSTableViewAnimationSlideLeft];
1534
1535            [displayedTorrents removeObjectsAtIndexes: indexes];
1536        }
1537    };
1538   
1539    //if not removed from the displayed torrents here, fullUpdateUI might cause a crash
1540    if ([fDisplayedTorrents count] > 0)
1541    {
1542        if ([[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1543        {
1544            for (TorrentGroup * group in fDisplayedTorrents)
1545                doTableRemoval([group torrents], group);
1546        }
1547        else
1548            doTableRemoval(fDisplayedTorrents, nil);
1549       
1550        if (beganUpdate)
1551        {
1552            [fTableView endUpdates];
1553            [NSAnimationContext endGrouping];
1554        }
1555    }
1556   
1557    if (!beganUpdate)
1558    {
1559        //do here if we're not doing it at the end of the animation
1560        for (Torrent * torrent in torrents)
1561            [torrent closeRemoveTorrent: deleteData];
1562    }
1563   
1564    [self fullUpdateUI];
1565}
1566
1567- (void) removeNoDelete: (id) sender
1568{
1569    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO];
1570}
1571
1572- (void) removeDeleteData: (id) sender
1573{
1574    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES];
1575}
1576
1577- (void) clearCompleted: (id) sender
1578{
1579    NSMutableArray * torrents = [NSMutableArray array];
1580   
1581    for (Torrent * torrent in fTorrents)
1582        if ([torrent isFinishedSeeding])
1583            [torrents addObject: torrent];
1584   
1585    if ([fDefaults boolForKey: @"WarningRemoveCompleted"])
1586    {
1587        NSString * message, * info;
1588        if ([torrents count] == 1)
1589        {
1590            NSString * torrentName = [(Torrent *)[torrents objectAtIndex: 0] name];
1591            message = [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1592                                                                  "Remove completed confirm panel -> title"), torrentName];
1593           
1594            info = NSLocalizedString(@"Once removed, continuing the transfer will require the torrent file or magnet link.",
1595                                     "Remove completed confirm panel -> message");
1596        }
1597        else
1598        {
1599            message = [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove %@ completed transfers from the transfer list?",
1600                                                                  "Remove completed confirm panel -> title"), [NSString formattedUInteger: [torrents count]]];
1601           
1602            info = NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files or magnet links.",
1603                                     "Remove completed confirm panel -> message");
1604        }
1605       
1606        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
1607        [alert setMessageText: message];
1608        [alert setInformativeText: info];
1609        [alert setAlertStyle: NSWarningAlertStyle];
1610        [alert addButtonWithTitle: NSLocalizedString(@"Remove", "Remove completed confirm panel -> button")];
1611        [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Remove completed confirm panel -> button")];
1612        [alert setShowsSuppressionButton: YES];
1613       
1614        const NSInteger returnCode = [alert runModal];
1615        if ([[alert suppressionButton] state])
1616            [fDefaults setBool: NO forKey: @"WarningRemoveCompleted"];
1617       
1618        if (returnCode != NSAlertFirstButtonReturn)
1619            return;
1620    }
1621   
1622    [self confirmRemoveTorrents: torrents deleteData: NO];
1623}
1624
1625- (void) moveDataFilesSelected: (id) sender
1626{
1627    [self moveDataFiles: [fTableView selectedTorrents]];
1628}
1629
1630- (void) moveDataFiles: (NSArray *) torrents
1631{
1632    NSOpenPanel * panel = [NSOpenPanel openPanel];
1633    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1634    [panel setAllowsMultipleSelection: NO];
1635    [panel setCanChooseFiles: NO];
1636    [panel setCanChooseDirectories: YES];
1637    [panel setCanCreateDirectories: YES];
1638   
1639    NSInteger count = [torrents count];
1640    if (count == 1)
1641        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1642                            "Move torrent -> select destination folder"), [(Torrent *)[torrents objectAtIndex: 0] name]]];
1643    else
1644        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1645                            "Move torrent -> select destination folder"), count]];
1646   
1647    [panel beginSheetModalForWindow: fWindow completionHandler: ^(NSInteger result) {
1648        if (result == NSFileHandlingPanelOKButton)
1649        {
1650            for (Torrent * torrent in torrents)
1651                [torrent moveTorrentDataFileTo: [[[panel URLs] objectAtIndex: 0] path]];
1652        }
1653    }];
1654}
1655
1656- (void) copyTorrentFiles: (id) sender
1657{
1658    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1659}
1660
1661- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1662{
1663    if ([torrents count] == 0)
1664    {
1665        [torrents release];
1666        return;
1667    }
1668   
1669    Torrent * torrent = [torrents objectAtIndex: 0];
1670   
1671    if (![torrent isMagnet] && [[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1672    {
1673        NSSavePanel * panel = [NSSavePanel savePanel];
1674        [panel setAllowedFileTypes: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]];
1675        [panel setExtensionHidden: NO];
1676       
1677        [panel setNameFieldStringValue: [torrent name]];
1678       
1679        [panel beginSheetModalForWindow: fWindow completionHandler: ^(NSInteger result) {
1680            //copy torrent to new location with name of data file
1681            if (result == NSFileHandlingPanelOKButton)
1682                [torrent copyTorrentFileTo: [[panel URL] path]];
1683           
1684            [torrents removeObjectAtIndex: 0];
1685            [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1686        }];
1687    }
1688    else
1689    {
1690        if (![torrent isMagnet])
1691        {
1692            NSAlert * alert = [[NSAlert alloc] init];
1693            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1694            [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1695                                    "Torrent file copy alert -> title"), [torrent name]]];
1696            [alert setInformativeText: [NSString stringWithFormat:
1697                    NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1698                                        [torrent torrentLocation]]];
1699            [alert setAlertStyle: NSWarningAlertStyle];
1700           
1701            [alert runModal];
1702            [alert release];
1703        }
1704       
1705        [torrents removeObjectAtIndex: 0];
1706        [self copyTorrentFileForTorrents: torrents];
1707    }
1708}
1709
1710- (void) copyMagnetLinks: (id) sender
1711{
1712    NSArray * torrents = [fTableView selectedTorrents];
1713   
1714    if ([torrents count] <= 0)
1715        return;
1716   
1717    NSMutableArray * links = [NSMutableArray arrayWithCapacity: [torrents count]];
1718    for (Torrent * torrent in torrents)
1719        [links addObject: [torrent magnetLink]];
1720   
1721    NSString * text = [links componentsJoinedByString: @"\n"];
1722   
1723    NSPasteboard * pb = [NSPasteboard generalPasteboard];
1724    [pb clearContents];
1725    [pb writeObjects: [NSArray arrayWithObject: text]];
1726}
1727
1728- (void) revealFile: (id) sender
1729{
1730    NSArray * selected = [fTableView selectedTorrents];
1731    NSMutableArray * paths = [NSMutableArray arrayWithCapacity: [selected count]];
1732    for (Torrent * torrent in selected)
1733    {
1734        NSString * location = [torrent dataLocation];
1735        if (location)
1736            [paths addObject: [NSURL fileURLWithPath: location]];
1737    }
1738   
1739    if ([paths count] > 0)
1740        [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: paths];
1741}
1742
1743- (IBAction) renameSelected: (id) sender
1744{
1745    NSArray * selected = [fTableView selectedTorrents];
1746    NSAssert([selected count] == 1, @"1 transfer needs to be selected to rename, but %ld are selected", [selected count]);
1747    Torrent * torrent = [selected objectAtIndex:0];
1748   
1749    [FileRenameSheetController presentSheetForTorrent:torrent modalForWindow: fWindow completionHandler: ^(BOOL didRename) {
1750        if (didRename)
1751        {
1752            dispatch_async(dispatch_get_main_queue(), ^{
1753                [self fullUpdateUI];
1754               
1755                [[NSNotificationCenter defaultCenter] postNotificationName: @"ResetInspector" object: self userInfo: @{ @"Torrent" : torrent }];
1756            });
1757        }
1758    }];
1759}
1760
1761- (void) announceSelectedTorrents: (id) sender
1762{
1763    for (Torrent * torrent in [fTableView selectedTorrents])
1764    {
1765        if ([torrent canManualAnnounce])
1766            [torrent manualAnnounce];
1767    }
1768}
1769
1770- (void) verifySelectedTorrents: (id) sender
1771{
1772    [self verifyTorrents: [fTableView selectedTorrents]];
1773}
1774
1775- (void) verifyTorrents: (NSArray *) torrents
1776{
1777    for (Torrent * torrent in torrents)
1778        [torrent resetCache];
1779   
1780    [self applyFilter];
1781}
1782
1783- (NSArray *)selectedTorrents
1784{
1785    return [fTableView selectedTorrents];
1786}
1787
1788- (void) showPreferenceWindow: (id) sender
1789{
1790    NSWindow * window = [fPrefsController window];
1791    if (![window isVisible])
1792        [window center];
1793
1794    [window makeKeyAndOrderFront: nil];
1795}
1796
1797- (void) showAboutWindow: (id) sender
1798{
1799    [[AboutWindowController aboutController] showWindow: nil];
1800}
1801
1802- (void) showInfo: (id) sender
1803{
1804    if ([[fInfoController window] isVisible])
1805        [fInfoController close];
1806    else
1807    {
1808        [fInfoController updateInfoStats];
1809        [[fInfoController window] orderFront: nil];
1810       
1811        if ([fInfoController canQuickLook] && [QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible])
1812            [[QLPreviewPanel sharedPreviewPanel] reloadData];
1813    }
1814   
1815    [[fWindow toolbar] validateVisibleItems];
1816}
1817
1818- (void) resetInfo
1819{
1820    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1821   
1822    if ([QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible])
1823        [[QLPreviewPanel sharedPreviewPanel] reloadData];
1824}
1825
1826- (void) setInfoTab: (id) sender
1827{
1828    if (sender == fNextInfoTabItem)
1829        [fInfoController setNextTab];
1830    else
1831        [fInfoController setPreviousTab];
1832}
1833
1834- (MessageWindowController *) messageWindowController
1835{
1836    if (!fMessageController)
1837        fMessageController = [[MessageWindowController alloc] init];
1838   
1839    return fMessageController;
1840}
1841
1842- (void) showMessageWindow: (id) sender
1843{
1844    [[self messageWindowController] showWindow: nil];
1845}
1846
1847- (void) showStatsWindow: (id) sender
1848{
1849    [[StatsWindowController statsWindow] showWindow: nil];
1850}
1851
1852- (void) updateUI
1853{
1854    CGFloat dlRate = 0.0, ulRate = 0.0;
1855    BOOL anyCompleted = NO;
1856    for (Torrent * torrent in fTorrents)
1857    {
1858        [torrent update];
1859       
1860        //pull the upload and download speeds - most consistent by using current stats
1861        dlRate += [torrent downloadRate];
1862        ulRate += [torrent uploadRate];
1863       
1864        anyCompleted |= [torrent isFinishedSeeding];
1865    }
1866   
1867    if (![NSApp isHidden])
1868    {
1869        if ([fWindow isVisible])
1870        {
1871            [self sortTorrents: NO];
1872           
1873            [fStatusBar updateWithDownload: dlRate upload: ulRate];
1874           
1875            [fClearCompletedButton setHidden: !anyCompleted];
1876        }
1877
1878        //update non-constant parts of info window
1879        if ([[fInfoController window] isVisible])
1880            [fInfoController updateInfoStats];
1881    }
1882   
1883    //badge dock
1884    [fBadger updateBadgeWithDownload: dlRate upload: ulRate];
1885}
1886
1887#warning can this be removed or refined?
1888- (void) fullUpdateUI
1889{
1890    [self updateUI];
1891    [self applyFilter];
1892    [[fWindow toolbar] validateVisibleItems];
1893    [self updateTorrentHistory];
1894}
1895
1896- (void) setBottomCountText: (BOOL) filtering
1897{
1898    NSString * totalTorrentsString;
1899    NSUInteger totalCount = [fTorrents count];
1900    if (totalCount != 1)
1901        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Status bar transfer count"),
1902                                [NSString formattedUInteger: totalCount]];
1903    else
1904        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1905   
1906    if (filtering)
1907    {
1908        NSUInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1909        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1910            count -= [fDisplayedTorrents count];
1911       
1912        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Status bar transfer count"),
1913                                [NSString formattedUInteger: count], totalTorrentsString];
1914    }
1915   
1916    [fTotalTorrentsField setStringValue: totalTorrentsString];
1917}
1918
1919- (BOOL) userNotificationCenter: (NSUserNotificationCenter *) center shouldPresentNotification:(NSUserNotification *) notification
1920{
1921    return YES;
1922}
1923
1924- (void) userNotificationCenter: (NSUserNotificationCenter *) center didActivateNotification: (NSUserNotification *) notification
1925{
1926    if (![notification userInfo])
1927        return;
1928   
1929    if ([notification activationType] == NSUserNotificationActivationTypeActionButtonClicked) //reveal
1930    {
1931        Torrent * torrent = [self torrentForHash: [[notification userInfo] objectForKey: @"Hash"]];
1932        NSString * location = [torrent dataLocation];
1933        if (!location)
1934            location = [[notification userInfo] objectForKey: @"Location"];
1935        if (location)
1936            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: @[[NSURL fileURLWithPath: location]]];
1937    }
1938    else if ([notification activationType] == NSUserNotificationActivationTypeContentsClicked)
1939    {
1940        Torrent * torrent = [self torrentForHash: [[notification userInfo] objectForKey: @"Hash"]];
1941        if (torrent)
1942        {
1943            //select in the table - first see if it's already shown
1944            NSInteger row = [fTableView rowForItem: torrent];
1945            if (row == -1)
1946            {
1947                //if it's not shown, see if it's in a collapsed row
1948                if ([fDefaults boolForKey: @"SortByGroup"])
1949                {
1950                    __block TorrentGroup * parent = nil;
1951                    [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(TorrentGroup * group, NSUInteger idx, BOOL *stop) {
1952                        if ([[group torrents] containsObject: torrent])
1953                        {
1954                            parent = group;
1955                            *stop = YES;
1956                        }
1957                    }];
1958                    if (parent)
1959                    {
1960                        [[fTableView animator] expandItem: parent];
1961                        row = [fTableView rowForItem: torrent];
1962                    }
1963                }
1964               
1965                if (row == -1)
1966                {
1967                    //not found - must be filtering
1968                    NSAssert([fDefaults boolForKey: @"FilterBar"], @"expected the filter to be enabled");
1969                    [fFilterBar reset: YES];
1970                   
1971                    row = [fTableView rowForItem: torrent];
1972                   
1973                    //if it's not shown, it has to be in a collapsed row...again
1974                    if ([fDefaults boolForKey: @"SortByGroup"])
1975                    {
1976                        __block TorrentGroup * parent = nil;
1977                        [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(TorrentGroup * group, NSUInteger idx, BOOL *stop) {
1978                            if ([[group torrents] containsObject: torrent])
1979                            {
1980                                parent = group;
1981                                *stop = YES;
1982                            }
1983                        }];
1984                        if (parent)
1985                        {
1986                            [[fTableView animator] expandItem: parent];
1987                            row = [fTableView rowForItem: torrent];
1988                        }
1989                    }
1990                }
1991            }
1992           
1993            NSAssert1(row != -1, @"expected a row to be found for torrent %@", torrent);
1994            [fTableView selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection:NO];
1995            #warning focus the window
1996        }
1997    }
1998}
1999
2000- (Torrent *) torrentForHash: (NSString *) hash
2001{
2002    NSParameterAssert(hash != nil);
2003   
2004    __block Torrent * torrent = nil;
2005    [fTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) {
2006        if ([[(Torrent *)obj hashString] isEqualToString: hash])
2007        {
2008            torrent = obj;
2009            *stop = YES;
2010        }
2011    }];
2012    return torrent;
2013}
2014
2015- (void) torrentFinishedDownloading: (NSNotification *) notification
2016{
2017    Torrent * torrent = [notification object];
2018   
2019    if ([[[notification userInfo] objectForKey: @"WasRunning"] boolValue])
2020    {
2021        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
2022        {
2023            NSSound * sound;
2024            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
2025            {
2026                [sound setDelegate: self];
2027                fSoundPlaying = YES;
2028                [sound play];
2029            }
2030        }
2031       
2032        NSString * location = [torrent dataLocation];
2033       
2034        NSString * notificationTitle = NSLocalizedString(@"Download Complete", "notification title");
2035        if ([NSApp isOnMountainLionOrBetter])
2036        {
2037            NSUserNotification * notification = [[NSUserNotificationMtLion alloc] init];
2038            [notification setTitle: notificationTitle];
2039            [notification setInformativeText: [torrent name]];
2040           
2041            [notification setHasActionButton: YES];
2042            [notification setActionButtonTitle: NSLocalizedString(@"Show", "notification button")];
2043           
2044            NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithObject: [torrent hashString] forKey: @"Hash"];
2045            if (location)
2046                [userInfo setObject: location forKey: @"Location"];
2047            [notification setUserInfo: userInfo];
2048           
2049            [[NSUserNotificationCenterMtLion defaultUserNotificationCenter] deliverNotification: notification];
2050            [notification release];
2051        }
2052       
2053        NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObjectsAndKeys:
2054                                              GROWL_DOWNLOAD_COMPLETE, @"Type", nil];
2055       
2056        if (location)
2057            [clickContext setObject: location forKey: @"Location"];
2058       
2059        [GrowlApplicationBridge notifyWithTitle: notificationTitle
2060                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
2061                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2062       
2063        //NSLog(@"delegate: %@", [[NSUserNotificationCenterMtLion defaultUserNotificationCenter] delegate]);
2064       
2065        if (![fWindow isMainWindow])
2066            [fBadger addCompletedTorrent: torrent];
2067       
2068        //bounce download stack
2069        [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"com.apple.DownloadFileFinished"
2070            object: [torrent dataLocation]];
2071    }
2072   
2073    [self fullUpdateUI];
2074}
2075
2076- (void) torrentRestartedDownloading: (NSNotification *) notification
2077{
2078    [self fullUpdateUI];
2079}
2080
2081- (void) torrentFinishedSeeding: (NSNotification *) notification
2082{
2083    Torrent * torrent = [notification object];
2084   
2085    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
2086    {
2087        NSSound * sound;
2088        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
2089        {
2090            [sound setDelegate: self];
2091            fSoundPlaying = YES;
2092            [sound play];
2093        }
2094    }
2095   
2096    NSString * location = [torrent dataLocation];
2097   
2098    NSString * notificationTitle = NSLocalizedString(@"Seeding Complete", "notification title");
2099    if ([NSApp isOnMountainLionOrBetter])
2100    {
2101        NSUserNotification * notification = [[NSUserNotificationMtLion alloc] init];
2102        [notification setTitle: notificationTitle];
2103        [notification setInformativeText: [torrent name]];
2104       
2105        [notification setHasActionButton: YES];
2106        [notification setActionButtonTitle: NSLocalizedString(@"Show", "notification button")];
2107       
2108        notification.additionalActions = @[ [NSUserNotificationAction actionWithIdentifier:@"a" title:@"a"], [NSUserNotificationAction actionWithIdentifier:@"b" title:@"b"] ];
2109       
2110        NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithObject: [torrent hashString] forKey: @"Hash"];
2111        if (location)
2112            [userInfo setObject: location forKey: @"Location"];
2113        [notification setUserInfo: userInfo];
2114       
2115        [[NSUserNotificationCenterMtLion defaultUserNotificationCenter] deliverNotification: notification];
2116        [notification release];
2117    }
2118   
2119    NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_SEEDING_COMPLETE forKey: @"Type"];
2120   
2121    if (location)
2122        [clickContext setObject: location forKey: @"Location"];
2123   
2124    [GrowlApplicationBridge notifyWithTitle: notificationTitle
2125                                description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2126                                   iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2127   
2128    //removing from the list calls fullUpdateUI
2129    if ([torrent removeWhenFinishSeeding])
2130        [self confirmRemoveTorrents: @[ torrent ] deleteData: NO];
2131    else
2132    {
2133        if (![fWindow isMainWindow])
2134            [fBadger addCompletedTorrent: torrent];
2135       
2136        [self fullUpdateUI];
2137       
2138        if ([[fTableView selectedTorrents] containsObject: torrent])
2139        {
2140            [fInfoController updateInfoStats];
2141            [fInfoController updateOptions];
2142        }
2143    }
2144}
2145
2146- (void) updateTorrentHistory
2147{
2148    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2149   
2150    for (Torrent * torrent in fTorrents)
2151        [history addObject: [torrent history]];
2152   
2153    NSString * historyFile = [fConfigDirectory stringByAppendingPathComponent: TRANSFER_PLIST];
2154    [history writeToFile: historyFile atomically: YES];
2155}
2156
2157- (void) setSort: (id) sender
2158{
2159    NSString * sortType;
2160    switch ([(NSMenuItem *)sender tag])
2161    {
2162        case SORT_ORDER_TAG:
2163            sortType = SORT_ORDER;
2164            [fDefaults setBool: NO forKey: @"SortReverse"];
2165            break;
2166        case SORT_DATE_TAG:
2167            sortType = SORT_DATE;
2168            break;
2169        case SORT_NAME_TAG:
2170            sortType = SORT_NAME;
2171            break;
2172        case SORT_PROGRESS_TAG:
2173            sortType = SORT_PROGRESS;
2174            break;
2175        case SORT_STATE_TAG:
2176            sortType = SORT_STATE;
2177            break;
2178        case SORT_TRACKER_TAG:
2179            sortType = SORT_TRACKER;
2180            break;
2181        case SORT_ACTIVITY_TAG:
2182            sortType = SORT_ACTIVITY;
2183            break;
2184        case SORT_SIZE_TAG:
2185            sortType = SORT_SIZE;
2186            break;
2187        default:
2188            NSAssert1(NO, @"Unknown sort tag received: %ld", [(NSMenuItem *)sender tag]);
2189            return;
2190    }
2191   
2192    [fDefaults setObject: sortType forKey: @"Sort"];
2193   
2194    [self sortTorrents: YES];
2195}
2196
2197- (void) setSortByGroup: (id) sender
2198{
2199    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
2200    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
2201   
2202    [self applyFilter];
2203}
2204
2205- (void) setSortReverse: (id) sender
2206{
2207    const BOOL setReverse = [(NSMenuItem *)sender tag] == SORT_DESC_TAG;
2208    if (setReverse != [fDefaults boolForKey: @"SortReverse"])
2209    {
2210        [fDefaults setBool: setReverse forKey: @"SortReverse"];
2211        [self sortTorrents: NO];
2212    }
2213}
2214
2215- (void) sortTorrents: (BOOL) includeQueueOrder
2216{
2217    //actually sort
2218    [self sortTorrentsCallUpdates: YES includeQueueOrder: includeQueueOrder];
2219    [fTableView setNeedsDisplay: YES];
2220}
2221
2222- (void) sortTorrentsCallUpdates: (BOOL) callUpdates includeQueueOrder: (BOOL) includeQueueOrder
2223{
2224    const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
2225   
2226    NSArray * descriptors;
2227    NSSortDescriptor * nameDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: asc selector: @selector(localizedStandardCompare:)];
2228   
2229    NSString * sortType = [fDefaults stringForKey: @"Sort"];
2230    if ([sortType isEqualToString: SORT_STATE])
2231    {
2232        NSSortDescriptor * stateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"stateSortKey" ascending: !asc],
2233                        * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: !asc],
2234                        * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: !asc];
2235       
2236        descriptors = [NSArray arrayWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor, nameDescriptor, nil];
2237    }
2238    else if ([sortType isEqualToString: SORT_PROGRESS])
2239    {
2240        NSSortDescriptor * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: asc],
2241                        * ratioProgressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progressStopRatio" ascending: asc],
2242                        * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: asc];
2243       
2244        descriptors = [NSArray arrayWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor, nameDescriptor, nil];
2245    }
2246    else if ([sortType isEqualToString: SORT_TRACKER])
2247    {
2248        NSSortDescriptor * trackerDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"trackerSortKey" ascending: asc selector: @selector(localizedCaseInsensitiveCompare:)];
2249       
2250        descriptors = [NSArray arrayWithObjects: trackerDescriptor, nameDescriptor, nil];
2251    }
2252    else if ([sortType isEqualToString: SORT_ACTIVITY])
2253    {
2254        NSSortDescriptor * rateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"totalRate" ascending: !asc];
2255        NSSortDescriptor * activityDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateActivityOrAdd" ascending: !asc];
2256       
2257        descriptors = [NSArray arrayWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
2258    }
2259    else if ([sortType isEqualToString: SORT_DATE])
2260    {
2261        NSSortDescriptor * dateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateAdded" ascending: asc];
2262       
2263        descriptors = [NSArray arrayWithObjects: dateDescriptor, nameDescriptor, nil];
2264    }
2265    else if ([sortType isEqualToString: SORT_SIZE])
2266    {
2267        NSSortDescriptor * sizeDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"size" ascending: asc];
2268       
2269        descriptors = [NSArray arrayWithObjects: sizeDescriptor, nameDescriptor, nil];
2270    }
2271    else if ([sortType isEqualToString: SORT_NAME])
2272    {
2273        descriptors = [NSArray arrayWithObject: nameDescriptor];
2274    }
2275    else
2276    {
2277        NSAssert1([sortType isEqualToString: SORT_ORDER], @"Unknown sort type received: %@", sortType);
2278       
2279        if (!includeQueueOrder)
2280            return;
2281       
2282        NSSortDescriptor * orderDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: asc];
2283       
2284        descriptors = [NSArray arrayWithObject: orderDescriptor];
2285    }
2286   
2287    BOOL beganTableUpdate = !callUpdates;
2288   
2289    //actually sort
2290    if ([fDefaults boolForKey: @"SortByGroup"])
2291    {
2292        for (TorrentGroup * group in fDisplayedTorrents)
2293            [self rearrangeTorrentTableArray: [group torrents] forParent: group withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate];
2294    }
2295    else
2296        [self rearrangeTorrentTableArray: fDisplayedTorrents forParent: nil withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate];
2297   
2298    if (beganTableUpdate && callUpdates)
2299    {
2300        [fTableView endUpdates];
2301    }
2302}
2303
2304#warning redo so that we search a copy once again (best explained by changing sorting from ascending to descending)
2305- (void) rearrangeTorrentTableArray: (NSMutableArray *) rearrangeArray forParent: parent withSortDescriptors: (NSArray *) descriptors beganTableUpdate: (BOOL *) beganTableUpdate
2306{
2307    for (NSUInteger currentIndex = 1; currentIndex < [rearrangeArray count]; ++currentIndex)
2308    {
2309        //manually do the sorting in-place
2310        const NSUInteger insertIndex = [rearrangeArray indexOfObject: [rearrangeArray objectAtIndex: currentIndex] inSortedRange: NSMakeRange(0, currentIndex) options: (NSBinarySearchingInsertionIndex | NSBinarySearchingLastEqual) usingComparator: ^NSComparisonResult(id obj1, id obj2) {
2311            for (NSSortDescriptor * descriptor in descriptors)
2312            {
2313                const NSComparisonResult result = [descriptor compareObject: obj1 toObject: obj2];
2314                if (result != NSOrderedSame)
2315                    return result;
2316            }
2317           
2318            return NSOrderedSame;
2319        }];
2320       
2321        if (insertIndex != currentIndex)
2322        {
2323            if (!*beganTableUpdate)
2324            {
2325                *beganTableUpdate = YES;
2326                [fTableView beginUpdates];
2327            }
2328           
2329            [rearrangeArray moveObjectAtIndex: currentIndex toIndex: insertIndex];
2330            [fTableView moveItemAtIndex: currentIndex inParent: parent toIndex: insertIndex inParent: parent];
2331        }
2332    }
2333   
2334    NSAssert2([rearrangeArray isEqualToArray: [rearrangeArray sortedArrayUsingDescriptors: descriptors]], @"Torrent rearranging didn't work! %@ %@", rearrangeArray, [rearrangeArray sortedArrayUsingDescriptors: descriptors]);
2335}
2336
2337- (void) applyFilter
2338{
2339    __block int32_t active = 0, downloading = 0, seeding = 0, paused = 0;
2340    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2341    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
2342    if ([filterType isEqualToString: FILTER_ACTIVE])
2343        filterActive = YES;
2344    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2345        filterDownload = YES;
2346    else if ([filterType isEqualToString: FILTER_SEED])
2347        filterSeed = YES;
2348    else if ([filterType isEqualToString: FILTER_PAUSE])
2349        filterPause = YES;
2350    else
2351        filterStatus = NO;
2352   
2353    const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
2354    const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
2355   
2356    NSArray * searchStrings = [fFilterBar searchStrings];
2357    if (searchStrings && [searchStrings count] == 0)
2358        searchStrings = nil;
2359    const BOOL filterTracker = searchStrings && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
2360   
2361    //filter & get counts of each type
2362    NSIndexSet * indexesOfNonFilteredTorrents = [fTorrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(Torrent * torrent, NSUInteger idx, BOOL * stop) {
2363        //check status
2364        if ([torrent isActive] && ![torrent isCheckingWaiting])
2365        {
2366            const BOOL isActive = ![torrent isStalled];
2367            if (isActive)
2368                OSAtomicIncrement32(&active);
2369           
2370            if ([torrent isSeeding])
2371            {
2372                OSAtomicIncrement32(&seeding);
2373                if (filterStatus && !((filterActive && isActive) || filterSeed))
2374                    return NO;
2375            }
2376            else
2377            {
2378                OSAtomicIncrement32(&downloading);
2379                if (filterStatus && !((filterActive && isActive) || filterDownload))
2380                    return NO;
2381            }
2382        }
2383        else
2384        {
2385            OSAtomicIncrement32(&paused);
2386            if (filterStatus && !filterPause)
2387                return NO;
2388        }
2389       
2390        //checkGroup
2391        if (filterGroup)
2392            if ([torrent groupValue] != groupFilterValue)
2393                return NO;
2394       
2395        //check text field
2396        if (searchStrings)
2397        {
2398            __block BOOL removeTextField = NO;
2399            if (filterTracker)
2400            {
2401                NSArray * trackers = [torrent allTrackersFlat];
2402               
2403                //to count, we need each string in at least 1 tracker
2404                [searchStrings enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id searchString, NSUInteger idx, BOOL * stop) {
2405                    __block BOOL found = NO;
2406                    [trackers enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id tracker, NSUInteger idx, BOOL * stopTracker) {
2407                        if ([tracker rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound)
2408                        {
2409                            found = YES;
2410                            *stopTracker = YES;
2411                        }
2412                    }];
2413                    if (!found)
2414                    {
2415                        removeTextField = YES;
2416                        *stop = YES;
2417                    }
2418                }];
2419            }
2420            else
2421            {
2422                [searchStrings enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id searchString, NSUInteger idx, BOOL * stop) {
2423                    if ([[torrent name] rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound)
2424                    {
2425                        removeTextField = YES;
2426                        *stop = YES;
2427                    }
2428                }];
2429            }
2430           
2431            if (removeTextField)
2432                return NO;
2433        }
2434       
2435        return YES;
2436    }];
2437   
2438    NSArray * allTorrents = [fTorrents objectsAtIndexes: indexesOfNonFilteredTorrents];
2439   
2440    //set button tooltips
2441    if (fFilterBar)
2442        [fFilterBar setCountAll: [fTorrents count] active: active downloading: downloading seeding: seeding paused: paused];
2443   
2444    //if either the previous or current lists are blank, set its value to the other
2445    const BOOL groupRows = [allTorrents count] > 0 ? [fDefaults boolForKey: @"SortByGroup"] : ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]]);
2446    const BOOL wasGroupRows = [fDisplayedTorrents count] > 0 ? [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]] : groupRows;
2447   
2448    #warning could probably be merged with later code somehow
2449    //clear display cache for not-shown torrents
2450    if ([fDisplayedTorrents count] > 0)
2451    {
2452        //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
2453        void (^removePreviousFinishedPieces)(id, NSUInteger, BOOL *) = ^(Torrent * torrent, NSUInteger idx, BOOL * stop) {
2454            //we used to keep track of which torrents we already found in allTorrents, but it wasn't safe fo concurrent enumeration
2455            if (![allTorrents containsObject: torrent])
2456                [torrent setPreviousFinishedPieces: nil];
2457        };
2458       
2459        if (wasGroupRows)
2460            [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) {
2461                [[(TorrentGroup *)obj torrents] enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces];
2462            }];
2463        else
2464            [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces];
2465    }
2466   
2467    BOOL beganUpdates = NO;
2468
2469    //don't animate torrents when first launching
2470    static dispatch_once_t onceToken;
2471    dispatch_once(&onceToken, ^{
2472        [[NSAnimationContext currentContext] setDuration: 0];
2473    });
2474    [NSAnimationContext beginGrouping];
2475   
2476    //add/remove torrents (and rearrange for groups), one by one
2477    if (!groupRows && !wasGroupRows)
2478    {
2479        NSMutableIndexSet * addIndexes = [NSMutableIndexSet indexSet],
2480                        * removePreviousIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])];
2481       
2482        //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)
2483        [allTorrents enumerateObjectsWithOptions: 0 usingBlock: ^(id objAll, NSUInteger previousIndex, BOOL * stop) {
2484            const NSUInteger currentIndex = [fDisplayedTorrents indexOfObjectAtIndexes: removePreviousIndexes options: NSEnumerationConcurrent passingTest: ^(id objDisplay, NSUInteger idx, BOOL *stop) {
2485                return (BOOL)(objAll == objDisplay);
2486            }];
2487            if (currentIndex == NSNotFound)
2488                [addIndexes addIndex: previousIndex];
2489            else
2490                [removePreviousIndexes removeIndex: currentIndex];
2491        }];
2492       
2493        if ([addIndexes count] > 0 || [removePreviousIndexes count] > 0)
2494        {
2495            beganUpdates = YES;
2496            [fTableView beginUpdates];
2497           
2498            //remove torrents we didn't find
2499            if ([removePreviousIndexes count] > 0)
2500            {
2501                [fDisplayedTorrents removeObjectsAtIndexes: removePreviousIndexes];
2502                [fTableView removeItemsAtIndexes: removePreviousIndexes inParent: nil withAnimation: NSTableViewAnimationSlideDown];
2503            }
2504           
2505            //add new torrents
2506            if ([addIndexes count] > 0)
2507            {
2508                //slide new torrents in differently
2509                if (fAddingTransfers)
2510                {
2511                    NSIndexSet * newAddIndexes = [allTorrents indexesOfObjectsAtIndexes: addIndexes options: NSEnumerationConcurrent passingTest: ^BOOL(id obj, NSUInteger idx, BOOL * stop) {
2512                        return [fAddingTransfers containsObject: obj];
2513                    }];
2514                   
2515                    [addIndexes removeIndexes: newAddIndexes];
2516                   
2517                    [fDisplayedTorrents addObjectsFromArray: [allTorrents objectsAtIndexes: newAddIndexes]];
2518                    [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange([fDisplayedTorrents count] - [newAddIndexes count], [newAddIndexes count])] inParent: nil withAnimation: NSTableViewAnimationSlideLeft];
2519                }
2520               
2521                [fDisplayedTorrents addObjectsFromArray: [allTorrents objectsAtIndexes: addIndexes]];
2522                [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange([fDisplayedTorrents count] - [addIndexes count], [addIndexes count])] inParent: nil withAnimation: NSTableViewAnimationSlideDown];
2523            }
2524        }
2525    }
2526    else if (groupRows && wasGroupRows)
2527    {
2528        NSAssert(groupRows && wasGroupRows, @"Should have had group rows and should remain with group rows");
2529       
2530        #warning don't always do?
2531        beganUpdates = YES;
2532        [fTableView beginUpdates];
2533       
2534        NSMutableIndexSet * unusedAllTorrentsIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [allTorrents count])];
2535       
2536        NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: [fDisplayedTorrents count]];
2537        for (TorrentGroup * group in fDisplayedTorrents)
2538            [groupsByIndex setObject: group forKey: [NSNumber numberWithInteger: [group groupIndex]]];
2539       
2540        const NSUInteger originalGroupCount = [fDisplayedTorrents count];
2541        for (NSUInteger index = 0; index < originalGroupCount; ++index)
2542        {
2543            TorrentGroup * group = [fDisplayedTorrents objectAtIndex: index];
2544           
2545            NSMutableIndexSet * removeIndexes = [NSMutableIndexSet indexSet];
2546           
2547            //needs to be a signed integer
2548            for (NSInteger indexInGroup = 0; indexInGroup < [[group torrents] count]; ++indexInGroup)
2549            {
2550                Torrent * torrent = [[group torrents] objectAtIndex: indexInGroup];
2551                const NSUInteger allIndex = [allTorrents indexOfObjectAtIndexes: unusedAllTorrentsIndexes options: NSEnumerationConcurrent passingTest: ^(id obj, NSUInteger idx, BOOL * stop) {
2552                    return (BOOL)(obj == torrent);
2553                }];
2554                if (allIndex == NSNotFound)
2555                    [removeIndexes addIndex: indexInGroup];
2556                else
2557                {
2558                    BOOL markTorrentAsUsed = YES;
2559                   
2560                    const NSInteger groupValue = [torrent groupValue];
2561                    if (groupValue != [group groupIndex])
2562                    {
2563                        TorrentGroup * newGroup = [groupsByIndex objectForKey: [NSNumber numberWithInteger: groupValue]];
2564                        if (!newGroup)
2565                        {
2566                            newGroup = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2567                            [groupsByIndex setObject: newGroup forKey: [NSNumber numberWithInteger: groupValue]];
2568                            [fDisplayedTorrents addObject: newGroup];
2569
2570                            [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [fDisplayedTorrents count]-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2571                            [fTableView isGroupCollapsed: groupValue] ? [fTableView collapseItem: newGroup] : [fTableView expandItem: newGroup];
2572                        }
2573                        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
2574                        {
2575                            //ugggh, but shouldn't happen too often
2576                            if ([fDisplayedTorrents indexOfObject: newGroup inRange: NSMakeRange(index+1, originalGroupCount-(index+1))] != NSNotFound)
2577                                markTorrentAsUsed = NO;
2578                        }
2579                       
2580                        [[group torrents] removeObjectAtIndex: indexInGroup];
2581                        [[newGroup torrents] addObject: torrent];
2582
2583                        [fTableView moveItemAtIndex: indexInGroup inParent: group toIndex: [[newGroup torrents] count]-1 inParent: newGroup];
2584                       
2585                        --indexInGroup;
2586                    }
2587                   
2588                    if (markTorrentAsUsed)
2589                        [unusedAllTorrentsIndexes removeIndex: allIndex];
2590                }
2591            }
2592           
2593            if ([removeIndexes count] > 0)
2594            {
2595                [[group torrents] removeObjectsAtIndexes: removeIndexes];
2596                [fTableView removeItemsAtIndexes: removeIndexes inParent: group withAnimation: NSTableViewAnimationEffectFade];
2597            }
2598        }
2599       
2600        //add remaining new torrents
2601        for (Torrent * torrent in [allTorrents objectsAtIndexes: unusedAllTorrentsIndexes])
2602        {
2603            const NSInteger groupValue = [torrent groupValue];
2604            TorrentGroup * group = [groupsByIndex objectForKey: [NSNumber numberWithInteger: groupValue]];
2605            if (!group)
2606            {
2607                group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2608                [groupsByIndex setObject: group forKey: [NSNumber numberWithInteger: groupValue]];
2609                [fDisplayedTorrents addObject: group];
2610
2611                [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [fDisplayedTorrents count]-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2612                [fTableView isGroupCollapsed: groupValue] ? [fTableView collapseItem: group] : [fTableView expandItem: group];
2613            }
2614           
2615            [[group torrents] addObject: torrent];
2616
2617            const BOOL newTorrent = fAddingTransfers && [fAddingTransfers containsObject: torrent];
2618            [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [[group torrents] count]-1] inParent: group withAnimation: newTorrent ? NSTableViewAnimationSlideLeft : NSTableViewAnimationSlideDown];
2619        }
2620       
2621        //remove empty groups
2622        NSIndexSet * removeGroupIndexes = [fDisplayedTorrents indexesOfObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, originalGroupCount)] options: NSEnumerationConcurrent passingTest: ^BOOL(id obj, NSUInteger idx, BOOL * stop) {
2623            return [[(TorrentGroup *)obj torrents] count] == 0;
2624        }];
2625       
2626        if ([removeGroupIndexes count] > 0)
2627        {
2628            [fDisplayedTorrents removeObjectsAtIndexes: removeGroupIndexes];
2629            [fTableView removeItemsAtIndexes: removeGroupIndexes inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2630        }
2631       
2632        //now that all groups are there, sort them - don't insert on the fly in case groups were reordered in prefs
2633        NSSortDescriptor * groupDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"groupOrderValue" ascending: YES];
2634        [self rearrangeTorrentTableArray: fDisplayedTorrents forParent: nil withSortDescriptors: [NSArray arrayWithObject: groupDescriptor] beganTableUpdate: &beganUpdates];
2635    }
2636    else
2637    {
2638        NSAssert(groupRows != wasGroupRows, @"Trying toggling group-torrent reordering when we weren't expecting to.");
2639       
2640        //set all groups as expanded
2641        [fTableView removeAllCollapsedGroups];
2642       
2643        //since we're not doing this the right way (boo buggy animation), we need to remember selected values
2644        #warning when Lion-only and using views instead of cells, this likely won't be needed
2645        NSArray * selectedValues = [fTableView selectedValues];
2646       
2647        beganUpdates = YES;
2648        [fTableView beginUpdates];
2649
2650        [fTableView removeItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])] inParent: nil withAnimation: NSTableViewAnimationSlideDown];
2651       
2652        if (groupRows)
2653        {
2654            //a map for quickly finding groups
2655            NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: [[GroupsController groups] numberOfGroups]];
2656            for (Torrent * torrent in allTorrents)
2657            {
2658                const NSInteger groupValue = [torrent groupValue];
2659                TorrentGroup * group = [groupsByIndex objectForKey: [NSNumber numberWithInteger: groupValue]];
2660                if (!group)
2661                {
2662                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2663                    [groupsByIndex setObject: group forKey: [NSNumber numberWithInteger: groupValue]];
2664                }
2665               
2666                [[group torrents] addObject: torrent];
2667            }
2668           
2669            [fDisplayedTorrents setArray: [groupsByIndex allValues]];
2670           
2671            //we need the groups to be sorted, and we can do it without moving items in the table, too!
2672            NSSortDescriptor * groupDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"groupOrderValue" ascending: YES];
2673            [fDisplayedTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2674        }
2675        else
2676            [fDisplayedTorrents setArray: allTorrents];
2677
2678        [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])] inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2679       
2680        if (groupRows)
2681        {
2682            //actually expand group rows
2683            for (TorrentGroup * group in fDisplayedTorrents)
2684                [fTableView expandItem: group];
2685        }
2686       
2687        if (selectedValues)
2688            [fTableView selectValues: selectedValues];
2689    }
2690   
2691    //sort the torrents (won't sort the groups, though)
2692    [self sortTorrentsCallUpdates: !beganUpdates includeQueueOrder: YES];
2693
2694    if (beganUpdates)
2695        [fTableView endUpdates];
2696    [fTableView setNeedsDisplay: YES];
2697   
2698    [NSAnimationContext endGrouping];
2699
2700    [self resetInfo]; //if group is already selected, but the torrents in it change
2701   
2702    [self setBottomCountText: groupRows || filterStatus || filterGroup || searchStrings];
2703   
2704    [self setWindowSizeToFit];
2705   
2706    if (fAddingTransfers)
2707    {
2708        [fAddingTransfers release];
2709        fAddingTransfers = nil;
2710    }
2711}
2712
2713- (void) switchFilter: (id) sender
2714{
2715    [fFilterBar switchFilter: sender == fNextFilterItem];
2716}
2717
2718- (IBAction) showGlobalPopover: (id) sender
2719{
2720    if (fGlobalPopoverShown)
2721        return;
2722   
2723    NSPopover * popover = [[NSPopover alloc] init];
2724    [popover setBehavior: NSPopoverBehaviorTransient];
2725    GlobalOptionsPopoverViewController * viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle: fLib];
2726    [popover setContentViewController: viewController];
2727    [popover setDelegate: self];
2728   
2729    [popover showRelativeToRect: [sender frame] ofView: sender preferredEdge: NSMaxYEdge];
2730   
2731    [viewController release];
2732    [popover release];
2733}
2734
2735//don't show multiple popovers when clicking the gear button repeatedly
2736- (void) popoverWillShow: (NSNotification *) notification
2737{
2738    fGlobalPopoverShown = YES;
2739}
2740
2741- (void) popoverWillClose: (NSNotification *) notification
2742{
2743    fGlobalPopoverShown = NO;
2744}
2745
2746- (void) menuNeedsUpdate: (NSMenu *) menu
2747{
2748    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2749    {
2750        for (NSInteger i = [menu numberOfItems]-1; i >= 0; i--)
2751            [menu removeItemAtIndex: i];
2752       
2753        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2754       
2755        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2756        for (NSInteger i = 0; i < groupMenuCount; i++)
2757        {
2758            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2759            [groupMenu removeItemAtIndex: 0];
2760            [menu addItem: item];
2761            [item release];
2762        }
2763    }
2764    else if (menu == fShareMenu || menu == fShareContextMenu) {
2765        [menu removeAllItems];
2766       
2767        for (NSMenuItem * item in [[ShareTorrentFileHelper sharedHelper] menuItems])
2768        {
2769            [menu addItem:item];
2770        }
2771    }
2772    else;
2773}
2774
2775- (void) setGroup: (id) sender
2776{
2777    for (Torrent * torrent in [fTableView selectedTorrents])
2778    {
2779        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2780       
2781        [torrent setGroupValue: [(NSMenuItem *)sender tag] determinationType: TorrentDeterminationUserSpecified];
2782    }
2783   
2784    [self applyFilter];
2785    [self updateUI];
2786    [self updateTorrentHistory];
2787}
2788
2789- (void) toggleSpeedLimit: (id) sender
2790{
2791    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2792    [self speedLimitChanged: sender];
2793}
2794
2795- (void) speedLimitChanged: (id) sender
2796{
2797    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2798    [fStatusBar updateSpeedFieldsToolTips];
2799}
2800
2801//dict has been retained
2802- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2803{
2804    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2805
2806    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2807    [fStatusBar updateSpeedFieldsToolTips];
2808   
2809    if (![[dict objectForKey: @"ByUser"] boolValue])
2810        [GrowlApplicationBridge notifyWithTitle: isLimited ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title") : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2811                                    description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2812                               notificationName: GROWL_AUTO_SPEED_LIMIT
2813                                       iconData: nil
2814                                       priority: 0
2815                                       isSticky: NO
2816                                   clickContext: nil
2817                                     identifier: GROWL_AUTO_SPEED_LIMIT];
2818   
2819    [dict release];
2820}
2821
2822- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2823{
2824    fSoundPlaying = NO;
2825}
2826
2827-(void) VDKQueue: (VDKQueue *) queue receivedNotification: (NSString*) notification forPath: (NSString*) fpath
2828{
2829    //don't assume that just because we're watching for write notification, we'll only receive write notifications
2830   
2831    if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2832        return;
2833   
2834    if ([fAutoImportTimer isValid])
2835        [fAutoImportTimer invalidate];
2836    [fAutoImportTimer release];
2837   
2838    //check again in 10 seconds in case torrent file wasn't complete
2839    fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2840        selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2841   
2842    [self checkAutoImportDirectory];
2843}
2844
2845- (void) changeAutoImport
2846{
2847    if ([fAutoImportTimer isValid])
2848        [fAutoImportTimer invalidate];
2849    [fAutoImportTimer release];
2850    fAutoImportTimer = nil;
2851   
2852    [fAutoImportedNames release];
2853    fAutoImportedNames = nil;
2854   
2855    [self checkAutoImportDirectory];
2856}
2857
2858- (void) checkAutoImportDirectory
2859{
2860    NSString * path;
2861    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2862        return;
2863   
2864    path = [path stringByExpandingTildeInPath];
2865   
2866    NSArray * importedNames;
2867    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2868        return;
2869   
2870    //only check files that have not been checked yet
2871    NSMutableArray * newNames = [importedNames mutableCopy];
2872   
2873    if (fAutoImportedNames)
2874        [newNames removeObjectsInArray: fAutoImportedNames];
2875    else
2876        fAutoImportedNames = [[NSMutableArray alloc] init];
2877    [fAutoImportedNames setArray: importedNames];
2878   
2879    for (NSString * file in newNames)
2880    {
2881        if ([file hasPrefix: @"."])
2882            continue;
2883       
2884        NSString * fullFile = [path stringByAppendingPathComponent: file];
2885       
2886        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2887                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2888            continue;
2889       
2890        tr_ctor * ctor = tr_ctorNew(fLib);
2891        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2892       
2893        switch (tr_torrentParse(ctor, NULL))
2894        {
2895            case TR_PARSE_OK:
2896                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2897               
2898                NSString * notificationTitle = NSLocalizedString(@"Torrent File Auto Added", "notification title");
2899                if ([NSApp isOnMountainLionOrBetter])
2900                {
2901                    NSUserNotification* notification = [[NSUserNotificationMtLion alloc] init];
2902                    [notification setTitle: notificationTitle];
2903                    [notification setInformativeText: file];
2904                   
2905                    [notification setHasActionButton: NO];
2906                   
2907                    [[NSUserNotificationCenterMtLion defaultUserNotificationCenter] deliverNotification: notification];
2908                    [notification release];
2909                }
2910               
2911                [GrowlApplicationBridge notifyWithTitle: notificationTitle
2912                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2913                    clickContext: nil];
2914                break;
2915           
2916            case TR_PARSE_ERR:
2917                [fAutoImportedNames removeObject: file];
2918                break;
2919           
2920            case TR_PARSE_DUPLICATE: //let's ignore this (but silence a warning)
2921                break;
2922        }
2923       
2924        tr_ctorFree(ctor);
2925    }
2926   
2927    [newNames release];
2928}
2929
2930- (void) beginCreateFile: (NSNotification *) notification
2931{
2932    if (![fDefaults boolForKey: @"AutoImport"])
2933        return;
2934   
2935    NSString * location = [(NSURL *)[notification object] path],
2936            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2937   
2938    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2939                                    isEqualToString: [path stringByExpandingTildeInPath]])
2940        [fAutoImportedNames addObject: [location lastPathComponent]];
2941}
2942
2943- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2944{
2945    if (item)
2946        return [[item torrents] count];
2947    else
2948        return [fDisplayedTorrents count];
2949}
2950
2951- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2952{
2953    if (item)
2954        return [[item torrents] objectAtIndex: index];
2955    else
2956        return [fDisplayedTorrents objectAtIndex: index];
2957}
2958
2959- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2960{
2961    return ![item isKindOfClass: [Torrent class]];
2962}
2963
2964- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2965{
2966    if ([item isKindOfClass: [Torrent class]]) {
2967        if (tableColumn)
2968            return nil;
2969        return [item hashString];
2970    }
2971    else
2972    {
2973        NSString * ident = [tableColumn identifier];
2974        if ([ident isEqualToString: @"Group"])
2975        {
2976            NSInteger group = [item groupIndex];
2977            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2978                                : NSLocalizedString(@"No Group", "Group table row");
2979        }
2980        else if ([ident isEqualToString: @"Color"])
2981        {
2982            NSInteger group = [item groupIndex];
2983            return [[GroupsController groups] imageForIndex: group];
2984        }
2985        else if ([ident isEqualToString: @"DL Image"])
2986            return [NSImage imageNamed: @"DownArrowGroupTemplate"];
2987        else if ([ident isEqualToString: @"UL Image"])
2988            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2989                                        ? @"YingYangGroupTemplate" : @"UpArrowGroupTemplate"];
2990        else
2991        {
2992            TorrentGroup * group = (TorrentGroup *)item;
2993           
2994            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2995                return [NSString stringForRatio: [group ratio]];
2996            else
2997            {
2998                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2999                return [NSString stringForSpeed: rate];
3000            }
3001        }
3002    }
3003}
3004
3005- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
3006{
3007    //only allow reordering of rows if sorting by order
3008    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
3009    {
3010        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
3011        for (id torrent in items)
3012        {
3013            if (![torrent isKindOfClass: [Torrent class]])
3014                return NO;
3015           
3016            [indexSet addIndex: [fTableView rowForItem: torrent]];
3017        }
3018       
3019        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
3020        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
3021        return YES;
3022    }
3023    return NO;
3024}
3025
3026- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
3027    proposedChildIndex: (NSInteger) index
3028{
3029    NSPasteboard * pasteboard = [info draggingPasteboard];
3030    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
3031    {
3032        if ([fDefaults boolForKey: @"SortByGroup"])
3033        {
3034            if (!item)
3035                return NSDragOperationNone;
3036           
3037            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
3038            {
3039                if ([item isKindOfClass: [Torrent class]])
3040                {
3041                    TorrentGroup * group = [fTableView parentForItem: item];
3042                    index = [[group torrents] indexOfObject: item] + 1;
3043                    item = group;
3044                }
3045            }
3046            else
3047            {
3048                if ([item isKindOfClass: [Torrent class]])
3049                    item = [fTableView parentForItem: item];
3050                index = NSOutlineViewDropOnItemIndex;
3051            }
3052        }
3053        else
3054        {
3055            if (index == NSOutlineViewDropOnItemIndex)
3056                return NSDragOperationNone;
3057           
3058            if (item)
3059            {
3060                index = [fTableView rowForItem: item] + 1;
3061                item = nil;
3062            }
3063        }
3064       
3065        [fTableView setDropItem: item dropChildIndex: index];
3066        return NSDragOperationGeneric;
3067    }
3068   
3069    return NSDragOperationNone;
3070}
3071
3072- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item childIndex: (NSInteger) newRow
3073{
3074    NSPasteboard * pasteboard = [info draggingPasteboard];
3075    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
3076    {
3077        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
3078       
3079        //get the torrents to move
3080        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
3081        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
3082        {
3083            Torrent * torrent = [fTableView itemAtRow: i];
3084            [movingTorrents addObject: torrent];
3085           
3086            //change groups
3087            if (item)
3088                [torrent setGroupValue: [item groupIndex] determinationType: TorrentDeterminationUserSpecified];
3089        }
3090       
3091        //reorder queue order
3092        if (newRow != NSOutlineViewDropOnItemIndex)
3093        {
3094            //find torrent to place under
3095            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
3096            Torrent * topTorrent = nil;
3097            for (NSInteger i = newRow-1; i >= 0; i--)
3098            {
3099                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
3100                if (![movingTorrents containsObject: tempTorrent])
3101                {
3102                    topTorrent = tempTorrent;
3103                    break;
3104                }
3105            }
3106           
3107            //remove objects to reinsert
3108            [fTorrents removeObjectsInArray: movingTorrents];
3109           
3110            //insert objects at new location
3111            const NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
3112            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
3113            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
3114           
3115            //we need to make sure the queue order is updated in the Torrent object before we sort - safest to just reset all queue positions
3116            NSUInteger i = 0;
3117            for (Torrent * torrent in fTorrents)
3118            {
3119                [torrent setQueuePosition: i++];
3120                [torrent update];
3121            }
3122           
3123            //do the drag animation here so that the dragged torrents are the ones that are animated as moving, and not the torrents around them
3124            [fTableView beginUpdates];
3125           
3126            NSUInteger insertDisplayIndex = topTorrent ? [groupTorrents indexOfObject: topTorrent] + 1 : 0;
3127           
3128            for (Torrent * torrent in movingTorrents)
3129            {
3130                TorrentGroup * oldParent = item ? [fTableView parentForItem: torrent] : nil;
3131                NSMutableArray * oldTorrents = oldParent ? [oldParent torrents] : fDisplayedTorrents;
3132                const NSUInteger oldIndex = [oldTorrents indexOfObject: torrent];
3133               
3134                if (item == oldParent)
3135                {
3136                    if (oldIndex < insertDisplayIndex)
3137                        --insertDisplayIndex;
3138                    [oldTorrents moveObjectAtIndex: oldIndex toIndex: insertDisplayIndex];
3139                }
3140                else
3141                {
3142                    NSAssert(item && oldParent, @"Expected to be dragging between group rows");
3143                   
3144                    NSMutableArray * newTorrents = [(TorrentGroup *)item torrents];
3145                    [newTorrents insertObject: torrent atIndex: insertDisplayIndex];
3146                    [oldTorrents removeObjectAtIndex: oldIndex];
3147                }
3148
3149                [fTableView moveItemAtIndex: oldIndex inParent: oldParent toIndex: insertDisplayIndex inParent: item];
3150               
3151                ++insertDisplayIndex;
3152            }
3153
3154            [fTableView endUpdates];
3155        }
3156       
3157        [self applyFilter];
3158    }
3159   
3160    return YES;
3161}
3162
3163- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
3164{
3165    [self resetInfo];
3166    [[fWindow toolbar] validateVisibleItems];
3167}
3168
3169- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
3170{
3171    NSPasteboard * pasteboard = [info draggingPasteboard];
3172    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
3173    {
3174        //check if any torrent files can be added
3175        BOOL torrent = NO;
3176        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
3177        for (NSString * file in files)
3178        {
3179            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
3180                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
3181            {
3182                torrent = YES;
3183                tr_ctor * ctor = tr_ctorNew(fLib);
3184                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
3185                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
3186                {
3187                    if (!fOverlayWindow)
3188                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
3189                    [fOverlayWindow setTorrents: files];
3190                   
3191                    return NSDragOperationCopy;
3192                }
3193                tr_ctorFree(ctor);
3194            }
3195        }
3196       
3197        //create a torrent file if a single file
3198        if (!torrent && [files count] == 1)
3199        {
3200            if (!fOverlayWindow)
3201                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
3202            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
3203           
3204            return NSDragOperationCopy;
3205        }
3206    }
3207    else if ([[pasteboard types] containsObject: NSURLPboardType])
3208    {
3209        if (!fOverlayWindow)
3210            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
3211        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
3212       
3213        return NSDragOperationCopy;
3214    }
3215    else;
3216   
3217    return NSDragOperationNone;
3218}
3219
3220- (void) draggingExited: (id <NSDraggingInfo>) info
3221{
3222    if (fOverlayWindow)
3223        [fOverlayWindow fadeOut];
3224}
3225
3226- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
3227{
3228    if (fOverlayWindow)
3229        [fOverlayWindow fadeOut];
3230   
3231    NSPasteboard * pasteboard = [info draggingPasteboard];
3232    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
3233    {
3234        BOOL torrent = NO, accept = YES;
3235       
3236        //create an array of files that can be opened
3237        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
3238        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
3239        for (NSString * file in files)
3240        {
3241            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
3242                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
3243            {
3244                torrent = YES;
3245                tr_ctor * ctor = tr_ctorNew(fLib);
3246                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
3247                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
3248                    [filesToOpen addObject: file];
3249                tr_ctorFree(ctor);
3250            }
3251        }
3252       
3253        if ([filesToOpen count] > 0)
3254            [self application: NSApp openFiles: filesToOpen];
3255        else
3256        {
3257            if (!torrent && [files count] == 1)
3258                [CreatorWindowController createTorrentFile: fLib forFile: [NSURL fileURLWithPath: [files objectAtIndex: 0]]];
3259            else
3260                accept = NO;
3261        }
3262       
3263        return accept;
3264    }
3265    else if ([[pasteboard types] containsObject: NSURLPboardType])
3266    {
3267        NSURL * url;
3268        if ((url = [NSURL URLFromPasteboard: pasteboard]))
3269        {
3270            [self openURL: [url absoluteString]];
3271            return YES;
3272        }
3273    }
3274    else;
3275   
3276    return NO;
3277}
3278
3279- (void) toggleSmallView: (id) sender
3280{
3281    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
3282    [fDefaults setBool: makeSmall forKey: @"SmallView"];
3283   
3284    [fTableView setUsesAlternatingRowBackgroundColors: !makeSmall];
3285   
3286    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
3287
3288    [fTableView beginUpdates];
3289    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
3290    [fTableView endUpdates];
3291   
3292    //resize for larger min height if not set to auto size
3293    if (![fDefaults boolForKey: @"AutoSize"])
3294    {
3295        const NSSize contentSize = [[fWindow contentView] frame].size;
3296       
3297        NSSize contentMinSize = [fWindow contentMinSize];
3298        contentMinSize.height = [self minWindowContentSizeAllowed];
3299        [fWindow setContentMinSize: contentMinSize];
3300       
3301        //make sure the window already isn't too small
3302        if (!makeSmall && contentSize.height < contentMinSize.height)
3303        {
3304            NSRect frame = [fWindow frame];
3305            CGFloat heightChange = contentMinSize.height - contentSize.height;
3306            frame.size.height += heightChange;
3307            frame.origin.y -= heightChange;
3308           
3309            [fWindow setFrame: frame display: YES];
3310        }
3311    }
3312    else
3313        [self setWindowSizeToFit];
3314}
3315
3316- (void) togglePiecesBar: (id) sender
3317{
3318    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
3319    [fTableView togglePiecesBar];
3320}
3321
3322- (void) toggleAvailabilityBar: (id) sender
3323{
3324    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
3325    [fTableView display];
3326}
3327
3328- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
3329{
3330    NSScrollView * scrollView = [fTableView enclosingScrollView];
3331   
3332    //convert pixels to points
3333    NSRect windowFrame = [fWindow frame];
3334    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
3335    windowSize.height += height;
3336   
3337    if (check)
3338    {
3339        //we can't call minSize, since it might be set to the current size (auto size)
3340        const CGFloat minHeight = [self minWindowContentSizeAllowed]
3341                                    + (NSHeight([fWindow frame]) - NSHeight([[fWindow contentView] frame])); //contentView to window
3342       
3343        if (windowSize.height <= minHeight)
3344            windowSize.height = minHeight;
3345        else
3346        {
3347            NSScreen * screen = [fWindow screen];
3348            if (screen)
3349            {
3350                NSSize maxSize = [scrollView convertSize: [screen visibleFrame].size fromView: nil];
3351                if (!fStatusBar)
3352                    maxSize.height -= STATUS_BAR_HEIGHT;
3353                if (!fFilterBar)
3354                    maxSize.height -= FILTER_BAR_HEIGHT;
3355                if (windowSize.height > maxSize.height)
3356                    windowSize.height = maxSize.height;
3357            }
3358        }
3359    }
3360
3361    //convert points to pixels
3362    windowSize = [scrollView convertSize: windowSize toView: nil];
3363
3364    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
3365    windowFrame.size.height = windowSize.height;
3366    return windowFrame;
3367}
3368
3369- (void) toggleStatusBar: (id) sender
3370{
3371    const BOOL show = fStatusBar == nil;
3372    [self showStatusBar: show animate: YES];
3373    [fDefaults setBool: show forKey: @"StatusBar"];
3374}
3375
3376//doesn't save shown state
3377- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
3378{
3379    const BOOL prevShown = fStatusBar != nil;
3380    if (show == prevShown)
3381        return;
3382   
3383    if (show)
3384    {
3385        fStatusBar = [[StatusBarController alloc] initWithLib: fLib];
3386       
3387        NSView * contentView = [fWindow contentView];
3388        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
3389       
3390        NSRect statusBarFrame = [[fStatusBar view] frame];
3391        statusBarFrame.size.width = windowSize.width;
3392        [[fStatusBar view] setFrame: statusBarFrame];
3393       
3394        [contentView addSubview: [fStatusBar view]];
3395        [[fStatusBar view] setFrameOrigin: NSMakePoint(0.0, NSMaxY([contentView frame]))];
3396    }
3397   
3398    CGFloat heightChange = [[fStatusBar view] frame].size.height;
3399    if (!show)
3400        heightChange *= -1;
3401   
3402    //allow bar to show even if not enough room
3403    if (show && ![fDefaults boolForKey: @"AutoSize"])
3404    {
3405        NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3406       
3407        NSScreen * screen = [fWindow screen];
3408        if (screen)
3409        {
3410            CGFloat change = [screen visibleFrame].size.height - frame.size.height;
3411            if (change < 0.0)
3412            {
3413                frame = [fWindow frame];
3414                frame.size.height += change;
3415                frame.origin.y -= change;
3416                [fWindow setFrame: frame display: NO animate: NO];
3417            }
3418        }
3419    }
3420   
3421    [self updateUI];
3422   
3423    NSScrollView * scrollView = [fTableView enclosingScrollView];
3424   
3425    //set views to not autoresize
3426    const NSUInteger statsMask = [[fStatusBar view] autoresizingMask];
3427    [[fStatusBar view] setAutoresizingMask: NSViewNotSizable];
3428    NSUInteger filterMask;
3429    if (fFilterBar)
3430    {
3431        filterMask = [[fFilterBar view] autoresizingMask];
3432        [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
3433    }
3434    const NSUInteger scrollMask = [scrollView autoresizingMask];
3435    [scrollView setAutoresizingMask: NSViewNotSizable];
3436   
3437    NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3438    [fWindow setFrame: frame display: YES animate: animate];
3439   
3440    //re-enable autoresize
3441    [[fStatusBar view] setAutoresizingMask: statsMask];
3442    if (fFilterBar)
3443        [[fFilterBar view] setAutoresizingMask: filterMask];
3444    [scrollView setAutoresizingMask: scrollMask];
3445   
3446    if (!show)
3447    {
3448        [[fStatusBar view] removeFromSuperviewWithoutNeedingDisplay];
3449        [fStatusBar release];
3450        fStatusBar = nil;
3451    }
3452   
3453    if ([fDefaults boolForKey: @"AutoSize"])
3454        [self setWindowMinMaxToCurrent];
3455    else
3456    {
3457        //change min size
3458        NSSize minSize = [fWindow contentMinSize];
3459        minSize.height += heightChange;
3460        [fWindow setContentMinSize: minSize];
3461    }
3462}
3463
3464- (void) toggleFilterBar: (id) sender
3465{
3466    const BOOL show = fFilterBar == nil;
3467   
3468    //disable filtering when hiding (have to do before showFilterBar:animate:)
3469    if (!show)
3470        [fFilterBar reset: NO];
3471   
3472    [self showFilterBar: show animate: YES];
3473    [fDefaults setBool: show forKey: @"FilterBar"];
3474    [[fWindow toolbar] validateVisibleItems];
3475   
3476    [self applyFilter]; //do even if showing to ensure tooltips are updated
3477}
3478
3479//doesn't save shown state
3480- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3481{
3482    const BOOL prevShown = fFilterBar != nil;
3483    if (show == prevShown)
3484        return;
3485   
3486    if (show)
3487    {
3488        fFilterBar = [[FilterBarController alloc] init];
3489       
3490        NSView * contentView = [fWindow contentView];
3491        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
3492       
3493        NSRect filterBarFrame = [[fFilterBar view] frame];
3494        filterBarFrame.size.width = windowSize.width;
3495        [[fFilterBar view] setFrame: filterBarFrame];
3496       
3497        if (fStatusBar)
3498            [contentView addSubview: [fFilterBar view] positioned: NSWindowBelow relativeTo: [fStatusBar view]];
3499        else
3500            [contentView addSubview: [fFilterBar view]];
3501        const CGFloat originY = fStatusBar ? NSMinY([[fStatusBar view] frame]) : NSMaxY([contentView frame]);
3502        [[fFilterBar view] setFrameOrigin: NSMakePoint(0.0, originY)];
3503    }
3504    else
3505        [fWindow makeFirstResponder: fTableView];
3506   
3507    CGFloat heightChange = NSHeight([[fFilterBar view] frame]);
3508    if (!show)
3509        heightChange *= -1;
3510   
3511    //allow bar to show even if not enough room
3512    if (show && ![fDefaults boolForKey: @"AutoSize"])
3513    {
3514        NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3515       
3516        NSScreen * screen = [fWindow screen];
3517        if (screen)
3518        {
3519            CGFloat change = [screen visibleFrame].size.height - frame.size.height;
3520            if (change < 0.0)
3521            {
3522                frame = [fWindow frame];
3523                frame.size.height += change;
3524                frame.origin.y -= change;
3525                [fWindow setFrame: frame display: NO animate: NO];
3526            }
3527        }
3528    }
3529   
3530    NSScrollView * scrollView = [fTableView enclosingScrollView];
3531
3532    //set views to not autoresize
3533    const NSUInteger filterMask = [[fFilterBar view] autoresizingMask];
3534    const NSUInteger scrollMask = [scrollView autoresizingMask];
3535    [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
3536    [scrollView setAutoresizingMask: NSViewNotSizable];
3537   
3538    const NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3539    [fWindow setFrame: frame display: YES animate: animate];
3540   
3541    //re-enable autoresize
3542    [[fFilterBar view] setAutoresizingMask: filterMask];
3543    [scrollView setAutoresizingMask: scrollMask];
3544   
3545    if (!show)
3546    {
3547        [[fFilterBar view] removeFromSuperviewWithoutNeedingDisplay];
3548        [fFilterBar release];
3549        fFilterBar = nil;
3550    }
3551   
3552    if ([fDefaults boolForKey: @"AutoSize"])
3553        [self setWindowMinMaxToCurrent];
3554    else
3555    {
3556        //change min size
3557        NSSize minSize = [fWindow contentMinSize];
3558        minSize.height += heightChange;
3559        [fWindow setContentMinSize: minSize];
3560    }
3561}
3562
3563- (void) focusFilterField
3564{
3565    if (!fFilterBar)
3566        [self toggleFilterBar: self];
3567    [fFilterBar focusSearchField];
3568}
3569
3570- (BOOL) acceptsPreviewPanelControl: (QLPreviewPanel *) panel
3571{
3572    return !fQuitting;
3573}
3574
3575- (void) beginPreviewPanelControl: (QLPreviewPanel *) panel
3576{
3577    fPreviewPanel = [panel retain];
3578    [fPreviewPanel setDelegate: self];
3579    [fPreviewPanel setDataSource: self];
3580}
3581
3582- (void) endPreviewPanelControl: (QLPreviewPanel *) panel
3583{
3584    [fPreviewPanel release];
3585    fPreviewPanel = nil;
3586}
3587
3588- (NSArray *) quickLookableTorrents
3589{
3590    NSArray * selectedTorrents = [fTableView selectedTorrents];
3591    NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3592   
3593    for (Torrent * torrent in selectedTorrents)
3594        if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation])
3595            [qlArray addObject: torrent];
3596   
3597    return qlArray;
3598}
3599
3600- (NSInteger) numberOfPreviewItemsInPreviewPanel: (QLPreviewPanel *) panel
3601{
3602    if ([fInfoController canQuickLook])
3603        return [[fInfoController quickLookURLs] count];
3604    else
3605        return [[self quickLookableTorrents] count];
3606}
3607
3608- (id <QLPreviewItem>) previewPanel: (QLPreviewPanel *) panel previewItemAtIndex: (NSInteger) index
3609{
3610    if ([fInfoController canQuickLook])
3611        return [[fInfoController quickLookURLs] objectAtIndex: index];
3612    else
3613        return [[self quickLookableTorrents] objectAtIndex: index];
3614}
3615
3616- (BOOL) previewPanel: (QLPreviewPanel *) panel handleEvent: (NSEvent *) event
3617{
3618    /*if ([event type] == NSKeyDown)
3619    {
3620        [super keyDown: event];
3621        return YES;
3622    }*/
3623   
3624    return NO;
3625}
3626
3627- (NSRect) previewPanel: (QLPreviewPanel *) panel sourceFrameOnScreenForPreviewItem: (id <QLPreviewItem>) item
3628{
3629    if ([fInfoController canQuickLook])
3630        return [fInfoController quickLookSourceFrameForPreviewItem: item];
3631    else
3632    {
3633        if (![fWindow isVisible])
3634            return NSZeroRect;
3635       
3636        const NSInteger row = [fTableView rowForItem: item];
3637        if (row == -1)
3638            return NSZeroRect;
3639       
3640        NSRect frame = [fTableView iconRectForRow: row];
3641       
3642        if (!NSIntersectsRect([fTableView visibleRect], frame))
3643            return NSZeroRect;
3644       
3645        frame.origin = [fTableView convertPoint: frame.origin toView: nil];
3646        frame.origin = [fWindow convertBaseToScreen: frame.origin];
3647        frame.origin.y -= frame.size.height;
3648        return frame;
3649    }
3650}
3651
3652- (void) showToolbarShare: (id) sender
3653{
3654    NSParameterAssert([sender isKindOfClass:[NSButton class]]);
3655   
3656    NSSharingServicePicker * picker = [[NSSharingServicePicker alloc] initWithItems: [[ShareTorrentFileHelper sharedHelper] shareTorrentURLs]];
3657    picker.delegate = self;
3658   
3659    [picker showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMinYEdge];
3660}
3661
3662- (id<NSSharingServiceDelegate>)sharingServicePicker:(NSSharingServicePicker *)sharingServicePicker delegateForSharingService:(NSSharingService *)sharingService
3663{
3664    return self;
3665}
3666
3667- (NSWindow *)sharingService:(NSSharingService *)sharingService sourceWindowForShareItems:(NSArray *)items sharingContentScope:(NSSharingContentScope *)sharingContentScope
3668{
3669    return fWindow;
3670}
3671
3672- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3673{
3674    return [self toolbarButtonWithIdentifier: ident forToolbarButtonClass: [ButtonToolbarItem class]];
3675}
3676
3677- (id) toolbarButtonWithIdentifier: (NSString *) ident forToolbarButtonClass:(Class)class
3678{
3679    ButtonToolbarItem * item = [[class alloc] initWithItemIdentifier: ident];
3680   
3681    NSButton * button = [[NSButton alloc] init];
3682    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3683    [button setStringValue: @""];
3684   
3685    [item setView: button];
3686    [button release];
3687   
3688    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3689    [item setMinSize: buttonSize];
3690    [item setMaxSize: buttonSize];
3691   
3692    return [item autorelease];
3693}
3694
3695- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3696{
3697    if ([ident isEqualToString: TOOLBAR_CREATE])
3698    {
3699        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3700       
3701        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3702        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3703        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3704        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate"]];
3705        [item setTarget: self];
3706        [item setAction: @selector(createFile:)];
3707        [item setAutovalidates: NO];
3708       
3709        return item;
3710    }
3711    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3712    {
3713        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3714       
3715        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3716        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3717        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3718        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate"]];
3719        [item setTarget: self];
3720        [item setAction: @selector(openShowSheet:)];
3721        [item setAutovalidates: NO];
3722       
3723        return item;
3724    }
3725    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3726    {
3727        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3728       
3729        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3730        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3731        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3732        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate"]];
3733        [item setTarget: self];
3734        [item setAction: @selector(openURLShowSheet:)];
3735        [item setAutovalidates: NO];
3736       
3737        return item;
3738    }
3739    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3740    {
3741        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3742       
3743        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3744        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3745        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3746        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate"]];
3747        [item setTarget: self];
3748        [item setAction: @selector(removeNoDelete:)];
3749        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3750       
3751        return item;
3752    }
3753    else if ([ident isEqualToString: TOOLBAR_INFO])
3754    {
3755        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3756        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3757       
3758        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3759        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3760        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3761        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate"]];
3762        [item setTarget: self];
3763        [item setAction: @selector(showInfo:)];
3764       
3765        return item;
3766    }
3767    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3768    {
3769        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3770       
3771        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3772        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3773        [groupItem setView: segmentedControl];
3774        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3775       
3776        if ([NSApp isOnYosemiteOrBetter]) {
3777            segmentedControl.segmentStyle = NSSegmentStyleSeparated;
3778        }
3779       
3780        [segmentedControl setSegmentCount: 2];
3781        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3782       
3783        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3784        [groupItem setMinSize: groupSize];
3785        [groupItem setMaxSize: groupSize];
3786       
3787        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3788        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3789        [groupItem setTarget: self];
3790        [groupItem setAction: @selector(allToolbarClicked:)];
3791       
3792        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3793       
3794        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3795        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate"] forSegment: TOOLBAR_PAUSE_TAG];
3796        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3797                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3798       
3799        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3800        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate"] forSegment: TOOLBAR_RESUME_TAG];
3801        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3802                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3803       
3804        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3805                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3806       
3807        [segmentedControl release];
3808       
3809        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3810       
3811        return [groupItem autorelease];
3812    }
3813    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3814    {
3815        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3816       
3817        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3818        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3819        [groupItem setView: segmentedControl];
3820        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3821       
3822        if ([NSApp isOnYosemiteOrBetter]) {
3823            segmentedControl.segmentStyle = NSSegmentStyleSeparated;
3824        }
3825       
3826        [segmentedControl setSegmentCount: 2];
3827        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3828       
3829        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3830        [groupItem setMinSize: groupSize];
3831        [groupItem setMaxSize: groupSize];
3832       
3833        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3834        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3835        [groupItem setTarget: self];
3836        [groupItem setAction: @selector(selectedToolbarClicked:)];
3837       
3838        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3839       
3840        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3841        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate"] forSegment: TOOLBAR_PAUSE_TAG];
3842        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3843                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3844       
3845        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3846        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate"] forSegment: TOOLBAR_RESUME_TAG];
3847        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3848                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3849       
3850        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3851                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3852       
3853        [segmentedControl release];
3854       
3855        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3856       
3857        return [groupItem autorelease];
3858    }
3859    else if ([ident isEqualToString: TOOLBAR_FILTER])
3860    {
3861        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3862        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3863       
3864        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3865        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3866        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3867        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate"]];
3868        [item setTarget: self];
3869        [item setAction: @selector(toggleFilterBar:)];
3870       
3871        return item;
3872    }
3873    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3874    {
3875        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3876        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3877       
3878        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3879        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3880        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3881        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3882        [item setTarget: self];
3883        [item setAction: @selector(toggleQuickLook:)];
3884        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow];
3885       
3886        return item;
3887    }
3888    else if ([ident isEqualToString: TOOLBAR_SHARE])
3889    {
3890        ShareToolbarItem * item = [self toolbarButtonWithIdentifier: ident forToolbarButtonClass: [ShareToolbarItem class]];
3891       
3892        [item setLabel: NSLocalizedString(@"Share", "Share toolbar item -> label")];
3893        [item setPaletteLabel: NSLocalizedString(@"Share", "Share toolbar item -> palette label")];
3894        [item setToolTip: NSLocalizedString(@"Share torrent file", "Share toolbar item -> tooltip")];
3895        [item setImage: [NSImage imageNamed: NSImageNameShareTemplate]];
3896        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow];
3897       
3898        NSButton *itemButton = (NSButton *)[item view];
3899        [itemButton setTarget: self];
3900        [itemButton setAction: @selector(showToolbarShare:)];
3901        [itemButton sendActionOn:NSLeftMouseDownMask];
3902       
3903        return item;
3904    }
3905    else
3906        return nil;
3907}
3908
3909- (void) allToolbarClicked: (id) sender
3910{
3911    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3912                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag];
3913    switch (tagValue)
3914    {
3915        case TOOLBAR_PAUSE_TAG:
3916            [self stopAllTorrents: sender];
3917            break;
3918        case TOOLBAR_RESUME_TAG:
3919            [self resumeAllTorrents: sender];
3920            break;
3921    }
3922}
3923
3924- (void) selectedToolbarClicked: (id) sender
3925{
3926    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3927                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag];
3928    switch (tagValue)
3929    {
3930        case TOOLBAR_PAUSE_TAG:
3931            [self stopSelectedTorrents: sender];
3932            break;
3933        case TOOLBAR_RESUME_TAG:
3934            [self resumeSelectedTorrents: sender];
3935            break;
3936    }
3937}
3938
3939- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3940{
3941    NSMutableArray *items = [NSMutableArray arrayWithObjects:
3942                             TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3943                             TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3944                             TOOLBAR_SHARE, TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3945                             NSToolbarSeparatorItemIdentifier,
3946                             NSToolbarSpaceItemIdentifier,
3947                             NSToolbarFlexibleSpaceItemIdentifier,
3948                             NSToolbarCustomizeToolbarItemIdentifier, nil];
3949    if (![NSApp isOnMountainLionOrBetter]) {
3950        [items removeObject:TOOLBAR_SHARE];
3951    }
3952    return items;
3953}
3954
3955- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3956{
3957    NSMutableArray *items = [NSMutableArray arrayWithObjects:
3958                             TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSpaceItemIdentifier,
3959                             TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3960                             TOOLBAR_SHARE, TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3961    if (![NSApp isOnMountainLionOrBetter]) {
3962        [items removeObject:TOOLBAR_SHARE];
3963    }
3964    return items;
3965}
3966
3967- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3968{
3969    NSString * ident = [toolbarItem itemIdentifier];
3970   
3971    //enable remove item
3972    if ([ident isEqualToString: TOOLBAR_REMOVE])
3973        return [fTableView numberOfSelectedRows] > 0;
3974
3975    //enable pause all item
3976    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3977    {
3978        for (Torrent * torrent in fTorrents)
3979            if ([torrent isActive] || [torrent waitingToStart])
3980                return YES;
3981        return NO;
3982    }
3983
3984    //enable resume all item
3985    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3986    {
3987        for (Torrent * torrent in fTorrents)
3988            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
3989                return YES;
3990        return NO;
3991    }
3992
3993    //enable pause item
3994    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3995    {
3996        for (Torrent * torrent in [fTableView selectedTorrents])
3997            if ([torrent isActive] || [torrent waitingToStart])
3998                return YES;
3999        return NO;
4000    }
4001   
4002    //enable resume item
4003    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
4004    {
4005        for (Torrent * torrent in [fTableView selectedTorrents])
4006            if (![torrent isActive] && ![torrent waitingToStart])
4007                return YES;
4008        return NO;
4009    }
4010   
4011    //set info item
4012    if ([ident isEqualToString: TOOLBAR_INFO])
4013    {
4014        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
4015        return YES;
4016    }
4017   
4018    //set filter item
4019    if ([ident isEqualToString: TOOLBAR_FILTER])
4020    {
4021        [(NSButton *)[toolbarItem view] setState: fFilterBar != nil];
4022        return YES;
4023    }
4024   
4025    //set quick look item
4026    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
4027    {
4028        [(NSButton *)[toolbarItem view] setState: [QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]];
4029        return YES;
4030    }
4031   
4032    //enable share item
4033    if ([ident isEqualToString: TOOLBAR_SHARE])
4034        return [fTableView numberOfSelectedRows] > 0;
4035   
4036    return YES;
4037}
4038
4039- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
4040{
4041    SEL action = [menuItem action];
4042   
4043    if (action == @selector(toggleSpeedLimit:))
4044    {
4045        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
4046        return YES;
4047    }
4048   
4049    //only enable some items if it is in a context menu or the window is useable
4050    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
4051
4052    //enable open items
4053    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
4054        return [fWindow attachedSheet] == nil;
4055   
4056    //enable sort options
4057    if (action == @selector(setSort:))
4058    {
4059        NSString * sortType;
4060        switch ([menuItem tag])
4061        {
4062            case SORT_ORDER_TAG:
4063                sortType = SORT_ORDER;
4064                break;
4065            case SORT_DATE_TAG:
4066                sortType = SORT_DATE;
4067                break;
4068            case SORT_NAME_TAG:
4069                sortType = SORT_NAME;
4070                break;
4071            case SORT_PROGRESS_TAG:
4072                sortType = SORT_PROGRESS;
4073                break;
4074            case SORT_STATE_TAG:
4075                sortType = SORT_STATE;
4076                break;
4077            case SORT_TRACKER_TAG:
4078                sortType = SORT_TRACKER;
4079                break;
4080            case SORT_ACTIVITY_TAG:
4081                sortType = SORT_ACTIVITY;
4082                break;
4083            case SORT_SIZE_TAG:
4084                sortType = SORT_SIZE;
4085                break;
4086            default:
4087                NSAssert1(NO, @"Unknown sort tag received: %ld", [menuItem tag]);
4088        }
4089       
4090        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
4091        return [fWindow isVisible];
4092    }
4093   
4094    if (action == @selector(setGroup:))
4095    {
4096        BOOL checked = NO;
4097       
4098        NSInteger index = [menuItem tag];
4099        for (Torrent * torrent in [fTableView selectedTorrents])
4100            if (index == [torrent groupValue])
4101            {
4102                checked = YES;
4103                break;
4104            }
4105       
4106        [menuItem setState: checked ? NSOnState : NSOffState];
4107        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4108    }
4109   
4110    if (action == @selector(toggleSmallView:))
4111    {
4112        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
4113        return [fWindow isVisible];
4114    }
4115   
4116    if (action == @selector(togglePiecesBar:))
4117    {
4118        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
4119        return [fWindow isVisible];
4120    }
4121   
4122    if (action == @selector(toggleAvailabilityBar:))
4123    {
4124        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
4125        return [fWindow isVisible];
4126    }
4127   
4128    //enable show info
4129    if (action == @selector(showInfo:))
4130    {
4131        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
4132                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
4133        [menuItem setTitle: title];
4134
4135        return YES;
4136    }
4137   
4138    //enable prev/next inspector tab
4139    if (action == @selector(setInfoTab:))
4140        return [[fInfoController window] isVisible];
4141   
4142    //enable toggle status bar
4143    if (action == @selector(toggleStatusBar:))
4144    {
4145        NSString * title = !fStatusBar ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
4146                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
4147        [menuItem setTitle: title];
4148
4149        return [fWindow isVisible];
4150    }
4151   
4152    //enable toggle filter bar
4153    if (action == @selector(toggleFilterBar:))
4154    {
4155        NSString * title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
4156                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
4157        [menuItem setTitle: title];
4158
4159        return [fWindow isVisible];
4160    }
4161   
4162    //enable prev/next filter button
4163    if (action == @selector(switchFilter:))
4164        return [fWindow isVisible] && fFilterBar;
4165   
4166    //enable reveal in finder
4167    if (action == @selector(revealFile:))
4168        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4169   
4170    //enable renaming file/folder
4171    if (action == @selector(renameSelected:))
4172        return canUseTable && [fTableView numberOfSelectedRows] == 1;
4173
4174    //enable remove items
4175    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
4176    {
4177        BOOL warning = NO;
4178       
4179        for (Torrent * torrent in [fTableView selectedTorrents])
4180        {
4181            if ([torrent isActive])
4182            {
4183                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
4184                {
4185                    warning = YES;
4186                    break;
4187                }
4188            }
4189        }
4190   
4191        //append or remove ellipsis when needed
4192        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
4193        if (warning && [fDefaults boolForKey: @"CheckRemove"])
4194        {
4195            if (![title hasSuffix: ellipsis])
4196                [menuItem setTitle: [title stringByAppendingEllipsis]];
4197        }
4198        else
4199        {
4200            if ([title hasSuffix: ellipsis])
4201                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
4202        }
4203       
4204        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4205    }
4206   
4207    //remove all completed transfers item
4208    if (action == @selector(clearCompleted:))
4209    {
4210        //append or remove ellipsis when needed
4211        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
4212        if ([fDefaults boolForKey: @"WarningRemoveCompleted"])
4213        {
4214            if (![title hasSuffix: ellipsis])
4215                [menuItem setTitle: [title stringByAppendingEllipsis]];
4216        }
4217        else
4218        {
4219            if ([title hasSuffix: ellipsis])
4220                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
4221        }
4222       
4223        for (Torrent * torrent in fTorrents)
4224            if ([torrent isFinishedSeeding])
4225                return YES;
4226        return NO;
4227    }
4228
4229    //enable pause all item
4230    if (action == @selector(stopAllTorrents:))
4231    {
4232        for (Torrent * torrent in fTorrents)
4233            if ([torrent isActive] || [torrent waitingToStart])
4234                return YES;
4235        return NO;
4236    }
4237   
4238    //enable resume all item
4239    if (action == @selector(resumeAllTorrents:))
4240    {
4241        for (Torrent * torrent in fTorrents)
4242            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
4243                return YES;
4244        return NO;
4245    }
4246   
4247    //enable resume all waiting item
4248    if (action == @selector(resumeWaitingTorrents:))
4249    {
4250        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
4251            return NO;
4252   
4253        for (Torrent * torrent in fTorrents)
4254            if ([torrent waitingToStart])
4255                return YES;
4256        return NO;
4257    }
4258   
4259    //enable resume selected waiting item
4260    if (action == @selector(resumeSelectedTorrentsNoWait:))
4261    {
4262        if (!canUseTable)
4263            return NO;
4264       
4265        for (Torrent * torrent in [fTableView selectedTorrents])
4266            if (![torrent isActive])
4267                return YES;
4268        return NO;
4269    }
4270
4271    //enable pause item
4272    if (action == @selector(stopSelectedTorrents:))
4273    {
4274        if (!canUseTable)
4275            return NO;
4276   
4277        for (Torrent * torrent in [fTableView selectedTorrents])
4278            if ([torrent isActive] || [torrent waitingToStart])
4279                return YES;
4280        return NO;
4281    }
4282   
4283    //enable resume item
4284    if (action == @selector(resumeSelectedTorrents:))
4285    {
4286        if (!canUseTable)
4287            return NO;
4288   
4289        for (Torrent * torrent in [fTableView selectedTorrents])
4290            if (![torrent isActive] && ![torrent waitingToStart])
4291                return YES;
4292        return NO;
4293    }
4294   
4295    //enable manual announce item
4296    if (action == @selector(announceSelectedTorrents:))
4297    {
4298        if (!canUseTable)
4299            return NO;
4300       
4301        for (Torrent * torrent in [fTableView selectedTorrents])
4302            if ([torrent canManualAnnounce])
4303                return YES;
4304        return NO;
4305    }
4306   
4307    //enable reset cache item
4308    if (action == @selector(verifySelectedTorrents:))
4309    {
4310        if (!canUseTable)
4311            return NO;
4312           
4313        for (Torrent * torrent in [fTableView selectedTorrents])
4314            if (![torrent isMagnet])
4315                return YES;
4316        return NO;
4317    }
4318   
4319    //enable move torrent file item
4320    if (action == @selector(moveDataFilesSelected:))
4321        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4322   
4323    //enable copy torrent file item
4324    if (action == @selector(copyTorrentFiles:))
4325    {
4326        if (!canUseTable)
4327            return NO;
4328       
4329        for (Torrent * torrent in [fTableView selectedTorrents])
4330            if (![torrent isMagnet])
4331                return YES;
4332        return NO;
4333    }
4334   
4335    //enable copy torrent file item
4336    if (action == @selector(copyMagnetLinks:))
4337        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4338   
4339    //enable reverse sort item
4340    if (action == @selector(setSortReverse:))
4341    {
4342        const BOOL isReverse = [menuItem tag] == SORT_DESC_TAG;
4343        [menuItem setState: (isReverse == [fDefaults boolForKey: @"SortReverse"]) ? NSOnState : NSOffState];
4344        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
4345    }
4346   
4347    //enable group sort item
4348    if (action == @selector(setSortByGroup:))
4349    {
4350        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
4351        return YES;
4352    }
4353   
4354    if (action == @selector(toggleQuickLook:))
4355    {
4356        const BOOL visible =[QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible];
4357        //text consistent with Finder
4358        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
4359                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
4360        [menuItem setTitle: title];
4361       
4362        return YES;
4363    }
4364   
4365    return YES;
4366}
4367
4368- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
4369{
4370    switch (messageType)
4371    {
4372        case kIOMessageSystemWillSleep:
4373        {
4374            //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
4375            BOOL anyActive = NO;
4376            for (Torrent * torrent in fTorrents)
4377            {
4378                if ([torrent isActive])
4379                    anyActive = YES;
4380                [torrent sleep]; //have to call on all, regardless if they are active
4381            }
4382           
4383            //if there are any running transfers, wait 15 seconds for them to stop
4384            if (anyActive)
4385            {
4386                sleep(15);
4387            }
4388           
4389            IOAllowPowerChange(fRootPort, (long) messageArgument);
4390            break;
4391        }
4392
4393        case kIOMessageCanSystemSleep:
4394            if ([fDefaults boolForKey: @"SleepPrevent"])
4395            {
4396                //prevent idle sleep unless no torrents are active
4397                for (Torrent * torrent in fTorrents)
4398                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
4399                    {
4400                        IOCancelPowerChange(fRootPort, (long) messageArgument);
4401                        return;
4402                    }
4403            }
4404           
4405            IOAllowPowerChange(fRootPort, (long) messageArgument);
4406            break;
4407
4408        case kIOMessageSystemHasPoweredOn:
4409            //resume sleeping transfers after we wake up
4410            for (Torrent * torrent in fTorrents)
4411                [torrent wakeUp];
4412            break;
4413    }
4414}
4415
4416- (NSMenu *) applicationDockMenu: (NSApplication *) sender
4417{
4418    if (fQuitting)
4419        return nil;
4420   
4421    NSUInteger seeding = 0, downloading = 0;
4422    for (Torrent * torrent in fTorrents)
4423    {
4424        if ([torrent isSeeding])
4425            seeding++;
4426        else if ([torrent isActive])
4427            downloading++;
4428        else;
4429    }
4430   
4431    NSMenu * menu = [[NSMenu alloc] init];
4432   
4433    if (seeding > 0)
4434    {
4435        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
4436        [menu addItemWithTitle: title action: nil keyEquivalent: @""];
4437    }
4438   
4439    if (downloading > 0)
4440    {
4441        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
4442        [menu addItemWithTitle: title action: nil keyEquivalent: @""];
4443    }
4444   
4445    if (seeding > 0 || downloading > 0)
4446        [menu addItem: [NSMenuItem separatorItem]];
4447   
4448    [menu addItemWithTitle: NSLocalizedString(@"Pause All", "Dock item") action: @selector(stopAllTorrents:) keyEquivalent: @""];
4449    [menu addItemWithTitle: NSLocalizedString(@"Resume All", "Dock item") action: @selector(resumeAllTorrents:) keyEquivalent: @""];
4450    [menu addItem: [NSMenuItem separatorItem]];
4451    [menu addItemWithTitle: NSLocalizedString(@"Speed Limit", "Dock item") action: @selector(toggleSpeedLimit:) keyEquivalent: @""];
4452   
4453    return [menu autorelease];
4454}
4455
4456- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
4457{
4458    //if auto size is enabled, the current frame shouldn't need to change
4459    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
4460   
4461    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
4462    return frame;
4463}
4464
4465- (void) setWindowSizeToFit
4466{
4467    if ([fDefaults boolForKey: @"AutoSize"])
4468    {
4469        NSScrollView * scrollView = [fTableView enclosingScrollView];
4470       
4471        [scrollView setHasVerticalScroller: NO];
4472        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
4473        [scrollView setHasVerticalScroller: YES];
4474       
4475        [self setWindowMinMaxToCurrent];
4476    }
4477}
4478
4479- (NSRect) sizedWindowFrame
4480{
4481    NSUInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
4482                        ? [fDisplayedTorrents count] : 0;
4483   
4484    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4485                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4486                        - NSHeight([[fTableView enclosingScrollView] frame]);
4487   
4488    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4489}
4490
4491- (void) updateForAutoSize
4492{
4493    if ([fDefaults boolForKey: @"AutoSize"])
4494        [self setWindowSizeToFit];
4495    else
4496    {
4497        NSSize contentMinSize = [fWindow contentMinSize];
4498        contentMinSize.height = [self minWindowContentSizeAllowed];
4499       
4500        [fWindow setContentMinSize: contentMinSize];
4501       
4502        NSSize contentMaxSize = [fWindow contentMaxSize];
4503        contentMaxSize.height = FLT_MAX;
4504        [fWindow setContentMaxSize: contentMaxSize];
4505    }
4506}
4507
4508- (void) setWindowMinMaxToCurrent
4509{
4510    const CGFloat height = NSHeight([[fWindow contentView] frame]);
4511   
4512    NSSize minSize = [fWindow contentMinSize],
4513            maxSize = [fWindow contentMaxSize];
4514    minSize.height = height;
4515    maxSize.height = height;
4516   
4517    [fWindow setContentMinSize: minSize];
4518    [fWindow setContentMaxSize: maxSize];
4519}
4520
4521- (CGFloat) minWindowContentSizeAllowed
4522{
4523    CGFloat contentMinHeight = NSHeight([[fWindow contentView] frame]) - NSHeight([[fTableView enclosingScrollView] frame])
4524                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
4525    return contentMinHeight;
4526}
4527
4528- (void) updateForExpandCollape
4529{
4530    [self setWindowSizeToFit];
4531    [self setBottomCountText: YES];
4532}
4533
4534- (void) showMainWindow: (id) sender
4535{
4536    [fWindow makeKeyAndOrderFront: nil];
4537}
4538
4539- (void) windowDidBecomeMain: (NSNotification *) notification
4540{
4541    [fBadger clearCompleted];
4542    [self updateUI];
4543}
4544
4545- (void) applicationWillUnhide: (NSNotification *) notification
4546{
4547    [self updateUI];
4548}
4549
4550- (void) toggleQuickLook: (id) sender
4551{
4552    if ([[QLPreviewPanel sharedPreviewPanel] isVisible])
4553        [[QLPreviewPanel sharedPreviewPanel] orderOut: nil];
4554    else
4555        [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront: nil];
4556}
4557
4558- (void) linkHomepage: (id) sender
4559{
4560    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4561}
4562
4563- (void) linkForums: (id) sender
4564{
4565    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4566}
4567
4568- (void) linkTrac: (id) sender
4569{
4570    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4571}
4572
4573- (void) linkDonate: (id) sender
4574{
4575    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4576}
4577
4578- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4579{
4580    fQuitRequested = YES;
4581}
4582
4583- (NSDictionary *) registrationDictionaryForGrowl
4584{
4585    NSArray * notifications = @[GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE, GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT];
4586   
4587    return @{GROWL_NOTIFICATIONS_ALL : notifications,
4588                GROWL_NOTIFICATIONS_DEFAULT : notifications };
4589}
4590
4591- (void) growlNotificationWasClicked: (id) clickContext
4592{
4593    if (![clickContext isKindOfClass: [NSDictionary class]])
4594        return;
4595   
4596    NSString * type = [clickContext objectForKey: @"Type"], * location;
4597    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4598            && (location = [clickContext objectForKey: @"Location"]))
4599    {
4600        NSURL * file = [NSURL fileURLWithPath: location];
4601        [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4602    }
4603}
4604
4605- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4606{
4607    @autoreleasepool
4608    {
4609        //get the torrent
4610        __block Torrent * torrent = nil;
4611        if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED && type != TR_RPC_SESSION_CLOSE))
4612        {
4613            [fTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(Torrent * checkTorrent, NSUInteger idx, BOOL *stop) {
4614                if (torrentStruct == [checkTorrent torrentStruct])
4615                {
4616                    torrent = checkTorrent;
4617                    *stop = YES;
4618                }
4619            }];
4620           
4621            if (!torrent)
4622            {
4623                NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4624                return;
4625            }
4626        }
4627       
4628        dispatch_async(dispatch_get_main_queue(), ^{
4629            switch (type)
4630            {
4631                case TR_RPC_TORRENT_ADDED:
4632                    [self rpcAddTorrentStruct: torrentStruct];
4633                    break;
4634                   
4635                case TR_RPC_TORRENT_STARTED:
4636                case TR_RPC_TORRENT_STOPPED:
4637                    [self rpcStartedStoppedTorrent: torrent];
4638                    break;
4639                   
4640                case TR_RPC_TORRENT_REMOVING:
4641                    [self rpcRemoveTorrent: torrent deleteData: NO];
4642                    break;
4643                   
4644                case TR_RPC_TORRENT_TRASHING:
4645                    [self rpcRemoveTorrent: torrent deleteData: YES];
4646                    break;
4647                   
4648                case TR_RPC_TORRENT_CHANGED:
4649                    [self rpcChangedTorrent: torrent];
4650                    break;
4651                   
4652                case TR_RPC_TORRENT_MOVED:
4653                    [self rpcMovedTorrent: torrent];
4654                    break;
4655                   
4656                case TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED:
4657                    [self rpcUpdateQueue];
4658                    break;
4659                   
4660                case TR_RPC_SESSION_CHANGED:
4661                    [fPrefsController rpcUpdatePrefs];
4662                    break;
4663                   
4664                case TR_RPC_SESSION_CLOSE:
4665                    fQuitRequested = YES;
4666                    [NSApp terminate: self];
4667                    break;
4668                   
4669                default:
4670                    NSAssert1(NO, @"Unknown RPC command received: %d", type);
4671            }
4672        });
4673    }
4674}
4675
4676- (void) rpcAddTorrentStruct: (struct tr_torrent *) torrentStruct
4677{
4678    NSString * location = nil;
4679    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4680        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4681   
4682    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4683   
4684    //change the location if the group calls for it (this has to wait until after the torrent is created)
4685    if ([[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
4686    {
4687        location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
4688        [torrent changeDownloadFolderBeforeUsing: location determinationType: TorrentDeterminationAutomatic];
4689    }
4690   
4691    [torrent update];
4692    [fTorrents addObject: torrent];
4693    [torrent release];
4694   
4695    if (!fAddingTransfers)
4696        fAddingTransfers = [[NSMutableSet alloc] init];
4697    [fAddingTransfers addObject: torrent];
4698   
4699    [self fullUpdateUI];
4700}
4701
4702- (void) rpcRemoveTorrent: (Torrent *) torrent deleteData: (BOOL) deleteData
4703{
4704    [self confirmRemoveTorrents: @[ torrent ] deleteData: deleteData];
4705}
4706
4707- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4708{
4709    [torrent update];
4710   
4711    [self updateUI];
4712    [self applyFilter];
4713    [self updateTorrentHistory];
4714}
4715
4716- (void) rpcChangedTorrent: (Torrent *) torrent
4717{
4718    [torrent update];
4719   
4720    if ([[fTableView selectedTorrents] containsObject: torrent])
4721    {
4722        [fInfoController updateInfoStats]; //this will reload the file table
4723        [fInfoController updateOptions];
4724    }
4725}
4726
4727- (void) rpcMovedTorrent: (Torrent *) torrent
4728{
4729    [torrent update];
4730    [torrent updateTimeMachineExclude];
4731   
4732    if ([[fTableView selectedTorrents] containsObject: torrent])
4733        [fInfoController updateInfoStats];
4734}
4735
4736- (void) rpcUpdateQueue
4737{
4738    for (Torrent * torrent in fTorrents)
4739        [torrent update];
4740   
4741    NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: YES];
4742    NSArray * descriptors = [NSArray arrayWithObject: descriptor];
4743    [fTorrents sortUsingDescriptors: descriptors];
4744   
4745    [self sortTorrents: YES];
4746}
4747
4748@end
Note: See TracBrowser for help on using the repository browser.