source: trunk/macosx/Controller.m @ 14044

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

r14044 Use OSAtomicIncrement32(&value) instead of OSAtomicAdd32(1, &value)

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