source: trunk/macosx/Controller.m @ 13562

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

comment out a debug log statement

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