source: trunk/macosx/Controller.m @ 13187

Last change on this file since 13187 was 13187, checked in by livings124, 10 years ago

remove redundant code in Torrent's canChangeDownloadCheckForFile:, and enumerate of the files in canChangeDownloadCheckForFiles: concurrently.

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