source: trunk/macosx/Controller.m @ 13488

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

#4874 Deleting multiple torrents from the WebUI fails

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