source: trunk/macosx/Controller.m @ 13144

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

more array enumeration using blocks and the concurrent option

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