source: trunk/macosx/Controller.m @ 13319

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

#4921 On Lion, use window restoration on the torrent creation window

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