source: trunk/macosx/Controller.m @ 13253

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

re-add non-ARC-specific changes from r13248-50, mainly to make re-adding ARC support easier in the future

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