source: trunk/macosx/Controller.m @ 13255

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

more cleanup

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