source: trunk/macosx/Controller.m @ 13611

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

#5121 Stopped torrents resume after sleep automatically.

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