source: trunk/macosx/Controller.m @ 13622

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

#5106 Work around for crash when seeding completes and the transfer is auto-removed.

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