source: trunk/macosx/Controller.m @ 13603

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

experimental fix for #5106

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