source: trunk/macosx/Controller.m @ 13254

Last change on this file since 13254 was 13254, checked in by livings124, 5 years ago

more changes to make future porting to ARC easier

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