source: trunk/macosx/Controller.m @ 13804

Last change on this file since 13804 was 13804, checked in by livings124, 9 years ago

#5223 Use VDKQueue for watching for torrent files

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