source: trunk/macosx/Controller.m @ 13131

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

speed up for #4696

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