source: trunk/macosx/Controller.m @ 13309

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

#4912 Filter and check all/uncheck all in Add Transfer window

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