source: trunk/macosx/Controller.m @ 13377

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

#2353 Add an option to the inspector to remove transfers from the list when seeding completes

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