source: trunk/macosx/Controller.m @ 13139

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

don't animate the main table on launch

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