source: trunk/macosx/Controller.m @ 13831

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

use the new rename function for the torrent, instead of the per-file function; update the interface right away when renaming the torrent

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