source: trunk/macosx/Controller.m @ 13340

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

#4749 When accessing images using imageNamed:, don't include the .png. This fixes the app not using the @2x images in HiDPI mode.

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