source: trunk/macosx/Controller.m @ 13828

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

#1220 Initial Mac support for changing file and folder names. Not fully complete.

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