source: trunk/macosx/Controller.m @ 13315

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

remove unused code

  • Property svn:keywords set to Date Rev Author Id
File size: 178.1 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 13315 2012-05-23 00:54:58Z 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;
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    }
1773   
1774    if (![NSApp isHidden])
1775    {
1776        if ([fWindow isVisible])
1777        {
1778            [self sortTorrents: NO];
1779           
1780            [fStatusBar updateWithDownload: dlRate upload: ulRate];
1781           
1782            [fClearCompletedButton setHidden: !anyCompleted];
1783        }
1784
1785        //update non-constant parts of info window
1786        if ([[fInfoController window] isVisible])
1787            [fInfoController updateInfoStats];
1788    }
1789   
1790    //badge dock
1791    [fBadger updateBadgeWithDownload: dlRate upload: ulRate];
1792}
1793
1794#warning can this be removed or refined?
1795- (void) fullUpdateUI
1796{
1797    [self updateUI];
1798    [self applyFilter];
1799    [[fWindow toolbar] validateVisibleItems];
1800    [self updateTorrentHistory];
1801}
1802
1803- (void) setBottomCountText: (BOOL) filtering
1804{
1805    NSString * totalTorrentsString;
1806    NSUInteger totalCount = [fTorrents count];
1807    if (totalCount != 1)
1808        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Status bar transfer count"),
1809                                [NSString formattedUInteger: totalCount]];
1810    else
1811        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1812   
1813    if (filtering)
1814    {
1815        NSUInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1816        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1817            count -= [fDisplayedTorrents count];
1818       
1819        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Status bar transfer count"),
1820                                [NSString formattedUInteger: count], totalTorrentsString];
1821    }
1822   
1823    [fTotalTorrentsField setStringValue: totalTorrentsString];
1824}
1825
1826- (void) torrentFinishedDownloading: (NSNotification *) notification
1827{
1828    Torrent * torrent = [notification object];
1829   
1830    if ([[[notification userInfo] objectForKey: @"WasRunning"] boolValue])
1831    {
1832        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1833        {
1834            NSSound * sound;
1835            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1836            {
1837                [sound setDelegate: self];
1838                fSoundPlaying = YES;
1839                [sound play];
1840            }
1841        }
1842       
1843        NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_DOWNLOAD_COMPLETE forKey: @"Type"];
1844       
1845        NSString * location = [torrent dataLocation];
1846        if (location)
1847            [clickContext setObject: location forKey: @"Location"];
1848       
1849        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1850                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1851                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1852       
1853        if (![fWindow isMainWindow])
1854            [fBadger addCompletedTorrent: torrent];
1855       
1856        //bounce download stack
1857        [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"com.apple.DownloadFileFinished"
1858            object: [torrent dataLocation]];
1859    }
1860   
1861    [self fullUpdateUI];
1862}
1863
1864- (void) torrentRestartedDownloading: (NSNotification *) notification
1865{
1866    [self fullUpdateUI];
1867}
1868
1869- (void) torrentFinishedSeeding: (NSNotification *) notification
1870{
1871    Torrent * torrent = [notification object];
1872   
1873    [self fullUpdateUI];
1874   
1875    if ([[fTableView selectedTorrents] containsObject: torrent])
1876    {
1877        [fInfoController updateInfoStats];
1878        [fInfoController updateOptions];
1879    }
1880   
1881    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1882    {
1883        NSSound * sound;
1884        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1885        {
1886            [sound setDelegate: self];
1887            fSoundPlaying = YES;
1888            [sound play];
1889        }
1890    }
1891   
1892    NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_SEEDING_COMPLETE forKey: @"Type"];
1893   
1894    NSString * location = [torrent dataLocation];
1895    if (location)
1896        [clickContext setObject: location forKey: @"Location"];
1897   
1898    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1899                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1900                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1901}
1902
1903- (void) updateTorrentHistory
1904{
1905    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1906   
1907    for (Torrent * torrent in fTorrents)
1908        [history addObject: [torrent history]];
1909   
1910    NSString * historyFile = [fConfigDirectory stringByAppendingPathComponent: TRANSFER_PLIST];
1911    [history writeToFile: historyFile atomically: YES];
1912}
1913
1914- (void) setSort: (id) sender
1915{
1916    NSString * sortType;
1917    switch ([(NSMenuItem *)sender tag])
1918    {
1919        case SORT_ORDER_TAG:
1920            sortType = SORT_ORDER;
1921            [fDefaults setBool: NO forKey: @"SortReverse"];
1922            break;
1923        case SORT_DATE_TAG:
1924            sortType = SORT_DATE;
1925            break;
1926        case SORT_NAME_TAG:
1927            sortType = SORT_NAME;
1928            break;
1929        case SORT_PROGRESS_TAG:
1930            sortType = SORT_PROGRESS;
1931            break;
1932        case SORT_STATE_TAG:
1933            sortType = SORT_STATE;
1934            break;
1935        case SORT_TRACKER_TAG:
1936            sortType = SORT_TRACKER;
1937            break;
1938        case SORT_ACTIVITY_TAG:
1939            sortType = SORT_ACTIVITY;
1940            break;
1941        case SORT_SIZE_TAG:
1942            sortType = SORT_SIZE;
1943            break;
1944        default:
1945            NSAssert1(NO, @"Unknown sort tag received: %d", [(NSMenuItem *)sender tag]);
1946            return;
1947    }
1948   
1949    [fDefaults setObject: sortType forKey: @"Sort"];
1950   
1951    [self sortTorrents: YES];
1952}
1953
1954- (void) setSortByGroup: (id) sender
1955{
1956    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1957    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1958   
1959    [self applyFilter];
1960}
1961
1962- (void) setSortReverse: (id) sender
1963{
1964    const BOOL setReverse = [(NSMenuItem *)sender tag] == SORT_DESC_TAG;
1965    if (setReverse != [fDefaults boolForKey: @"SortReverse"])
1966    {
1967        [fDefaults setBool: setReverse forKey: @"SortReverse"];
1968        [self sortTorrents: NO];
1969    }
1970}
1971
1972- (void) sortTorrents: (BOOL) includeQueueOrder
1973{
1974    const BOOL onLion = [NSApp isOnLionOrBetter];
1975   
1976    NSArray * selectedValues;
1977    if (!onLion)
1978        selectedValues = [fTableView selectedValues];
1979   
1980    //actually sort
1981    [self sortTorrentsCallUpdates: YES includeQueueOrder: includeQueueOrder];
1982   
1983    if (!onLion)
1984        [fTableView selectValues: selectedValues];
1985   
1986    [fTableView setNeedsDisplay: YES];
1987}
1988
1989- (void) sortTorrentsCallUpdates: (BOOL) callUpdates includeQueueOrder: (BOOL) includeQueueOrder
1990{
1991    const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1992   
1993    NSArray * descriptors;
1994    NSSortDescriptor * nameDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: asc selector: @selector(localizedStandardCompare:)];
1995   
1996    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1997    if ([sortType isEqualToString: SORT_STATE])
1998    {
1999        NSSortDescriptor * stateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"stateSortKey" ascending: !asc],
2000                        * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: !asc],
2001                        * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: !asc];
2002       
2003        descriptors = [NSArray arrayWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor, nameDescriptor, nil];
2004    }
2005    else if ([sortType isEqualToString: SORT_PROGRESS])
2006    {
2007        NSSortDescriptor * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: asc],
2008                        * ratioProgressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progressStopRatio" ascending: asc],
2009                        * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: asc];
2010       
2011        descriptors = [NSArray arrayWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor, nameDescriptor, nil];
2012    }
2013    else if ([sortType isEqualToString: SORT_TRACKER])
2014    {
2015        NSSortDescriptor * trackerDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"trackerSortKey" ascending: asc selector: @selector(localizedCaseInsensitiveCompare:)];
2016       
2017        descriptors = [NSArray arrayWithObjects: trackerDescriptor, nameDescriptor, nil];
2018    }
2019    else if ([sortType isEqualToString: SORT_ACTIVITY])
2020    {
2021        NSSortDescriptor * rateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"totalRate" ascending: !asc];
2022        NSSortDescriptor * activityDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateActivityOrAdd" ascending: !asc];
2023       
2024        descriptors = [NSArray arrayWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
2025    }
2026    else if ([sortType isEqualToString: SORT_DATE])
2027    {
2028        NSSortDescriptor * dateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateAdded" ascending: asc];
2029       
2030        descriptors = [NSArray arrayWithObjects: dateDescriptor, nameDescriptor, nil];
2031    }
2032    else if ([sortType isEqualToString: SORT_SIZE])
2033    {
2034        NSSortDescriptor * sizeDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"size" ascending: asc];
2035       
2036        descriptors = [NSArray arrayWithObjects: sizeDescriptor, nameDescriptor, nil];
2037    }
2038    else if ([sortType isEqualToString: SORT_NAME])
2039    {
2040        descriptors = [NSArray arrayWithObject: nameDescriptor];
2041    }
2042    else
2043    {
2044        NSAssert1([sortType isEqualToString: SORT_ORDER], @"Unknown sort type received: %@", sortType);
2045       
2046        if (!includeQueueOrder)
2047            return;
2048       
2049        NSSortDescriptor * orderDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: asc];
2050       
2051        descriptors = [NSArray arrayWithObject: orderDescriptor];
2052    }
2053   
2054    BOOL beganTableUpdate = !callUpdates || ![NSApp isOnLionOrBetter];
2055   
2056    //actually sort
2057    if ([fDefaults boolForKey: @"SortByGroup"])
2058    {
2059        for (TorrentGroup * group in fDisplayedTorrents)
2060            [self rearrangeTorrentTableArray: [group torrents] forParent: group withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate];
2061    }
2062    else
2063        [self rearrangeTorrentTableArray: fDisplayedTorrents forParent: nil withSortDescriptors: descriptors beganTableUpdate: &beganTableUpdate];
2064   
2065    if (beganTableUpdate && callUpdates)
2066    {
2067        if ([NSApp isOnLionOrBetter])
2068            [fTableView endUpdates];
2069        else
2070            [fTableView reloadData];
2071    }
2072}
2073
2074#warning redo so that we search a copy once again (best explained by changing sorting from ascending to descending)
2075- (void) rearrangeTorrentTableArray: (NSMutableArray *) rearrangeArray forParent: parent withSortDescriptors: (NSArray *) descriptors beganTableUpdate: (BOOL *) beganTableUpdate
2076{
2077    for (NSUInteger currentIndex = 1; currentIndex < [rearrangeArray count]; ++currentIndex)
2078    {
2079        //manually do the sorting in-place
2080        const NSUInteger insertIndex = [rearrangeArray indexOfObject: [rearrangeArray objectAtIndex: currentIndex] inSortedRange: NSMakeRange(0, currentIndex) options: (NSBinarySearchingInsertionIndex | NSBinarySearchingLastEqual) usingComparator: ^(id obj1, id obj2) {
2081            for (NSSortDescriptor * descriptor in descriptors)
2082            {
2083                const NSComparisonResult result = [descriptor compareObject: obj1 toObject: obj2];
2084                if (result != NSOrderedSame)
2085                    return result;
2086            }
2087           
2088            return NSOrderedSame;
2089        }];
2090       
2091        if (insertIndex != currentIndex)
2092        {
2093            if (!*beganTableUpdate)
2094            {
2095                *beganTableUpdate = YES;
2096                if ([NSApp isOnLionOrBetter])
2097                    [fTableView beginUpdates];
2098            }
2099           
2100            [rearrangeArray moveObjectAtIndex: currentIndex toIndex: insertIndex];
2101            if ([NSApp isOnLionOrBetter])
2102                [fTableView moveItemAtIndex: currentIndex inParent: parent toIndex: insertIndex inParent: parent];
2103        }
2104    }
2105   
2106    NSAssert2([rearrangeArray isEqualToArray: [rearrangeArray sortedArrayUsingDescriptors: descriptors]], @"Torrent rearranging didn't work! %@ %@", rearrangeArray, [rearrangeArray sortedArrayUsingDescriptors: descriptors]);
2107}
2108
2109- (void) applyFilter
2110{
2111    const BOOL onLion = [NSApp isOnLionOrBetter];
2112   
2113    NSArray * selectedValuesSL = nil;
2114    if (!onLion)
2115        selectedValuesSL = [fTableView selectedValues];
2116   
2117    __block NSUInteger active = 0, downloading = 0, seeding = 0, paused = 0;
2118    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2119    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
2120    if ([filterType isEqualToString: FILTER_ACTIVE])
2121        filterActive = YES;
2122    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2123        filterDownload = YES;
2124    else if ([filterType isEqualToString: FILTER_SEED])
2125        filterSeed = YES;
2126    else if ([filterType isEqualToString: FILTER_PAUSE])
2127        filterPause = YES;
2128    else
2129        filterStatus = NO;
2130   
2131    const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
2132    const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
2133   
2134    NSArray * searchStrings = [fFilterBar searchStrings];
2135    if (searchStrings && [searchStrings count] == 0)
2136        searchStrings = nil;
2137    const BOOL filterTracker = searchStrings && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
2138   
2139    //filter & get counts of each type
2140    NSIndexSet * indexesOfNonFilteredTorrents = [fTorrents indexesOfObjectsWithOptions: NSEnumerationConcurrent passingTest: ^BOOL(Torrent * torrent, NSUInteger idx, BOOL * stop) {
2141        //check status
2142        if ([torrent isActive] && ![torrent isCheckingWaiting])
2143        {
2144            const BOOL isActive = ![torrent isStalled];
2145            if (isActive)
2146                ++active;
2147           
2148            if ([torrent isSeeding])
2149            {
2150                ++seeding;
2151                if (filterStatus && !((filterActive && isActive) || filterSeed))
2152                    return NO;
2153            }
2154            else
2155            {
2156                ++downloading;
2157                if (filterStatus && !((filterActive && isActive) || filterDownload))
2158                    return NO;
2159            }
2160        }
2161        else
2162        {
2163            ++paused;
2164            if (filterStatus && !filterPause)
2165                return NO;
2166        }
2167       
2168        //checkGroup
2169        if (filterGroup)
2170            if ([torrent groupValue] != groupFilterValue)
2171                return NO;
2172       
2173        //check text field
2174        if (searchStrings)
2175        {
2176            __block BOOL removeTextField = NO;
2177            if (filterTracker)
2178            {
2179                NSArray * trackers = [torrent allTrackersFlat];
2180               
2181                //to count, we need each string in at least 1 tracker
2182                [searchStrings enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id searchString, NSUInteger idx, BOOL * stop) {
2183                    __block BOOL found = NO;
2184                    [trackers enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id tracker, NSUInteger idx, BOOL * stopTracker) {
2185                        if ([tracker rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound)
2186                        {
2187                            found = YES;
2188                            *stopTracker = YES;
2189                        }
2190                    }];
2191                    if (!found)
2192                    {
2193                        removeTextField = YES;
2194                        *stop = YES;
2195                    }
2196                }];
2197            }
2198            else
2199            {
2200                [searchStrings enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id searchString, NSUInteger idx, BOOL * stop) {
2201                    if ([[torrent name] rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound)
2202                    {
2203                        removeTextField = YES;
2204                        *stop = YES;
2205                    }
2206                }];
2207            }
2208           
2209            if (removeTextField)
2210                return NO;
2211        }
2212       
2213        return YES;
2214    }];
2215   
2216    NSArray * allTorrents = [fTorrents objectsAtIndexes: indexesOfNonFilteredTorrents];
2217   
2218    //set button tooltips
2219    if (fFilterBar)
2220        [fFilterBar setCountAll: [fTorrents count] active: active downloading: downloading seeding: seeding paused: paused];
2221   
2222    //if either the previous or current lists are blank, set its value to the other
2223    const BOOL groupRows = [allTorrents count] > 0 ? [fDefaults boolForKey: @"SortByGroup"] : ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]]);
2224    const BOOL wasGroupRows = [fDisplayedTorrents count] > 0 ? [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]] : groupRows;
2225   
2226    #warning could probably be merged with later code somehow
2227    //clear display cache for not-shown torrents
2228    if ([fDisplayedTorrents count] > 0)
2229    {
2230        //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
2231        void (^removePreviousFinishedPieces)(id, NSUInteger, BOOL *) = ^(Torrent * torrent, NSUInteger idx, BOOL * stop) {
2232            //we used to keep track of which torrents we already found in allTorrents, but it wasn't safe fo concurrent enumeration
2233            if (![allTorrents containsObject: torrent])
2234                [torrent setPreviousFinishedPieces: nil];
2235        };
2236       
2237        if (wasGroupRows)
2238            [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger idx, BOOL * stop) {
2239                [[(TorrentGroup *)obj torrents] enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces];
2240            }];
2241        else
2242            [fDisplayedTorrents enumerateObjectsWithOptions: NSEnumerationConcurrent usingBlock: removePreviousFinishedPieces];
2243    }
2244   
2245    BOOL beganUpdates = NO;
2246   
2247    if (onLion)
2248    {
2249        //don't animate torrents when first launching
2250        static dispatch_once_t onceToken;
2251        dispatch_once(&onceToken, ^{
2252            [[NSAnimationContext currentContext] setDuration: 0];
2253        });
2254        [NSAnimationContext beginGrouping];
2255    }
2256   
2257    //add/remove torrents (and rearrange for groups), one by one
2258    if (!groupRows && !wasGroupRows)
2259    {
2260        NSMutableIndexSet * addIndexes = [NSMutableIndexSet indexSet],
2261                        * removePreviousIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])];
2262       
2263        //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)
2264        [allTorrents enumerateObjectsWithOptions: 0 usingBlock: ^(id objAll, NSUInteger previousIndex, BOOL * stop) {
2265            const NSUInteger currentIndex = [fDisplayedTorrents indexOfObjectAtIndexes: removePreviousIndexes options: NSEnumerationConcurrent passingTest: ^(id objDisplay, NSUInteger idx, BOOL *stop) {
2266                return (BOOL)(objAll == objDisplay);
2267            }];
2268            if (currentIndex == NSNotFound)
2269                [addIndexes addIndex: previousIndex];
2270            else
2271                [removePreviousIndexes removeIndex: currentIndex];
2272        }];
2273       
2274        if ([addIndexes count] > 0 || [removePreviousIndexes count] > 0)
2275        {
2276            beganUpdates = YES;
2277            if (onLion)
2278                [fTableView beginUpdates];
2279           
2280            //remove torrents we didn't find
2281            if ([removePreviousIndexes count] > 0)
2282            {
2283                [fDisplayedTorrents removeObjectsAtIndexes: removePreviousIndexes];
2284                if (onLion)
2285                    [fTableView removeItemsAtIndexes: removePreviousIndexes inParent: nil withAnimation: NSTableViewAnimationSlideDown];
2286            }
2287           
2288            //add new torrents
2289            if ([addIndexes count] > 0)
2290            {
2291                //slide new torrents in differently
2292                if (fAddingTransfers)
2293                {
2294                    NSIndexSet * newAddIndexes = [allTorrents indexesOfObjectsAtIndexes: addIndexes options: NSEnumerationConcurrent passingTest: ^BOOL(id obj, NSUInteger idx, BOOL * stop) {
2295                        return [fAddingTransfers containsObject: obj];
2296                    }];
2297                   
2298                    [addIndexes removeIndexes: newAddIndexes];
2299                   
2300                    [fDisplayedTorrents addObjectsFromArray: [allTorrents objectsAtIndexes: newAddIndexes]];
2301                    if (onLion)
2302                        [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange([fDisplayedTorrents count] - [newAddIndexes count], [newAddIndexes count])] inParent: nil withAnimation: NSTableViewAnimationSlideLeft];
2303                }
2304               
2305                [fDisplayedTorrents addObjectsFromArray: [allTorrents objectsAtIndexes: addIndexes]];
2306                if (onLion)
2307                    [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange([fDisplayedTorrents count] - [addIndexes count], [addIndexes count])] inParent: nil withAnimation: NSTableViewAnimationSlideDown];
2308            }
2309        }
2310    }
2311    else if (groupRows && wasGroupRows)
2312    {
2313        NSAssert(groupRows && wasGroupRows, @"Should have had group rows and should remain with group rows");
2314       
2315        #warning don't always do?
2316        beganUpdates = YES;
2317        if (onLion)
2318            [fTableView beginUpdates];
2319       
2320        NSMutableIndexSet * unusedAllTorrentsIndexes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [allTorrents count])];
2321       
2322        NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: [fDisplayedTorrents count]];
2323        for (TorrentGroup * group in fDisplayedTorrents)
2324            [groupsByIndex setObject: group forKey: [NSNumber numberWithInteger: [group groupIndex]]];
2325       
2326        const NSUInteger originalGroupCount = [fDisplayedTorrents count];
2327        for (NSUInteger index = 0; index < originalGroupCount; ++index)
2328        {
2329            TorrentGroup * group = [fDisplayedTorrents objectAtIndex: index];
2330           
2331            NSMutableIndexSet * removeIndexes = [NSMutableIndexSet indexSet];
2332           
2333            //needs to be a signed integer
2334            for (NSInteger indexInGroup = 0; indexInGroup < [[group torrents] count]; ++indexInGroup)
2335            {
2336                Torrent * torrent = [[group torrents] objectAtIndex: indexInGroup];
2337                const NSUInteger allIndex = [allTorrents indexOfObjectAtIndexes: unusedAllTorrentsIndexes options: NSEnumerationConcurrent passingTest: ^(id obj, NSUInteger idx, BOOL * stop) {
2338                    return (BOOL)(obj == torrent);
2339                }];
2340                if (allIndex == NSNotFound)
2341                    [removeIndexes addIndex: indexInGroup];
2342                else
2343                {
2344                    BOOL markTorrentAsUsed = YES;
2345                   
2346                    const NSInteger groupValue = [torrent groupValue];
2347                    if (groupValue != [group groupIndex])
2348                    {
2349                        TorrentGroup * newGroup = [groupsByIndex objectForKey: [NSNumber numberWithInteger: groupValue]];
2350                        if (!newGroup)
2351                        {
2352                            newGroup = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2353                            [groupsByIndex setObject: newGroup forKey: [NSNumber numberWithInteger: groupValue]];
2354                            [fDisplayedTorrents addObject: newGroup];
2355                           
2356                            if (onLion)
2357                            {
2358                                [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [fDisplayedTorrents count]-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2359                                [fTableView isGroupCollapsed: groupValue] ? [fTableView collapseItem: newGroup] : [fTableView expandItem: newGroup];
2360                            }
2361                        }
2362                        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
2363                        {
2364                            //ugggh, but shouldn't happen too often
2365                            if ([fDisplayedTorrents indexOfObject: newGroup inRange: NSMakeRange(index+1, originalGroupCount-(index+1))] != NSNotFound)
2366                                markTorrentAsUsed = NO;
2367                        }
2368                       
2369                        [[group torrents] removeObjectAtIndex: indexInGroup];
2370                        [[newGroup torrents] addObject: torrent];
2371                       
2372                        if (onLion)
2373                            [fTableView moveItemAtIndex: indexInGroup inParent: group toIndex: [[newGroup torrents] count]-1 inParent: newGroup];
2374                       
2375                        --indexInGroup;
2376                    }
2377                   
2378                    if (markTorrentAsUsed)
2379                        [unusedAllTorrentsIndexes removeIndex: allIndex];
2380                }
2381            }
2382           
2383            if ([removeIndexes count] > 0)
2384            {
2385                [[group torrents] removeObjectsAtIndexes: removeIndexes];
2386                if (onLion)
2387                    [fTableView removeItemsAtIndexes: removeIndexes inParent: group withAnimation: NSTableViewAnimationEffectFade];
2388            }
2389        }
2390       
2391        //add remaining new torrents
2392        for (Torrent * torrent in [allTorrents objectsAtIndexes: unusedAllTorrentsIndexes])
2393        {
2394            const NSInteger groupValue = [torrent groupValue];
2395            TorrentGroup * group = [groupsByIndex objectForKey: [NSNumber numberWithInteger: groupValue]];
2396            if (!group)
2397            {
2398                group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2399                [groupsByIndex setObject: group forKey: [NSNumber numberWithInteger: groupValue]];
2400                [fDisplayedTorrents addObject: group];
2401               
2402                if (onLion)
2403                {
2404                    [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [fDisplayedTorrents count]-1] inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2405                    [fTableView isGroupCollapsed: groupValue] ? [fTableView collapseItem: group] : [fTableView expandItem: group];
2406                }
2407            }
2408           
2409            [[group torrents] addObject: torrent];
2410            if (onLion)
2411            {
2412                const BOOL newTorrent = fAddingTransfers && [fAddingTransfers containsObject: torrent];
2413                [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndex: [[group torrents] count]-1] inParent: group withAnimation: newTorrent ? NSTableViewAnimationSlideLeft : NSTableViewAnimationSlideDown];
2414            }
2415        }
2416       
2417        //remove empty groups
2418        NSIndexSet * removeGroupIndexes = [fDisplayedTorrents indexesOfObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, originalGroupCount)] options: NSEnumerationConcurrent passingTest: ^BOOL(id obj, NSUInteger idx, BOOL * stop) {
2419            return [[(TorrentGroup *)obj torrents] count] == 0;
2420        }];
2421       
2422        if ([removeGroupIndexes count] > 0)
2423        {
2424            [fDisplayedTorrents removeObjectsAtIndexes: removeGroupIndexes];
2425            if (onLion)
2426                [fTableView removeItemsAtIndexes: removeGroupIndexes inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2427        }
2428       
2429        //now that all groups are there, sort them - don't insert on the fly in case groups were reordered in prefs
2430        NSSortDescriptor * groupDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"groupOrderValue" ascending: YES];
2431        [self rearrangeTorrentTableArray: fDisplayedTorrents forParent: nil withSortDescriptors: [NSArray arrayWithObject: groupDescriptor] beganTableUpdate: &beganUpdates];
2432    }
2433    else
2434    {
2435        NSAssert(groupRows != wasGroupRows, @"Trying toggling group-torrent reordering when we weren't expecting to.");
2436       
2437        //set all groups as expanded
2438        [fTableView removeAllCollapsedGroups];
2439       
2440        //since we're not doing this the right way (boo buggy animation), we need to remember selected values
2441        #warning when Lion-only and using views instead of cells, this likely won't be needed
2442        NSArray * selectedValues = [fTableView selectedValues];
2443       
2444        beganUpdates = YES;
2445        if (onLion)
2446            [fTableView beginUpdates];
2447       
2448        if (onLion)
2449            [fTableView removeItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])] inParent: nil withAnimation: NSTableViewAnimationSlideDown];
2450       
2451        if (groupRows)
2452        {
2453            //a map for quickly finding groups
2454            NSMutableDictionary * groupsByIndex = [NSMutableDictionary dictionaryWithCapacity: [[GroupsController groups] numberOfGroups]];
2455            for (Torrent * torrent in allTorrents)
2456            {
2457                const NSInteger groupValue = [torrent groupValue];
2458                TorrentGroup * group = [groupsByIndex objectForKey: [NSNumber numberWithInteger: groupValue]];
2459                if (!group)
2460                {
2461                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2462                    [groupsByIndex setObject: group forKey: [NSNumber numberWithInteger: groupValue]];
2463                }
2464               
2465                [[group torrents] addObject: torrent];
2466            }
2467           
2468            [fDisplayedTorrents setArray: [groupsByIndex allValues]];
2469           
2470            //we need the groups to be sorted, and we can do it without moving items in the table, too!
2471            NSSortDescriptor * groupDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"groupOrderValue" ascending: YES];
2472            [fDisplayedTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2473        }
2474        else
2475            [fDisplayedTorrents setArray: allTorrents];
2476       
2477        if (onLion)
2478            [fTableView insertItemsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fDisplayedTorrents count])] inParent: nil withAnimation: NSTableViewAnimationEffectFade];
2479       
2480        if (groupRows)
2481        {
2482            //actually expand group rows
2483            for (TorrentGroup * group in fDisplayedTorrents)
2484                [fTableView expandItem: group];
2485        }
2486       
2487        if (selectedValues)
2488            [fTableView selectValues: selectedValues];
2489    }
2490   
2491    //sort the torrents (won't sort the groups, though)
2492    [self sortTorrentsCallUpdates: !beganUpdates includeQueueOrder: YES];
2493   
2494    if (onLion)
2495    {
2496        if (beganUpdates)
2497            [fTableView endUpdates];
2498        [fTableView setNeedsDisplay: YES];
2499       
2500        [NSAnimationContext endGrouping];
2501    }
2502    else
2503    {
2504        [fTableView reloadData];
2505       
2506        if (groupRows)
2507        {
2508            for (TorrentGroup * group in fDisplayedTorrents)
2509            {
2510                if ([fTableView isGroupCollapsed: [group groupIndex]])
2511                    [fTableView collapseItem: group];
2512                else
2513                    [fTableView expandItem: group];
2514            }
2515        }
2516    }
2517   
2518    if (!onLion)
2519        [fTableView selectValues: selectedValuesSL];
2520   
2521    [self resetInfo]; //if group is already selected, but the torrents in it change
2522   
2523    [self setBottomCountText: groupRows || filterStatus || filterGroup || searchStrings];
2524   
2525    [self setWindowSizeToFit];
2526   
2527    if (fAddingTransfers)
2528    {
2529        [fAddingTransfers release];
2530        fAddingTransfers = nil;
2531    }
2532}
2533
2534- (void) switchFilter: (id) sender
2535{
2536    [fFilterBar switchFilter: sender == fNextFilterItem];
2537}
2538
2539- (IBAction) showGlobalPopover: (id) sender
2540{
2541    if ([NSApp isOnLionOrBetter])
2542    {
2543        if (fGlobalPopoverShown)
2544            return;
2545       
2546        NSPopover * popover = [[NSPopoverLion alloc] init];
2547        [popover setBehavior: NSPopoverBehaviorTransient];
2548        GlobalOptionsPopoverViewController * viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle: [PrefsController handle]];
2549        [popover setContentViewController: viewController];
2550        [popover setDelegate: self];
2551       
2552        [popover showRelativeToRect: [sender frame] ofView: sender preferredEdge: NSMaxYEdge];
2553       
2554        [viewController release];
2555        [popover release];
2556    }
2557    else
2558    {
2559        //place menu below button
2560        NSRect rect = [sender frame];
2561        NSPoint location = rect.origin;
2562        location.y += NSHeight(rect) + 5.0;
2563       
2564        [fActionMenu popUpMenuPositioningItem: nil atLocation: location inView: sender];
2565    }
2566}
2567
2568//don't show multiple popovers when clicking the gear button repeatedly
2569- (void) popoverWillShow: (NSNotification *) notification
2570{
2571    fGlobalPopoverShown = YES;
2572}
2573
2574- (void) popoverWillClose: (NSNotification *) notification
2575{
2576    fGlobalPopoverShown = NO;
2577}
2578
2579- (void) menuNeedsUpdate: (NSMenu *) menu
2580{
2581    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2582    {
2583        for (NSInteger i = [menu numberOfItems]-1; i >= 0; i--)
2584            [menu removeItemAtIndex: i];
2585       
2586        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2587       
2588        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2589        for (NSInteger i = 0; i < groupMenuCount; i++)
2590        {
2591            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2592            [groupMenu removeItemAtIndex: 0];
2593            [menu addItem: item];
2594            [item release];
2595        }
2596    }
2597    else if (menu == fUploadMenu || menu == fDownloadMenu)
2598    {
2599        if ([menu numberOfItems] > 3)
2600            return;
2601       
2602        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2603       
2604        NSMenuItem * item;
2605        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2606        {
2607            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2608                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2609                    keyEquivalent: @""];
2610            [item setTarget: self];
2611            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2612            [menu addItem: item];
2613            [item release];
2614        }
2615    }
2616    else if (menu == fRatioStopMenu)
2617    {
2618        if ([menu numberOfItems] > 3)
2619            return;
2620       
2621        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2622       
2623        NSMenuItem * item;
2624        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2625        {
2626            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2627                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2628            [item setTarget: self];
2629            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2630            [menu addItem: item];
2631            [item release];
2632        }
2633    }
2634    else;
2635}
2636
2637- (void) setGroup: (id) sender
2638{
2639    for (Torrent * torrent in [fTableView selectedTorrents])
2640    {
2641        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2642       
2643        [torrent setGroupValue: [(NSMenuItem *)sender tag]];
2644    }
2645   
2646    [self applyFilter];
2647    [self updateUI];
2648    [self updateTorrentHistory];
2649}
2650
2651- (void) toggleSpeedLimit: (id) sender
2652{
2653    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2654    [self speedLimitChanged: sender];
2655}
2656
2657- (void) speedLimitChanged: (id) sender
2658{
2659    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2660    [fStatusBar updateSpeedFieldsToolTips];
2661}
2662
2663//dict has been retained
2664- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2665{
2666    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2667
2668    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2669    [fStatusBar updateSpeedFieldsToolTips];
2670   
2671    if (![[dict objectForKey: @"ByUser"] boolValue])
2672        [GrowlApplicationBridge notifyWithTitle: isLimited
2673                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2674                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2675            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2676            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2677   
2678    [dict release];
2679}
2680
2681- (void) setLimitGlobalEnabled: (id) sender
2682{
2683    BOOL upload = [sender menu] == fUploadMenu;
2684    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2685   
2686    [fPrefsController applySpeedSettings: nil];
2687}
2688
2689- (void) setQuickLimitGlobal: (id) sender
2690{
2691    BOOL upload = [sender menu] == fUploadMenu;
2692    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2693    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2694   
2695    [fPrefsController updateLimitFields];
2696    [fPrefsController applySpeedSettings: nil];
2697}
2698
2699- (void) setRatioGlobalEnabled: (id) sender
2700{
2701    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2702   
2703    [fPrefsController applyRatioSetting: nil];
2704}
2705
2706- (void) setQuickRatioGlobal: (id) sender
2707{
2708    [fDefaults setBool: YES forKey: @"RatioCheck"];
2709    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2710   
2711    [fPrefsController updateRatioStopFieldOld];
2712}
2713
2714- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2715{
2716    fSoundPlaying = NO;
2717}
2718
2719- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2720{
2721    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2722    {
2723        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2724            return;
2725       
2726        if (fAutoImportTimer)
2727        {
2728            if ([fAutoImportTimer isValid])
2729                [fAutoImportTimer invalidate];
2730            [fAutoImportTimer release];
2731            fAutoImportTimer = nil;
2732        }
2733       
2734        //check again in 10 seconds in case torrent file wasn't complete
2735        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2736            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2737       
2738        [self checkAutoImportDirectory];
2739    }
2740}
2741
2742- (void) changeAutoImport
2743{
2744    if (fAutoImportTimer)
2745    {
2746        if ([fAutoImportTimer isValid])
2747            [fAutoImportTimer invalidate];
2748        [fAutoImportTimer release];
2749        fAutoImportTimer = nil;
2750    }
2751    [fAutoImportedNames release];
2752    fAutoImportedNames = nil;
2753   
2754    [self checkAutoImportDirectory];
2755}
2756
2757- (void) checkAutoImportDirectory
2758{
2759    NSString * path;
2760    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2761        return;
2762   
2763    path = [path stringByExpandingTildeInPath];
2764   
2765    NSArray * importedNames;
2766    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2767        return;
2768   
2769    //only check files that have not been checked yet
2770    NSMutableArray * newNames = [importedNames mutableCopy];
2771   
2772    if (fAutoImportedNames)
2773        [newNames removeObjectsInArray: fAutoImportedNames];
2774    else
2775        fAutoImportedNames = [[NSMutableArray alloc] init];
2776    [fAutoImportedNames setArray: importedNames];
2777   
2778    for (NSString * file in newNames)
2779    {
2780        if ([file hasPrefix: @"."])
2781            continue;
2782       
2783        NSString * fullFile = [path stringByAppendingPathComponent: file];
2784       
2785        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2786                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2787            continue;
2788       
2789        tr_ctor * ctor = tr_ctorNew(fLib);
2790        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2791       
2792        switch (tr_torrentParse(ctor, NULL))
2793        {
2794            case TR_PARSE_OK:
2795                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2796               
2797                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2798                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2799                    clickContext: nil];
2800                break;
2801           
2802            case TR_PARSE_ERR:
2803                [fAutoImportedNames removeObject: file];
2804                break;
2805           
2806            case TR_PARSE_DUPLICATE: //let's ignore this (but silence a warning)
2807                break;
2808        }
2809       
2810        tr_ctorFree(ctor);
2811    }
2812   
2813    [newNames release];
2814}
2815
2816- (void) beginCreateFile: (NSNotification *) notification
2817{
2818    if (![fDefaults boolForKey: @"AutoImport"])
2819        return;
2820   
2821    NSString * location = [notification object],
2822            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2823   
2824    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2825                                    isEqualToString: [path stringByExpandingTildeInPath]])
2826        [fAutoImportedNames addObject: [location lastPathComponent]];
2827}
2828
2829- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2830{
2831    if (item)
2832        return [[item torrents] count];
2833    else
2834        return [fDisplayedTorrents count];
2835}
2836
2837- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2838{
2839    if (item)
2840        return [[item torrents] objectAtIndex: index];
2841    else
2842        return [fDisplayedTorrents objectAtIndex: index];
2843}
2844
2845- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2846{
2847    return ![item isKindOfClass: [Torrent class]];
2848}
2849
2850- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2851{
2852    if ([item isKindOfClass: [Torrent class]]) {
2853        if (tableColumn)
2854            return nil;
2855        return [item hashString];
2856    }
2857    else
2858    {
2859        NSString * ident = [tableColumn identifier];
2860        if ([ident isEqualToString: @"Group"])
2861        {
2862            NSInteger group = [item groupIndex];
2863            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2864                                : NSLocalizedString(@"No Group", "Group table row");
2865        }
2866        else if ([ident isEqualToString: @"Color"])
2867        {
2868            NSInteger group = [item groupIndex];
2869            return [[GroupsController groups] imageForIndex: group];
2870        }
2871        else if ([ident isEqualToString: @"DL Image"])
2872            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2873        else if ([ident isEqualToString: @"UL Image"])
2874            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2875                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2876        else
2877        {
2878            TorrentGroup * group = (TorrentGroup *)item;
2879           
2880            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2881                return [NSString stringForRatio: [group ratio]];
2882            else
2883            {
2884                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2885                return [NSString stringForSpeed: rate];
2886            }
2887        }
2888    }
2889}
2890
2891- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2892{
2893    //only allow reordering of rows if sorting by order
2894    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2895    {
2896        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2897        for (id torrent in items)
2898        {
2899            if (![torrent isKindOfClass: [Torrent class]])
2900                return NO;
2901           
2902            [indexSet addIndex: [fTableView rowForItem: torrent]];
2903        }
2904       
2905        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2906        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2907        return YES;
2908    }
2909    return NO;
2910}
2911
2912- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2913    proposedChildIndex: (NSInteger) index
2914{
2915    NSPasteboard * pasteboard = [info draggingPasteboard];
2916    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2917    {
2918        if ([fDefaults boolForKey: @"SortByGroup"])
2919        {
2920            if (!item)
2921                return NSDragOperationNone;
2922           
2923            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2924            {
2925                if ([item isKindOfClass: [Torrent class]])
2926                {
2927                    TorrentGroup * group = [fTableView parentForItem: item];
2928                    index = [[group torrents] indexOfObject: item] + 1;
2929                    item = group;
2930                }
2931            }
2932            else
2933            {
2934                if ([item isKindOfClass: [Torrent class]])
2935                    item = [fTableView parentForItem: item];
2936                index = NSOutlineViewDropOnItemIndex;
2937            }
2938        }
2939        else
2940        {
2941            if (index == NSOutlineViewDropOnItemIndex)
2942                return NSDragOperationNone;
2943           
2944            if (item)
2945            {
2946                index = [fTableView rowForItem: item] + 1;
2947                item = nil;
2948            }
2949        }
2950       
2951        [fTableView setDropItem: item dropChildIndex: index];
2952        return NSDragOperationGeneric;
2953    }
2954   
2955    return NSDragOperationNone;
2956}
2957
2958- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item childIndex: (NSInteger) newRow
2959{
2960    NSPasteboard * pasteboard = [info draggingPasteboard];
2961    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2962    {
2963        //remember selected rows
2964        NSArray * selectedValues = nil;
2965        if (![NSApp isOnLionOrBetter])
2966            selectedValues = [fTableView selectedValues];
2967   
2968        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2969       
2970        //get the torrents to move
2971        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2972        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2973        {
2974            Torrent * torrent = [fTableView itemAtRow: i];
2975            [movingTorrents addObject: torrent];
2976           
2977            //change groups
2978            if (item)
2979                [torrent setGroupValue: [item groupIndex]];
2980        }
2981       
2982        //reorder queue order
2983        if (newRow != NSOutlineViewDropOnItemIndex)
2984        {
2985            //find torrent to place under
2986            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2987            Torrent * topTorrent = nil;
2988            for (NSInteger i = newRow-1; i >= 0; i--)
2989            {
2990                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2991                if (![movingTorrents containsObject: tempTorrent])
2992                {
2993                    topTorrent = tempTorrent;
2994                    break;
2995                }
2996            }
2997           
2998            //remove objects to reinsert
2999            [fTorrents removeObjectsInArray: movingTorrents];
3000           
3001            //insert objects at new location
3002            const NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
3003            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
3004            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
3005           
3006            //we need to make sure the queue order is updated in the Torrent object before we sort - safest to just reset all queue positions
3007            NSUInteger i = 0;
3008            for (Torrent * torrent in fTorrents)
3009            {
3010                [torrent setQueuePosition: i++];
3011                [torrent update];
3012            }
3013           
3014            //do the drag animation here so that the dragged torrents are the ones that are animated as moving, and not the torrents around them
3015            const BOOL onLion = [NSApp isOnLionOrBetter];
3016            if (onLion)
3017                [fTableView beginUpdates];
3018           
3019            NSUInteger insertDisplayIndex = topTorrent ? [groupTorrents indexOfObject: topTorrent] + 1 : 0;
3020           
3021            for (Torrent * torrent in movingTorrents)
3022            {
3023                TorrentGroup * oldParent = item ? [fTableView parentForItem: torrent] : nil;
3024                NSMutableArray * oldTorrents = oldParent ? [oldParent torrents] : fDisplayedTorrents;
3025                const NSUInteger oldIndex = [oldTorrents indexOfObject: torrent];
3026               
3027                if (item == oldParent)
3028                {
3029                    if (oldIndex < insertDisplayIndex)
3030                        --insertDisplayIndex;
3031                    [oldTorrents moveObjectAtIndex: oldIndex toIndex: insertDisplayIndex];
3032                }
3033                else
3034                {
3035                    NSAssert(item && oldParent, @"Expected to be dragging between group rows");
3036                   
3037                    NSMutableArray * newTorrents = [(TorrentGroup *)item torrents];
3038                    [newTorrents insertObject: torrent atIndex: insertDisplayIndex];
3039                    [oldTorrents removeObjectAtIndex: oldIndex];
3040                }
3041               
3042                if (onLion)
3043                    [fTableView moveItemAtIndex: oldIndex inParent: oldParent toIndex: insertDisplayIndex inParent: item];
3044               
3045                ++insertDisplayIndex;
3046            }
3047           
3048            if (onLion)
3049                [fTableView endUpdates];
3050        }
3051       
3052        [self applyFilter];
3053        if (selectedValues)
3054            [fTableView selectValues: selectedValues];
3055    }
3056   
3057    return YES;
3058}
3059
3060- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
3061{
3062    [self resetInfo];
3063    [[fWindow toolbar] validateVisibleItems];
3064}
3065
3066- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
3067{
3068    NSPasteboard * pasteboard = [info draggingPasteboard];
3069    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
3070    {
3071        //check if any torrent files can be added
3072        BOOL torrent = NO;
3073        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
3074        for (NSString * file in files)
3075        {
3076            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
3077                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
3078            {
3079                torrent = YES;
3080                tr_ctor * ctor = tr_ctorNew(fLib);
3081                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
3082                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
3083                {
3084                    if (!fOverlayWindow)
3085                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
3086                    [fOverlayWindow setTorrents: files];
3087                   
3088                    return NSDragOperationCopy;
3089                }
3090                tr_ctorFree(ctor);
3091            }
3092        }
3093       
3094        //create a torrent file if a single file
3095        if (!torrent && [files count] == 1)
3096        {
3097            if (!fOverlayWindow)
3098                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
3099            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
3100           
3101            return NSDragOperationCopy;
3102        }
3103    }
3104    else if ([[pasteboard types] containsObject: NSURLPboardType])
3105    {
3106        if (!fOverlayWindow)
3107            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
3108        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
3109       
3110        return NSDragOperationCopy;
3111    }
3112    else;
3113   
3114    return NSDragOperationNone;
3115}
3116
3117- (void) draggingExited: (id <NSDraggingInfo>) info
3118{
3119    if (fOverlayWindow)
3120        [fOverlayWindow fadeOut];
3121}
3122
3123- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
3124{
3125    if (fOverlayWindow)
3126        [fOverlayWindow fadeOut];
3127   
3128    NSPasteboard * pasteboard = [info draggingPasteboard];
3129    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
3130    {
3131        BOOL torrent = NO, accept = YES;
3132       
3133        //create an array of files that can be opened
3134        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
3135        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
3136        for (NSString * file in files)
3137        {
3138            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
3139                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
3140            {
3141                torrent = YES;
3142                tr_ctor * ctor = tr_ctorNew(fLib);
3143                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
3144                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
3145                    [filesToOpen addObject: file];
3146                tr_ctorFree(ctor);
3147            }
3148        }
3149       
3150        if ([filesToOpen count] > 0)
3151            [self application: NSApp openFiles: filesToOpen];
3152        else
3153        {
3154            if (!torrent && [files count] == 1)
3155                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
3156            else
3157                accept = NO;
3158        }
3159       
3160        return accept;
3161    }
3162    else if ([[pasteboard types] containsObject: NSURLPboardType])
3163    {
3164        NSURL * url;
3165        if ((url = [NSURL URLFromPasteboard: pasteboard]))
3166        {
3167            [self openURL: [url absoluteString]];
3168            return YES;
3169        }
3170    }
3171    else;
3172   
3173    return NO;
3174}
3175
3176- (void) toggleSmallView: (id) sender
3177{
3178    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
3179    [fDefaults setBool: makeSmall forKey: @"SmallView"];
3180   
3181    [fTableView setUsesAlternatingRowBackgroundColors: !makeSmall];
3182   
3183    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
3184   
3185    if ([NSApp isOnLionOrBetter])
3186        [fTableView beginUpdates];
3187    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
3188    if ([NSApp isOnLionOrBetter])
3189        [fTableView endUpdates];
3190   
3191    //resize for larger min height if not set to auto size
3192    if (![fDefaults boolForKey: @"AutoSize"])
3193    {
3194        const NSSize contentSize = [[fWindow contentView] frame].size;
3195       
3196        NSSize contentMinSize = [fWindow contentMinSize];
3197        contentMinSize.height = [self minWindowContentSizeAllowed];
3198        [fWindow setContentMinSize: contentMinSize];
3199       
3200        //make sure the window already isn't too small
3201        if (!makeSmall && contentSize.height < contentMinSize.height)
3202        {
3203            NSRect frame = [fWindow frame];
3204            CGFloat heightChange = contentMinSize.height - contentSize.height;
3205            frame.size.height += heightChange;
3206            frame.origin.y -= heightChange;
3207           
3208            [fWindow setFrame: frame display: YES];
3209        }
3210    }
3211    else
3212        [self setWindowSizeToFit];
3213}
3214
3215- (void) togglePiecesBar: (id) sender
3216{
3217    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
3218    [fTableView togglePiecesBar];
3219}
3220
3221- (void) toggleAvailabilityBar: (id) sender
3222{
3223    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
3224    [fTableView display];
3225}
3226
3227#warning elliminate when 10.7-only
3228- (void) toggleStatusString: (id) sender
3229{
3230    if ([fDefaults boolForKey: @"SmallView"])
3231        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
3232    else
3233        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
3234   
3235    [fTableView setNeedsDisplay: YES];
3236}
3237
3238- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
3239{
3240    NSScrollView * scrollView = [fTableView enclosingScrollView];
3241   
3242    //convert pixels to points
3243    NSRect windowFrame = [fWindow frame];
3244    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
3245    windowSize.height += height;
3246   
3247    if (check)
3248    {
3249        //we can't call minSize, since it might be set to the current size (auto size)
3250        const CGFloat minHeight = [self minWindowContentSizeAllowed]
3251                                    + (NSHeight([fWindow frame]) - NSHeight([[fWindow contentView] frame])); //contentView to window
3252       
3253        if (windowSize.height <= minHeight)
3254            windowSize.height = minHeight;
3255        else
3256        {
3257            NSScreen * screen = [fWindow screen];
3258            if (screen)
3259            {
3260                NSSize maxSize = [scrollView convertSize: [screen visibleFrame].size fromView: nil];
3261                if (!fStatusBar)
3262                    maxSize.height -= STATUS_BAR_HEIGHT;
3263                if (!fFilterBar)
3264                    maxSize.height -= FILTER_BAR_HEIGHT;
3265                if (windowSize.height > maxSize.height)
3266                    windowSize.height = maxSize.height;
3267            }
3268        }
3269    }
3270
3271    //convert points to pixels
3272    windowSize = [scrollView convertSize: windowSize toView: nil];
3273
3274    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
3275    windowFrame.size.height = windowSize.height;
3276    return windowFrame;
3277}
3278
3279- (void) toggleStatusBar: (id) sender
3280{
3281    const BOOL show = fStatusBar == nil;
3282    [self showStatusBar: show animate: YES];
3283    [fDefaults setBool: show forKey: @"StatusBar"];
3284}
3285
3286//doesn't save shown state
3287- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
3288{
3289    const BOOL prevShown = fStatusBar != nil;
3290    if (show == prevShown)
3291        return;
3292   
3293    if (show)
3294    {
3295        fStatusBar = [[StatusBarController alloc] initWithLib: fLib];
3296       
3297        NSView * contentView = [fWindow contentView];
3298        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
3299       
3300        NSRect statusBarFrame = [[fStatusBar view] frame];
3301        statusBarFrame.size.width = windowSize.width;
3302        [[fStatusBar view] setFrame: statusBarFrame];
3303       
3304        [contentView addSubview: [fStatusBar view]];
3305        [[fStatusBar view] setFrameOrigin: NSMakePoint(0.0, NSMaxY([contentView frame]))];
3306    }
3307   
3308    CGFloat heightChange = [[fStatusBar view] frame].size.height;
3309    if (!show)
3310        heightChange *= -1;
3311   
3312    //allow bar to show even if not enough room
3313    if (show && ![fDefaults boolForKey: @"AutoSize"])
3314    {
3315        NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3316       
3317        NSScreen * screen = [fWindow screen];
3318        if (screen)
3319        {
3320            CGFloat change = [screen visibleFrame].size.height - frame.size.height;
3321            if (change < 0.0)
3322            {
3323                frame = [fWindow frame];
3324                frame.size.height += change;
3325                frame.origin.y -= change;
3326                [fWindow setFrame: frame display: NO animate: NO];
3327            }
3328        }
3329    }
3330   
3331    [self updateUI];
3332   
3333    NSScrollView * scrollView = [fTableView enclosingScrollView];
3334   
3335    //set views to not autoresize
3336    const NSUInteger statsMask = [[fStatusBar view] autoresizingMask];
3337    [[fStatusBar view] setAutoresizingMask: NSViewNotSizable];
3338    NSUInteger filterMask;
3339    if (fFilterBar)
3340    {
3341        filterMask = [[fFilterBar view] autoresizingMask];
3342        [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
3343    }
3344    const NSUInteger scrollMask = [scrollView autoresizingMask];
3345    [scrollView setAutoresizingMask: NSViewNotSizable];
3346   
3347    NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3348    [fWindow setFrame: frame display: YES animate: animate];
3349   
3350    //re-enable autoresize
3351    [[fStatusBar view] setAutoresizingMask: statsMask];
3352    if (fFilterBar)
3353        [[fFilterBar view] setAutoresizingMask: filterMask];
3354    [scrollView setAutoresizingMask: scrollMask];
3355   
3356    if (!show)
3357    {
3358        [[fStatusBar view] removeFromSuperviewWithoutNeedingDisplay];
3359        [fStatusBar release];
3360        fStatusBar = nil;
3361    }
3362   
3363    if ([fDefaults boolForKey: @"AutoSize"])
3364        [self setWindowMinMaxToCurrent];
3365    else
3366    {
3367        //change min size
3368        NSSize minSize = [fWindow contentMinSize];
3369        minSize.height += heightChange;
3370        [fWindow setContentMinSize: minSize];
3371    }
3372}
3373
3374- (void) toggleFilterBar: (id) sender
3375{
3376    const BOOL show = fFilterBar == nil;
3377   
3378    [self showFilterBar: show animate: YES];
3379    [fDefaults setBool: show forKey: @"FilterBar"];
3380    [[fWindow toolbar] validateVisibleItems];
3381   
3382    //disable filtering when hiding
3383    if (!show)
3384    {
3385        [[NSUserDefaults standardUserDefaults] setObject: FILTER_NONE forKey: @"Filter"];
3386        [[NSUserDefaults standardUserDefaults] setInteger: GROUP_FILTER_ALL_TAG forKey: @"FilterGroup"];
3387        [[NSUserDefaults standardUserDefaults] removeObjectForKey: @"FilterSearchString"];
3388    }
3389   
3390    [self applyFilter]; //do even if showing to ensure tooltips are updated
3391}
3392
3393//doesn't save shown state
3394- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3395{
3396    const BOOL prevShown = fFilterBar != nil;
3397    if (show == prevShown)
3398        return;
3399   
3400    if (show)
3401    {
3402        fFilterBar = [[FilterBarController alloc] init];
3403       
3404        NSView * contentView = [fWindow contentView];
3405        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
3406       
3407        NSRect filterBarFrame = [[fFilterBar view] frame];
3408        filterBarFrame.size.width = windowSize.width;
3409        [[fFilterBar view] setFrame: filterBarFrame];
3410       
3411        if (fStatusBar)
3412            [contentView addSubview: [fFilterBar view] positioned: NSWindowBelow relativeTo: [fStatusBar view]];
3413        else
3414            [contentView addSubview: [fFilterBar view]];
3415        const CGFloat originY = fStatusBar ? NSMinY([[fStatusBar view] frame]) : NSMaxY([contentView frame]);
3416        [[fFilterBar view] setFrameOrigin: NSMakePoint(0.0, originY)];
3417    }
3418    else
3419        [fWindow makeFirstResponder: fTableView];
3420   
3421    CGFloat heightChange = NSHeight([[fFilterBar view] frame]);
3422    if (!show)
3423        heightChange *= -1;
3424   
3425    //allow bar to show even if not enough room
3426    if (show && ![fDefaults boolForKey: @"AutoSize"])
3427    {
3428        NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3429       
3430        NSScreen * screen = [fWindow screen];
3431        if (screen)
3432        {
3433            CGFloat change = [screen visibleFrame].size.height - frame.size.height;
3434            if (change < 0.0)
3435            {
3436                frame = [fWindow frame];
3437                frame.size.height += change;
3438                frame.origin.y -= change;
3439                [fWindow setFrame: frame display: NO animate: NO];
3440            }
3441        }
3442    }
3443   
3444    NSScrollView * scrollView = [fTableView enclosingScrollView];
3445
3446    //set views to not autoresize
3447    const NSUInteger filterMask = [[fFilterBar view] autoresizingMask];
3448    const NSUInteger scrollMask = [scrollView autoresizingMask];
3449    [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
3450    [scrollView setAutoresizingMask: NSViewNotSizable];
3451   
3452    const NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3453    [fWindow setFrame: frame display: YES animate: animate];
3454   
3455    //re-enable autoresize
3456    [[fFilterBar view] setAutoresizingMask: filterMask];
3457    [scrollView setAutoresizingMask: scrollMask];
3458   
3459    if (!show)
3460    {
3461        [[fFilterBar view] removeFromSuperviewWithoutNeedingDisplay];
3462        [fFilterBar release];
3463        fFilterBar = nil;
3464    }
3465   
3466    if ([fDefaults boolForKey: @"AutoSize"])
3467        [self setWindowMinMaxToCurrent];
3468    else
3469    {
3470        //change min size
3471        NSSize minSize = [fWindow contentMinSize];
3472        minSize.height += heightChange;
3473        [fWindow setContentMinSize: minSize];
3474    }
3475}
3476
3477- (void) focusFilterField
3478{
3479    if (!fFilterBar)
3480        [self toggleFilterBar: self];
3481    [fFilterBar focusSearchField];
3482}
3483
3484- (BOOL) acceptsPreviewPanelControl: (QLPreviewPanel *) panel
3485{
3486    return !fQuitting;
3487}
3488
3489- (void) beginPreviewPanelControl: (QLPreviewPanel *) panel
3490{
3491    fPreviewPanel = [panel retain];
3492    [fPreviewPanel setDelegate: self];
3493    [fPreviewPanel setDataSource: self];
3494}
3495
3496- (void) endPreviewPanelControl: (QLPreviewPanel *) panel
3497{
3498    [fPreviewPanel release];
3499    fPreviewPanel = nil;
3500}
3501
3502- (NSArray *) quickLookableTorrents
3503{
3504    NSArray * selectedTorrents = [fTableView selectedTorrents];
3505    NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3506   
3507    for (Torrent * torrent in selectedTorrents)
3508        if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation])
3509            [qlArray addObject: torrent];
3510   
3511    return qlArray;
3512}
3513
3514- (NSInteger) numberOfPreviewItemsInPreviewPanel: (QLPreviewPanel *) panel
3515{
3516    if ([fInfoController canQuickLook])
3517        return [[fInfoController quickLookURLs] count];
3518    else
3519        return [[self quickLookableTorrents] count];
3520}
3521
3522- (id <QLPreviewItem>) previewPanel: (QLPreviewPanel *) panel previewItemAtIndex: (NSInteger) index
3523{
3524    if ([fInfoController canQuickLook])
3525        return [[fInfoController quickLookURLs] objectAtIndex: index];
3526    else
3527        return [[self quickLookableTorrents] objectAtIndex: index];
3528}
3529
3530- (BOOL) previewPanel: (QLPreviewPanel *) panel handleEvent: (NSEvent *) event
3531{
3532    /*if ([event type] == NSKeyDown)
3533    {
3534        [super keyDown: event];
3535        return YES;
3536    }*/
3537   
3538    return NO;
3539}
3540
3541- (NSRect) previewPanel: (QLPreviewPanel *) panel sourceFrameOnScreenForPreviewItem: (id <QLPreviewItem>) item
3542{
3543    if ([fInfoController canQuickLook])
3544        return [fInfoController quickLookSourceFrameForPreviewItem: item];
3545    else
3546    {
3547        if (![fWindow isVisible])
3548            return NSZeroRect;
3549       
3550        const NSInteger row = [fTableView rowForItem: item];
3551        if (row == -1)
3552            return NSZeroRect;
3553       
3554        NSRect frame = [fTableView iconRectForRow: row];
3555       
3556        if (!NSIntersectsRect([fTableView visibleRect], frame))
3557            return NSZeroRect;
3558       
3559        frame.origin = [fTableView convertPoint: frame.origin toView: nil];
3560        frame.origin = [fWindow convertBaseToScreen: frame.origin];
3561        frame.origin.y -= frame.size.height;
3562        return frame;
3563    }
3564}
3565
3566- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3567{
3568    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3569   
3570    NSButton * button = [[NSButton alloc] init];
3571    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3572    [button setStringValue: @""];
3573   
3574    [item setView: button];
3575    [button release];
3576   
3577    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3578    [item setMinSize: buttonSize];
3579    [item setMaxSize: buttonSize];
3580   
3581    return [item autorelease];
3582}
3583
3584- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3585{
3586    if ([ident isEqualToString: TOOLBAR_CREATE])
3587    {
3588        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3589       
3590        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3591        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3592        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3593        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3594        [item setTarget: self];
3595        [item setAction: @selector(createFile:)];
3596        [item setAutovalidates: NO];
3597       
3598        return item;
3599    }
3600    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3601    {
3602        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3603       
3604        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3605        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3606        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3607        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3608        [item setTarget: self];
3609        [item setAction: @selector(openShowSheet:)];
3610        [item setAutovalidates: NO];
3611       
3612        return item;
3613    }
3614    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3615    {
3616        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3617       
3618        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3619        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3620        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3621        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3622        [item setTarget: self];
3623        [item setAction: @selector(openURLShowSheet:)];
3624        [item setAutovalidates: NO];
3625       
3626        return item;
3627    }
3628    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3629    {
3630        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3631       
3632        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3633        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3634        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3635        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3636        [item setTarget: self];
3637        [item setAction: @selector(removeNoDelete:)];
3638        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3639       
3640        return item;
3641    }
3642    else if ([ident isEqualToString: TOOLBAR_INFO])
3643    {
3644        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3645        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3646       
3647        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3648        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3649        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3650        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3651        [item setTarget: self];
3652        [item setAction: @selector(showInfo:)];
3653       
3654        return item;
3655    }
3656    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3657    {
3658        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3659       
3660        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3661        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3662        [groupItem setView: segmentedControl];
3663        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3664       
3665        [segmentedControl setSegmentCount: 2];
3666        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3667       
3668        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3669        [groupItem setMinSize: groupSize];
3670        [groupItem setMaxSize: groupSize];
3671       
3672        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3673        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3674        [groupItem setTarget: self];
3675        [groupItem setAction: @selector(allToolbarClicked:)];
3676       
3677        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3678       
3679        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3680        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3681        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3682                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3683       
3684        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3685        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3686        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3687                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3688       
3689        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3690                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3691       
3692        [segmentedControl release];
3693       
3694        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3695       
3696        return [groupItem autorelease];
3697    }
3698    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3699    {
3700        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3701       
3702        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3703        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3704        [groupItem setView: segmentedControl];
3705        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3706       
3707        [segmentedControl setSegmentCount: 2];
3708        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3709       
3710        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3711        [groupItem setMinSize: groupSize];
3712        [groupItem setMaxSize: groupSize];
3713       
3714        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3715        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3716        [groupItem setTarget: self];
3717        [groupItem setAction: @selector(selectedToolbarClicked:)];
3718       
3719        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3720       
3721        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3722        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3723        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3724                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3725       
3726        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3727        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3728        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3729                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3730       
3731        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3732                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3733       
3734        [segmentedControl release];
3735       
3736        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3737       
3738        return [groupItem autorelease];
3739    }
3740    else if ([ident isEqualToString: TOOLBAR_FILTER])
3741    {
3742        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3743        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3744       
3745        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3746        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3747        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3748        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3749        [item setTarget: self];
3750        [item setAction: @selector(toggleFilterBar:)];
3751       
3752        return item;
3753    }
3754    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3755    {
3756        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3757        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3758       
3759        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3760        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3761        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3762        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3763        [item setTarget: self];
3764        [item setAction: @selector(toggleQuickLook:)];
3765        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow];
3766       
3767        return item;
3768    }
3769    else
3770        return nil;
3771}
3772
3773- (void) allToolbarClicked: (id) sender
3774{
3775    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3776                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag];
3777    switch (tagValue)
3778    {
3779        case TOOLBAR_PAUSE_TAG:
3780            [self stopAllTorrents: sender];
3781            break;
3782        case TOOLBAR_RESUME_TAG:
3783            [self resumeAllTorrents: sender];
3784            break;
3785    }
3786}
3787
3788- (void) selectedToolbarClicked: (id) sender
3789{
3790    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3791                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag];
3792    switch (tagValue)
3793    {
3794        case TOOLBAR_PAUSE_TAG:
3795            [self stopSelectedTorrents: sender];
3796            break;
3797        case TOOLBAR_RESUME_TAG:
3798            [self resumeSelectedTorrents: sender];
3799            break;
3800    }
3801}
3802
3803- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3804{
3805    return [NSArray arrayWithObjects:
3806            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3807            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3808            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3809            NSToolbarSeparatorItemIdentifier,
3810            NSToolbarSpaceItemIdentifier,
3811            NSToolbarFlexibleSpaceItemIdentifier,
3812            NSToolbarCustomizeToolbarItemIdentifier, nil];
3813}
3814
3815- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3816{
3817    return [NSArray arrayWithObjects:
3818            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSpaceItemIdentifier,
3819            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3820            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3821}
3822
3823- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3824{
3825    NSString * ident = [toolbarItem itemIdentifier];
3826   
3827    //enable remove item
3828    if ([ident isEqualToString: TOOLBAR_REMOVE])
3829        return [fTableView numberOfSelectedRows] > 0;
3830
3831    //enable pause all item
3832    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3833    {
3834        for (Torrent * torrent in fTorrents)
3835            if ([torrent isActive] || [torrent waitingToStart])
3836                return YES;
3837        return NO;
3838    }
3839
3840    //enable resume all item
3841    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3842    {
3843        for (Torrent * torrent in fTorrents)
3844            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
3845                return YES;
3846        return NO;
3847    }
3848
3849    //enable pause item
3850    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3851    {
3852        for (Torrent * torrent in [fTableView selectedTorrents])
3853            if ([torrent isActive] || [torrent waitingToStart])
3854                return YES;
3855        return NO;
3856    }
3857   
3858    //enable resume item
3859    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3860    {
3861        for (Torrent * torrent in [fTableView selectedTorrents])
3862            if (![torrent isActive] && ![torrent waitingToStart])
3863                return YES;
3864        return NO;
3865    }
3866   
3867    //set info item
3868    if ([ident isEqualToString: TOOLBAR_INFO])
3869    {
3870        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3871        return YES;
3872    }
3873   
3874    //set filter item
3875    if ([ident isEqualToString: TOOLBAR_FILTER])
3876    {
3877        [(NSButton *)[toolbarItem view] setState: fFilterBar != nil];
3878        return YES;
3879    }
3880   
3881    //set quick look item
3882    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3883    {
3884        [(NSButton *)[toolbarItem view] setState: [QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]];
3885        return YES;
3886    }
3887
3888    return YES;
3889}
3890
3891- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3892{
3893    SEL action = [menuItem action];
3894   
3895    if (action == @selector(toggleSpeedLimit:))
3896    {
3897        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3898        return YES;
3899    }
3900   
3901    //only enable some items if it is in a context menu or the window is useable
3902    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3903
3904    //enable open items
3905    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3906        return [fWindow attachedSheet] == nil;
3907   
3908    //enable sort options
3909    if (action == @selector(setSort:))
3910    {
3911        NSString * sortType;
3912        switch ([menuItem tag])
3913        {
3914            case SORT_ORDER_TAG:
3915                sortType = SORT_ORDER;
3916                break;
3917            case SORT_DATE_TAG:
3918                sortType = SORT_DATE;
3919                break;
3920            case SORT_NAME_TAG:
3921                sortType = SORT_NAME;
3922                break;
3923            case SORT_PROGRESS_TAG:
3924                sortType = SORT_PROGRESS;
3925                break;
3926            case SORT_STATE_TAG:
3927                sortType = SORT_STATE;
3928                break;
3929            case SORT_TRACKER_TAG:
3930                sortType = SORT_TRACKER;
3931                break;
3932            case SORT_ACTIVITY_TAG:
3933                sortType = SORT_ACTIVITY;
3934                break;
3935            case SORT_SIZE_TAG:
3936                sortType = SORT_SIZE;
3937                break;
3938            default:
3939                NSAssert1(NO, @"Unknown sort tag received: %d", [menuItem tag]);
3940        }
3941       
3942        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3943        return [fWindow isVisible];
3944    }
3945   
3946    if (action == @selector(setGroup:))
3947    {
3948        BOOL checked = NO;
3949       
3950        NSInteger index = [menuItem tag];
3951        for (Torrent * torrent in [fTableView selectedTorrents])
3952            if (index == [torrent groupValue])
3953            {
3954                checked = YES;
3955                break;
3956            }
3957       
3958        [menuItem setState: checked ? NSOnState : NSOffState];
3959        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3960    }
3961   
3962    if (action == @selector(toggleSmallView:))
3963    {
3964        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3965        return [fWindow isVisible];
3966    }
3967   
3968    if (action == @selector(togglePiecesBar:))
3969    {
3970        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3971        return [fWindow isVisible];
3972    }
3973   
3974    #warning remove when menu is removed (10.7-only)
3975    if (action == @selector(toggleStatusString:))
3976    {
3977        if ([fDefaults boolForKey: @"SmallView"])
3978        {
3979            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3980            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3981        }
3982        else
3983        {
3984            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3985            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3986        }
3987       
3988        return [fWindow isVisible];
3989    }
3990   
3991    if (action == @selector(toggleAvailabilityBar:))
3992    {
3993        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3994        return [fWindow isVisible];
3995    }
3996   
3997    if (action == @selector(setLimitGlobalEnabled:))
3998    {
3999        BOOL upload = [menuItem menu] == fUploadMenu;
4000        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
4001        if (limit)
4002            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
4003                                    "Action menu -> upload/download limit"),
4004                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
4005       
4006        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
4007        return YES;
4008    }
4009   
4010    if (action == @selector(setRatioGlobalEnabled:))
4011    {
4012        BOOL check = menuItem == fCheckRatioItem;
4013        if (check)
4014            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
4015                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
4016       
4017        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
4018        return YES;
4019    }
4020
4021    //enable show info
4022    if (action == @selector(showInfo:))
4023    {
4024        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
4025                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
4026        [menuItem setTitle: title];
4027
4028        return YES;
4029    }
4030   
4031    //enable prev/next inspector tab
4032    if (action == @selector(setInfoTab:))
4033        return [[fInfoController window] isVisible];
4034   
4035    //enable toggle status bar
4036    if (action == @selector(toggleStatusBar:))
4037    {
4038        NSString * title = !fStatusBar ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
4039                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
4040        [menuItem setTitle: title];
4041
4042        return [fWindow isVisible];
4043    }
4044   
4045    //enable toggle filter bar
4046    if (action == @selector(toggleFilterBar:))
4047    {
4048        NSString * title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
4049                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
4050        [menuItem setTitle: title];
4051
4052        return [fWindow isVisible];
4053    }
4054   
4055    //enable prev/next filter button
4056    if (action == @selector(switchFilter:))
4057        return [fWindow isVisible] && fFilterBar;
4058   
4059    //enable reveal in finder
4060    if (action == @selector(revealFile:))
4061        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4062
4063    //enable remove items
4064    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
4065    {
4066        BOOL warning = NO;
4067       
4068        for (Torrent * torrent in [fTableView selectedTorrents])
4069        {
4070            if ([torrent isActive])
4071            {
4072                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
4073                {
4074                    warning = YES;
4075                    break;
4076                }
4077            }
4078        }
4079   
4080        //append or remove ellipsis when needed
4081        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
4082        if (warning && [fDefaults boolForKey: @"CheckRemove"])
4083        {
4084            if (![title hasSuffix: ellipsis])
4085                [menuItem setTitle: [title stringByAppendingEllipsis]];
4086        }
4087        else
4088        {
4089            if ([title hasSuffix: ellipsis])
4090                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
4091        }
4092       
4093        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4094    }
4095   
4096    //remove all completed transfers item
4097    if (action == @selector(clearCompleted:))
4098    {
4099        //append or remove ellipsis when needed
4100        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
4101        if ([fDefaults boolForKey: @"WarningRemoveCompleted"])
4102        {
4103            if (![title hasSuffix: ellipsis])
4104                [menuItem setTitle: [title stringByAppendingEllipsis]];
4105        }
4106        else
4107        {
4108            if ([title hasSuffix: ellipsis])
4109                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
4110        }
4111       
4112        for (Torrent * torrent in fTorrents)
4113            if ([torrent isFinishedSeeding])
4114                return YES;
4115        return NO;
4116    }
4117
4118    //enable pause all item
4119    if (action == @selector(stopAllTorrents:))
4120    {
4121        for (Torrent * torrent in fTorrents)
4122            if ([torrent isActive] || [torrent waitingToStart])
4123                return YES;
4124        return NO;
4125    }
4126   
4127    //enable resume all item
4128    if (action == @selector(resumeAllTorrents:))
4129    {
4130        for (Torrent * torrent in fTorrents)
4131            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
4132                return YES;
4133        return NO;
4134    }
4135   
4136    //enable resume all waiting item
4137    if (action == @selector(resumeWaitingTorrents:))
4138    {
4139        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
4140            return NO;
4141   
4142        for (Torrent * torrent in fTorrents)
4143            if ([torrent waitingToStart])
4144                return YES;
4145        return NO;
4146    }
4147   
4148    //enable resume selected waiting item
4149    if (action == @selector(resumeSelectedTorrentsNoWait:))
4150    {
4151        if (!canUseTable)
4152            return NO;
4153       
4154        for (Torrent * torrent in [fTableView selectedTorrents])
4155            if (![torrent isActive])
4156                return YES;
4157        return NO;
4158    }
4159
4160    //enable pause item
4161    if (action == @selector(stopSelectedTorrents:))
4162    {
4163        if (!canUseTable)
4164            return NO;
4165   
4166        for (Torrent * torrent in [fTableView selectedTorrents])
4167            if ([torrent isActive] || [torrent waitingToStart])
4168                return YES;
4169        return NO;
4170    }
4171   
4172    //enable resume item
4173    if (action == @selector(resumeSelectedTorrents:))
4174    {
4175        if (!canUseTable)
4176            return NO;
4177   
4178        for (Torrent * torrent in [fTableView selectedTorrents])
4179            if (![torrent isActive] && ![torrent waitingToStart])
4180                return YES;
4181        return NO;
4182    }
4183   
4184    //enable manual announce item
4185    if (action == @selector(announceSelectedTorrents:))
4186    {
4187        if (!canUseTable)
4188            return NO;
4189       
4190        for (Torrent * torrent in [fTableView selectedTorrents])
4191            if ([torrent canManualAnnounce])
4192                return YES;
4193        return NO;
4194    }
4195   
4196    //enable reset cache item
4197    if (action == @selector(verifySelectedTorrents:))
4198    {
4199        if (!canUseTable)
4200            return NO;
4201           
4202        for (Torrent * torrent in [fTableView selectedTorrents])
4203            if (![torrent isMagnet])
4204                return YES;
4205        return NO;
4206    }
4207   
4208    //enable move torrent file item
4209    if (action == @selector(moveDataFilesSelected:))
4210        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4211   
4212    //enable copy torrent file item
4213    if (action == @selector(copyTorrentFiles:))
4214    {
4215        if (!canUseTable)
4216            return NO;
4217       
4218        for (Torrent * torrent in [fTableView selectedTorrents])
4219            if (![torrent isMagnet])
4220                return YES;
4221        return NO;
4222    }
4223   
4224    //enable copy torrent file item
4225    if (action == @selector(copyMagnetLinks:))
4226        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4227   
4228    //enable reverse sort item
4229    if (action == @selector(setSortReverse:))
4230    {
4231        const BOOL isReverse = [menuItem tag] == SORT_DESC_TAG;
4232        [menuItem setState: (isReverse == [fDefaults boolForKey: @"SortReverse"]) ? NSOnState : NSOffState];
4233        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
4234    }
4235   
4236    //enable group sort item
4237    if (action == @selector(setSortByGroup:))
4238    {
4239        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
4240        return YES;
4241    }
4242   
4243    if (action == @selector(toggleQuickLook:))
4244    {
4245        const BOOL visible =[QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible];
4246        //text consistent with Finder
4247        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
4248                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
4249        [menuItem setTitle: title];
4250       
4251        return YES;
4252    }
4253   
4254    return YES;
4255}
4256
4257- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
4258{
4259    switch (messageType)
4260    {
4261        case kIOMessageSystemWillSleep:
4262            //if there are any running transfers, wait 15 seconds for them to stop
4263            for (Torrent * torrent in fTorrents)
4264                if ([torrent isActive])
4265                {
4266                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
4267                    for (Torrent * torrent in fTorrents)
4268                        [torrent sleep];
4269                    sleep(15);
4270                    break;
4271                }
4272
4273            IOAllowPowerChange(fRootPort, (long) messageArgument);
4274            break;
4275
4276        case kIOMessageCanSystemSleep:
4277            if ([fDefaults boolForKey: @"SleepPrevent"])
4278            {
4279                //prevent idle sleep unless no torrents are active
4280                for (Torrent * torrent in fTorrents)
4281                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
4282                    {
4283                        IOCancelPowerChange(fRootPort, (long) messageArgument);
4284                        return;
4285                    }
4286            }
4287           
4288            IOAllowPowerChange(fRootPort, (long) messageArgument);
4289            break;
4290
4291        case kIOMessageSystemHasPoweredOn:
4292            //resume sleeping transfers after we wake up
4293            for (Torrent * torrent in fTorrents)
4294                [torrent wakeUp];
4295            break;
4296    }
4297}
4298
4299- (NSMenu *) applicationDockMenu: (NSApplication *) sender
4300{
4301    if (fQuitting)
4302        return nil;
4303   
4304    NSUInteger seeding = 0, downloading = 0;
4305    for (Torrent * torrent in fTorrents)
4306    {
4307        if ([torrent isSeeding])
4308            seeding++;
4309        else if ([torrent isActive])
4310            downloading++;
4311        else;
4312    }
4313   
4314    NSMenu * menu = [[NSMenu alloc] init];
4315   
4316    if (seeding > 0)
4317    {
4318        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
4319        [menu addItemWithTitle: title action: nil keyEquivalent: @""];
4320    }
4321   
4322    if (downloading > 0)
4323    {
4324        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
4325        [menu addItemWithTitle: title action: nil keyEquivalent: @""];
4326    }
4327   
4328    if (seeding > 0 || downloading > 0)
4329        [menu addItem: [NSMenuItem separatorItem]];
4330   
4331    [menu addItemWithTitle: NSLocalizedString(@"Pause All", "Dock item") action: @selector(stopAllTorrents:) keyEquivalent: @""];
4332    [menu addItemWithTitle: NSLocalizedString(@"Resume All", "Dock item") action: @selector(resumeAllTorrents:) keyEquivalent: @""];
4333    [menu addItem: [NSMenuItem separatorItem]];
4334    [menu addItemWithTitle: NSLocalizedString(@"Speed Limit", "Dock item") action: @selector(toggleSpeedLimit:) keyEquivalent: @""];
4335   
4336    return [menu autorelease];
4337}
4338
4339- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
4340{
4341    //if auto size is enabled, the current frame shouldn't need to change
4342    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
4343   
4344    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
4345    return frame;
4346}
4347
4348- (void) setWindowSizeToFit
4349{
4350    if ([fDefaults boolForKey: @"AutoSize"])
4351    {
4352        NSScrollView * scrollView = [fTableView enclosingScrollView];
4353       
4354        [scrollView setHasVerticalScroller: NO];
4355        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
4356        [scrollView setHasVerticalScroller: YES];
4357       
4358        [self setWindowMinMaxToCurrent];
4359    }
4360}
4361
4362- (NSRect) sizedWindowFrame
4363{
4364    NSUInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
4365                        ? [fDisplayedTorrents count] : 0;
4366   
4367    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4368                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4369                        - NSHeight([[fTableView enclosingScrollView] frame]);
4370   
4371    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4372}
4373
4374- (void) updateForAutoSize
4375{
4376    if ([fDefaults boolForKey: @"AutoSize"])
4377        [self setWindowSizeToFit];
4378    else
4379    {
4380        NSSize contentMinSize = [fWindow contentMinSize];
4381        contentMinSize.height = [self minWindowContentSizeAllowed];
4382       
4383        [fWindow setContentMinSize: contentMinSize];
4384       
4385        NSSize contentMaxSize = [fWindow contentMaxSize];
4386        contentMaxSize.height = FLT_MAX;
4387        [fWindow setContentMaxSize: contentMaxSize];
4388    }
4389}
4390
4391- (void) setWindowMinMaxToCurrent
4392{
4393    const CGFloat height = NSHeight([[fWindow contentView] frame]);
4394   
4395    NSSize minSize = [fWindow contentMinSize],
4396            maxSize = [fWindow contentMaxSize];
4397    minSize.height = height;
4398    maxSize.height = height;
4399   
4400    [fWindow setContentMinSize: minSize];
4401    [fWindow setContentMaxSize: maxSize];
4402}
4403
4404- (CGFloat) minWindowContentSizeAllowed
4405{
4406    CGFloat contentMinHeight = NSHeight([[fWindow contentView] frame]) - NSHeight([[fTableView enclosingScrollView] frame])
4407                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
4408    return contentMinHeight;
4409}
4410
4411- (void) updateForExpandCollape
4412{
4413    [self setWindowSizeToFit];
4414    [self setBottomCountText: YES];
4415}
4416
4417- (void) showMainWindow: (id) sender
4418{
4419    [fWindow makeKeyAndOrderFront: nil];
4420}
4421
4422- (void) windowDidBecomeMain: (NSNotification *) notification
4423{
4424    [fBadger clearCompleted];
4425    [self updateUI];
4426}
4427
4428- (void) applicationWillUnhide: (NSNotification *) notification
4429{
4430    [self updateUI];
4431}
4432
4433- (void) toggleQuickLook: (id) sender
4434{
4435    if ([[QLPreviewPanel sharedPreviewPanel] isVisible])
4436        [[QLPreviewPanel sharedPreviewPanel] orderOut: nil];
4437    else
4438        [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront: nil];
4439}
4440
4441- (void) linkHomepage: (id) sender
4442{
4443    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4444}
4445
4446- (void) linkForums: (id) sender
4447{
4448    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4449}
4450
4451- (void) linkTrac: (id) sender
4452{
4453    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4454}
4455
4456- (void) linkDonate: (id) sender
4457{
4458    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4459}
4460
4461- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4462{
4463    fQuitRequested = YES;
4464}
4465
4466- (NSDictionary *) registrationDictionaryForGrowl
4467{
4468    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4469                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4470    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4471                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4472}
4473
4474- (void) growlNotificationWasClicked: (id) clickContext
4475{
4476    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4477        return;
4478   
4479    NSString * type = [clickContext objectForKey: @"Type"], * location;
4480    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4481            && (location = [clickContext objectForKey: @"Location"]))
4482    {
4483        NSURL * file = [NSURL fileURLWithPath: location];
4484        [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4485    }
4486}
4487
4488- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4489{
4490    @autoreleasepool
4491    {
4492        //get the torrent
4493        Torrent * torrent = nil;
4494        if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED && type != TR_RPC_SESSION_CLOSE))
4495        {
4496            for (torrent in fTorrents)
4497                if (torrentStruct == [torrent torrentStruct])
4498                {
4499                    [torrent retain];
4500                    break;
4501                }
4502           
4503            if (!torrent)
4504            {
4505                NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4506                return;
4507            }
4508        }
4509       
4510        switch (type)
4511        {
4512            case TR_RPC_TORRENT_ADDED:
4513                [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4514                    [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4515                break;
4516           
4517            case TR_RPC_TORRENT_STARTED:
4518            case TR_RPC_TORRENT_STOPPED:
4519                [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4520                break;
4521           
4522            case TR_RPC_TORRENT_REMOVING:
4523                [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4524                break;
4525           
4526            case TR_RPC_TORRENT_TRASHING:
4527                [self performSelectorOnMainThread: @selector(rpcRemoveTorrentDeleteData:) withObject: torrent waitUntilDone: NO];
4528                break;
4529           
4530            case TR_RPC_TORRENT_CHANGED:
4531                [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4532                break;
4533           
4534            case TR_RPC_TORRENT_MOVED:
4535                [self performSelectorOnMainThread: @selector(rpcMovedTorrent:) withObject: torrent waitUntilDone: NO];
4536                break;
4537           
4538            case TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED:
4539                [self performSelectorOnMainThread: @selector(rpcUpdateQueue) withObject: nil waitUntilDone: NO];
4540                break;
4541           
4542            case TR_RPC_SESSION_CHANGED:
4543                [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4544                break;
4545           
4546            case TR_RPC_SESSION_CLOSE:
4547                fQuitRequested = YES;
4548                [NSApp performSelectorOnMainThread: @selector(terminate:) withObject: self waitUntilDone: NO];
4549                break;
4550           
4551            default:
4552                NSAssert1(NO, @"Unknown RPC command received: %d", type);
4553                [torrent release];
4554        }
4555    }
4556}
4557
4558- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4559{
4560    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4561    [torrentStructPtr release];
4562   
4563    NSString * location = nil;
4564    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4565        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4566   
4567    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4568   
4569    //change the location if the group calls for it (this has to wait until after the torrent is created)
4570    if ([[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
4571    {
4572        location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
4573        [torrent changeDownloadFolderBeforeUsing: location];
4574    }
4575   
4576    [torrent update];
4577    [fTorrents addObject: torrent];
4578    [torrent release];
4579   
4580    if (!fAddingTransfers)
4581        fAddingTransfers = [[NSMutableSet alloc] init];
4582    [fAddingTransfers addObject: torrent];
4583   
4584    [self fullUpdateUI];
4585}
4586
4587- (void) rpcRemoveTorrent: (Torrent *) torrent
4588{
4589    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4590    [torrent release];
4591}
4592
4593- (void) rpcRemoveTorrentDeleteData: (Torrent *) torrent
4594{
4595    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: YES];
4596    [torrent release];
4597}
4598
4599- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4600{
4601    [torrent update];
4602    [torrent release];
4603   
4604    [self updateUI];
4605    [self applyFilter];
4606    [self updateTorrentHistory];
4607}
4608
4609- (void) rpcChangedTorrent: (Torrent *) torrent
4610{
4611    [torrent update];
4612   
4613    if ([[fTableView selectedTorrents] containsObject: torrent])
4614    {
4615        [fInfoController updateInfoStats]; //this will reload the file table
4616        [fInfoController updateOptions];
4617    }
4618   
4619    [torrent release];
4620}
4621
4622- (void) rpcMovedTorrent: (Torrent *) torrent
4623{
4624    [torrent update];
4625    [torrent updateTimeMachineExclude];
4626   
4627    if ([[fTableView selectedTorrents] containsObject: torrent])
4628        [fInfoController updateInfoStats];
4629   
4630    [torrent release];
4631}
4632
4633- (void) rpcUpdateQueue
4634{
4635    for (Torrent * torrent in fTorrents)
4636        [torrent update];
4637   
4638    NSArray * selectedValues = [fTableView selectedValues];
4639   
4640    NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: YES];
4641    NSArray * descriptors = [NSArray arrayWithObject: descriptor];
4642   
4643    [fTorrents sortUsingDescriptors: descriptors];
4644   
4645    [self fullUpdateUI];
4646   
4647    [fTableView selectValues: selectedValues];
4648}
4649
4650@end
Note: See TracBrowser for help on using the repository browser.