source: trunk/macosx/Controller.m @ 13130

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

#4696 (Lion) animate sorting the main table

  • Property svn:keywords set to Date Rev Author Id
File size: 159.9 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 13130 2012-01-04 05:16:07Z 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    NSArray * selectedValues;
1836    if ([NSApp isOnLionOrBetter])
1837        [fTableView beginUpdates];
1838    else
1839        selectedValues = [fTableView selectedValues];
1840   
1841    NSMutableArray * moves = [NSMutableArray array];
1842    [self sortTorrentsIgnoreSelected: moves includeQueueOrder: includeQueueOrder]; //actually sort
1843   
1844    if ([NSApp isOnLionOrBetter])
1845    {
1846        for (NSDictionary * move in moves)
1847        {
1848            id parent = [move objectForKey: @"Parent"];
1849            [fTableView moveItemAtIndex: [(NSNumber *)[move objectForKey: @"From"] unsignedIntegerValue] inParent: parent toIndex: [(NSNumber *)[move objectForKey: @"To"] unsignedIntegerValue] inParent: parent];
1850        }
1851       
1852        [fTableView setNeedsDisplay: YES]; //need to make sure all have new info
1853    }
1854    else
1855    {
1856        if ([moves count] > 0)
1857        {
1858            [fTableView reloadData];
1859            [fTableView selectValues: selectedValues];
1860        }
1861        else
1862            [fTableView setNeedsDisplay: YES];
1863    }
1864   
1865    if ([NSApp isOnLionOrBetter])
1866        [fTableView endUpdates];
1867}
1868
1869#warning rename
1870- (void) sortTorrentsIgnoreSelected: (NSMutableArray *) moves includeQueueOrder: (BOOL) includeQueueOrder
1871{
1872    [moves removeAllObjects];
1873   
1874    //don't do anything else if we don't have to
1875    const BOOL sortByGroup = [fDefaults boolForKey: @"SortByGroup"];
1876    const NSUInteger count = [fDisplayedTorrents count];
1877    if (count == 0 || (!sortByGroup && count == 1))
1878        return;
1879   
1880    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1881   
1882    if (!includeQueueOrder && [sortType isEqualToString: SORT_ORDER])
1883        return;
1884   
1885    const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1886   
1887    NSArray * descriptors;
1888    NSSortDescriptor * nameDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: asc selector: @selector(localizedStandardCompare:)];
1889   
1890    if ([sortType isEqualToString: SORT_STATE])
1891    {
1892        NSSortDescriptor * stateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"stateSortKey" ascending: !asc],
1893                        * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: !asc],
1894                        * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: !asc];
1895       
1896        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor, nameDescriptor, nil];
1897    }
1898    else if ([sortType isEqualToString: SORT_PROGRESS])
1899    {
1900        NSSortDescriptor * progressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progress" ascending: asc],
1901                        * ratioProgressDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"progressStopRatio" ascending: asc],
1902                        * ratioDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"ratio" ascending: asc];
1903       
1904        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor, nameDescriptor, nil];
1905    }
1906    else if ([sortType isEqualToString: SORT_TRACKER])
1907    {
1908        NSSortDescriptor * trackerDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"trackerSortKey" ascending: asc selector: @selector(localizedCaseInsensitiveCompare:)];
1909       
1910        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, nil];
1911    }
1912    else if ([sortType isEqualToString: SORT_ACTIVITY])
1913    {
1914        NSSortDescriptor * rateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"totalRate" ascending: !asc];
1915        NSSortDescriptor * activityDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateActivityOrAdd" ascending: !asc];
1916       
1917        descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
1918    }
1919    else if ([sortType isEqualToString: SORT_DATE])
1920    {
1921        NSSortDescriptor * dateDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"dateAdded" ascending: asc];
1922       
1923        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
1924    }
1925    else if ([sortType isEqualToString: SORT_SIZE])
1926    {
1927        NSSortDescriptor * sizeDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"size" ascending: asc];
1928       
1929        descriptors = [[NSArray alloc] initWithObjects: sizeDescriptor, nameDescriptor, nil];
1930    }
1931    else if ([sortType isEqualToString: SORT_NAME])
1932    {
1933        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, nil];
1934    }
1935    else
1936    {
1937        NSAssert1([sortType isEqualToString: SORT_ORDER], @"Unknown sort type received: %@", sortType);
1938        NSAssert(includeQueueOrder, @"Sorting by queue order when we shouldn't");
1939       
1940        NSSortDescriptor * orderDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: asc];
1941       
1942        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1943    }
1944   
1945    //actually sort
1946    if (sortByGroup)
1947    {
1948        for (TorrentGroup * group in fDisplayedTorrents)
1949        {
1950            if ([[group torrents] count] > 1)
1951            {
1952                if (moves)
1953                {
1954                    NSArray * sorted = [[group torrents] sortedArrayUsingDescriptors: descriptors];
1955                    [moves addObjectsFromArray: [self rearrangeTorrentArray: [group torrents] to: sorted forParent: group]];
1956                }
1957                else
1958                    [[group torrents] sortUsingDescriptors: descriptors];
1959            }
1960        }
1961    }
1962    else
1963    {
1964        if (moves)
1965        {
1966            NSArray * sorted = [fDisplayedTorrents sortedArrayUsingDescriptors: descriptors];
1967            [moves setArray: [self rearrangeTorrentArray: fDisplayedTorrents to: sorted forParent: nil]];
1968        }
1969        else
1970            [fDisplayedTorrents sortUsingDescriptors: descriptors];
1971    }
1972   
1973    [descriptors release];
1974}
1975
1976- (NSArray *) rearrangeTorrentArray: (NSMutableArray *) rearrangeArray to: (NSArray *) endingArray forParent: parent
1977{
1978    NSAssert2([rearrangeArray count] == [endingArray count], @"Torrent arrays aren't equal size: %d and %d", [rearrangeArray count], [endingArray count]);
1979   
1980    NSMutableArray * moves = [NSMutableArray array];
1981    for (NSUInteger currentIndex = 0; currentIndex < [rearrangeArray count]; ++currentIndex)
1982    {
1983        Torrent * torrent = [endingArray objectAtIndex: currentIndex];
1984        const NSUInteger previousIndex = [rearrangeArray indexOfObject: torrent inRange: NSMakeRange(currentIndex, [rearrangeArray count]-currentIndex)];
1985       
1986        if (previousIndex != currentIndex)
1987        {
1988            NSAssert3(previousIndex != NSNotFound, @"Expected torrent %@ not found! %@ %@", torrent, rearrangeArray, endingArray);
1989           
1990            [rearrangeArray moveObjectAtIndex: previousIndex toIndex: currentIndex];
1991           
1992            NSMutableDictionary * move = [NSMutableDictionary dictionaryWithCapacity: parent ? 3 : 2];
1993            [move setObject: [NSNumber numberWithUnsignedInteger: previousIndex] forKey: @"From"];
1994            [move setObject: [NSNumber numberWithUnsignedInteger: currentIndex] forKey: @"To"];
1995            if (parent)
1996                [move setObject: parent forKey: @"Parent"];
1997           
1998            [moves addObject: move];
1999        }
2000    }
2001   
2002    NSAssert2([rearrangeArray isEqualToArray: endingArray], @"Torrent rearranging didn't work! %@ %@", rearrangeArray, endingArray);
2003   
2004    return moves;
2005}
2006
2007- (void) applyFilter
2008{
2009    //get all the torrents in the table
2010    NSMutableArray * previousTorrents;
2011    if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2012    {
2013        previousTorrents = [NSMutableArray array];
2014       
2015        for (TorrentGroup * group in fDisplayedTorrents)
2016            [previousTorrents addObjectsFromArray: [group torrents]];
2017    }
2018    else
2019        previousTorrents = fDisplayedTorrents;
2020   
2021    NSArray * selectedValues = [fTableView selectedValues];
2022   
2023    NSUInteger active = 0, downloading = 0, seeding = 0, paused = 0;
2024    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2025    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
2026    if ([filterType isEqualToString: FILTER_ACTIVE])
2027        filterActive = YES;
2028    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2029        filterDownload = YES;
2030    else if ([filterType isEqualToString: FILTER_SEED])
2031        filterSeed = YES;
2032    else if ([filterType isEqualToString: FILTER_PAUSE])
2033        filterPause = YES;
2034    else
2035        filterStatus = NO;
2036   
2037    const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
2038    const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
2039   
2040    NSArray * searchStrings = [fFilterBar searchStrings];
2041    if (searchStrings && [searchStrings count] == 0)
2042        searchStrings = nil;
2043    const BOOL filterTracker = searchStrings && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
2044   
2045    NSMutableArray * allTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2046   
2047    //get count of each type
2048    for (Torrent * torrent in fTorrents)
2049    {
2050        //check status
2051        if ([torrent isActive] && ![torrent isCheckingWaiting])
2052        {
2053            const BOOL isActive = ![torrent isStalled];
2054            if (isActive)
2055                ++active;
2056           
2057            if ([torrent isSeeding])
2058            {
2059                ++seeding;
2060                if (filterStatus && !((filterActive && isActive) || filterSeed))
2061                    continue;
2062            }
2063            else
2064            {
2065                ++downloading;
2066                if (filterStatus && !((filterActive && isActive) || filterDownload))
2067                    continue;
2068            }
2069        }
2070        else
2071        {
2072            ++paused;
2073            if (filterStatus && !filterPause)
2074                continue;
2075        }
2076       
2077        //checkGroup
2078        if (filterGroup)
2079            if ([torrent groupValue] != groupFilterValue)
2080                continue;
2081       
2082        //check text field
2083        if (searchStrings)
2084        {
2085            BOOL removeTextField = NO;
2086            if (filterTracker)
2087            {
2088                NSArray * trackers = [torrent allTrackersFlat];
2089               
2090                //to count, we need each string in atleast 1 tracker
2091                for (NSString * searchString in searchStrings)
2092                {
2093                    BOOL found = NO;
2094                    for (NSString * tracker in trackers)
2095                    {
2096                        if ([tracker rangeOfString: searchString options:
2097                             (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound)
2098                        {
2099                            found = YES;
2100                            break;
2101                        }
2102                    }
2103                    if (!found)
2104                    {
2105                        removeTextField = YES;
2106                        break;
2107                    }
2108                }
2109            }
2110            else
2111            {
2112                for (NSString * searchString in searchStrings)
2113                    if ([[torrent name] rangeOfString: searchString options: (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound)
2114                    {
2115                        removeTextField = YES;
2116                        break;
2117                    }
2118            }
2119           
2120            if (removeTextField)
2121                continue;
2122        }
2123       
2124        [allTorrents addObject: torrent];
2125    }
2126   
2127    //set button tooltips
2128    if (fFilterBar)
2129        [fFilterBar setCountAll: [fTorrents count] active: active downloading: downloading seeding: seeding paused: paused];
2130   
2131    //clear display cache for not-shown torrents
2132    [previousTorrents removeObjectsInArray: allTorrents];
2133    for (Torrent * torrent in previousTorrents)
2134        [torrent setPreviousFinishedPieces: nil];
2135   
2136    //place torrents into groups
2137    const BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"];
2138    if (groupRows)
2139    {
2140        NSMutableArray * oldTorrentGroups = [NSMutableArray array];
2141        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2142            [oldTorrentGroups addObjectsFromArray: fDisplayedTorrents];
2143       
2144        [fDisplayedTorrents removeAllObjects];
2145       
2146        NSSortDescriptor * groupDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"groupOrderValue" ascending: YES];
2147        [allTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2148       
2149        TorrentGroup * group = nil;
2150        NSInteger lastGroupValue = -2, currentOldGroupIndex = 0;
2151        for (Torrent * torrent in allTorrents)
2152        {
2153            const NSInteger groupValue = [torrent groupValue];
2154            if (groupValue != lastGroupValue)
2155            {
2156                lastGroupValue = groupValue;
2157               
2158                group = nil;
2159               
2160                //try to see if the group already exists
2161                for (; currentOldGroupIndex < [oldTorrentGroups count]; ++currentOldGroupIndex)
2162                {
2163                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
2164                    const NSInteger currentGroupValue = [currentGroup groupIndex];
2165                    if (currentGroupValue == groupValue)
2166                    {
2167                        group = currentGroup;
2168                        [[currentGroup torrents] removeAllObjects];
2169                       
2170                        ++currentOldGroupIndex;
2171                    }
2172                   
2173                    if (currentGroupValue >= groupValue)
2174                        break;
2175                }
2176               
2177                if (!group)
2178                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2179                [fDisplayedTorrents addObject: group];
2180            }
2181           
2182            NSAssert(group != nil, @"No group object to add torrents to");
2183            [[group torrents] addObject: torrent];
2184        }
2185    }
2186    else
2187        [fDisplayedTorrents setArray: allTorrents];
2188   
2189    //actually sort
2190    [self sortTorrentsIgnoreSelected: NULL includeQueueOrder: NO];
2191    [fTableView reloadData];
2192   
2193    //reset expanded/collapsed rows
2194    if (groupRows)
2195    {
2196        for (TorrentGroup * group in fDisplayedTorrents)
2197        {
2198            if ([fTableView isGroupCollapsed: [group groupIndex]])
2199                [fTableView collapseItem: group];
2200            else
2201                [fTableView expandItem: group];
2202        }
2203    }
2204   
2205    [fTableView selectValues: selectedValues];
2206    [self resetInfo]; //if group is already selected, but the torrents in it change
2207   
2208    [self setBottomCountText: groupRows || filterStatus || filterGroup || searchStrings];
2209   
2210    [self setWindowSizeToFit];
2211}
2212
2213- (void) switchFilter: (id) sender
2214{
2215    [fFilterBar switchFilter: sender == fNextFilterItem];
2216}
2217
2218- (IBAction) showGlobalPopover: (id) sender
2219{
2220    if ([NSApp isOnLionOrBetter])
2221    {
2222        if (fGlobalPopoverShown)
2223            return;
2224       
2225        NSPopover * popover = [[NSPopoverLion alloc] init];
2226        [popover setBehavior: NSPopoverBehaviorTransient];
2227        GlobalOptionsPopoverViewController * viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle: [PrefsController handle]];
2228        [popover setContentViewController: viewController];
2229        [popover setDelegate: self];
2230       
2231        [popover showRelativeToRect: [sender frame] ofView: sender preferredEdge: NSMaxYEdge];
2232       
2233        [viewController release];
2234        [popover release];
2235    }
2236    else
2237    {
2238        //place menu below button
2239        NSRect rect = [sender frame];
2240        NSPoint location = rect.origin;
2241        location.y += NSHeight(rect) + 5.0;
2242       
2243        [fActionMenu popUpMenuPositioningItem: nil atLocation: location inView: sender];
2244    }
2245}
2246
2247//don't show multiple popovers when clicking the gear button repeatedly
2248- (void) popoverWillShow: (NSNotification *) notification
2249{
2250    fGlobalPopoverShown = YES;
2251}
2252
2253- (void) popoverWillClose: (NSNotification *) notification
2254{
2255    fGlobalPopoverShown = NO;
2256}
2257
2258- (void) menuNeedsUpdate: (NSMenu *) menu
2259{
2260    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2261    {
2262        for (NSInteger i = [menu numberOfItems]-1; i >= 0; i--)
2263            [menu removeItemAtIndex: i];
2264       
2265        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2266       
2267        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2268        for (NSInteger i = 0; i < groupMenuCount; i++)
2269        {
2270            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2271            [groupMenu removeItemAtIndex: 0];
2272            [menu addItem: item];
2273            [item release];
2274        }
2275    }
2276    else if (menu == fUploadMenu || menu == fDownloadMenu)
2277    {
2278        if ([menu numberOfItems] > 3)
2279            return;
2280       
2281        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2282       
2283        NSMenuItem * item;
2284        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2285        {
2286            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2287                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2288                    keyEquivalent: @""];
2289            [item setTarget: self];
2290            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2291            [menu addItem: item];
2292            [item release];
2293        }
2294    }
2295    else if (menu == fRatioStopMenu)
2296    {
2297        if ([menu numberOfItems] > 3)
2298            return;
2299       
2300        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2301       
2302        NSMenuItem * item;
2303        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2304        {
2305            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2306                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2307            [item setTarget: self];
2308            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2309            [menu addItem: item];
2310            [item release];
2311        }
2312    }
2313    else;
2314}
2315
2316- (void) setGroup: (id) sender
2317{
2318    for (Torrent * torrent in [fTableView selectedTorrents])
2319    {
2320        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2321       
2322        [torrent setGroupValue: [(NSMenuItem *)sender tag]];
2323    }
2324   
2325    [self applyFilter];
2326    [self updateUI];
2327    [self updateTorrentHistory];
2328}
2329
2330- (void) toggleSpeedLimit: (id) sender
2331{
2332    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2333    [self speedLimitChanged: sender];
2334}
2335
2336- (void) speedLimitChanged: (id) sender
2337{
2338    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2339    [fStatusBar updateSpeedFieldsToolTips];
2340}
2341
2342//dict has been retained
2343- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2344{
2345    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2346
2347    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2348    [fStatusBar updateSpeedFieldsToolTips];
2349   
2350    if (![[dict objectForKey: @"ByUser"] boolValue])
2351        [GrowlApplicationBridge notifyWithTitle: isLimited
2352                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2353                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2354            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2355            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2356   
2357    [dict release];
2358}
2359
2360- (void) setLimitGlobalEnabled: (id) sender
2361{
2362    BOOL upload = [sender menu] == fUploadMenu;
2363    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2364   
2365    [fPrefsController applySpeedSettings: nil];
2366}
2367
2368- (void) setQuickLimitGlobal: (id) sender
2369{
2370    BOOL upload = [sender menu] == fUploadMenu;
2371    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2372    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2373   
2374    [fPrefsController updateLimitFields];
2375    [fPrefsController applySpeedSettings: nil];
2376}
2377
2378- (void) setRatioGlobalEnabled: (id) sender
2379{
2380    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2381   
2382    [fPrefsController applyRatioSetting: nil];
2383}
2384
2385- (void) setQuickRatioGlobal: (id) sender
2386{
2387    [fDefaults setBool: YES forKey: @"RatioCheck"];
2388    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2389   
2390    [fPrefsController updateRatioStopFieldOld];
2391}
2392
2393- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2394{
2395    fSoundPlaying = NO;
2396}
2397
2398- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2399{
2400    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2401    {
2402        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2403            return;
2404       
2405        if (fAutoImportTimer)
2406        {
2407            if ([fAutoImportTimer isValid])
2408                [fAutoImportTimer invalidate];
2409            [fAutoImportTimer release];
2410            fAutoImportTimer = nil;
2411        }
2412       
2413        //check again in 10 seconds in case torrent file wasn't complete
2414        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2415            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2416       
2417        [self checkAutoImportDirectory];
2418    }
2419}
2420
2421- (void) changeAutoImport
2422{
2423    if (fAutoImportTimer)
2424    {
2425        if ([fAutoImportTimer isValid])
2426            [fAutoImportTimer invalidate];
2427        [fAutoImportTimer release];
2428        fAutoImportTimer = nil;
2429    }
2430   
2431    if (fAutoImportedNames)
2432    {
2433        [fAutoImportedNames release];
2434        fAutoImportedNames = nil;
2435    }
2436   
2437    [self checkAutoImportDirectory];
2438}
2439
2440- (void) checkAutoImportDirectory
2441{
2442    NSString * path;
2443    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2444        return;
2445   
2446    path = [path stringByExpandingTildeInPath];
2447   
2448    NSArray * importedNames;
2449    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2450        return;
2451   
2452    //only check files that have not been checked yet
2453    NSMutableArray * newNames = [importedNames mutableCopy];
2454   
2455    if (fAutoImportedNames)
2456        [newNames removeObjectsInArray: fAutoImportedNames];
2457    else
2458        fAutoImportedNames = [[NSMutableArray alloc] init];
2459    [fAutoImportedNames setArray: importedNames];
2460   
2461    for (NSString * file in newNames)
2462    {
2463        if ([file hasPrefix: @"."])
2464            continue;
2465       
2466        NSString * fullFile = [path stringByAppendingPathComponent: file];
2467       
2468        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2469                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2470            continue;
2471       
2472        tr_ctor * ctor = tr_ctorNew(fLib);
2473        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2474       
2475        switch (tr_torrentParse(ctor, NULL))
2476        {
2477            case TR_PARSE_OK:
2478                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2479               
2480                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2481                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2482                    clickContext: nil];
2483                break;
2484           
2485            case TR_PARSE_ERR:
2486                [fAutoImportedNames removeObject: file];
2487                break;
2488           
2489            case TR_PARSE_DUPLICATE: //let's ignore this (but silence a warning)
2490                break;
2491        }
2492       
2493        tr_ctorFree(ctor);
2494    }
2495   
2496    [newNames release];
2497}
2498
2499- (void) beginCreateFile: (NSNotification *) notification
2500{
2501    if (![fDefaults boolForKey: @"AutoImport"])
2502        return;
2503   
2504    NSString * location = [notification object],
2505            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2506   
2507    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2508                                    isEqualToString: [path stringByExpandingTildeInPath]])
2509        [fAutoImportedNames addObject: [location lastPathComponent]];
2510}
2511
2512- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2513{
2514    if (item)
2515        return [[item torrents] count];
2516    else
2517        return [fDisplayedTorrents count];
2518}
2519
2520- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2521{
2522    if (item)
2523        return [[item torrents] objectAtIndex: index];
2524    else
2525        return [fDisplayedTorrents objectAtIndex: index];
2526}
2527
2528- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2529{
2530    return ![item isKindOfClass: [Torrent class]];
2531}
2532
2533- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2534{
2535    if ([item isKindOfClass: [Torrent class]]) {
2536        if (tableColumn)
2537            return nil;
2538        return [item hashString];
2539    }
2540    else
2541    {
2542        NSString * ident = [tableColumn identifier];
2543        if ([ident isEqualToString: @"Group"])
2544        {
2545            NSInteger group = [item groupIndex];
2546            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2547                                : NSLocalizedString(@"No Group", "Group table row");
2548        }
2549        else if ([ident isEqualToString: @"Color"])
2550        {
2551            NSInteger group = [item groupIndex];
2552            return [[GroupsController groups] imageForIndex: group];
2553        }
2554        else if ([ident isEqualToString: @"DL Image"])
2555            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2556        else if ([ident isEqualToString: @"UL Image"])
2557            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2558                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2559        else
2560        {
2561            TorrentGroup * group = (TorrentGroup *)item;
2562           
2563            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2564                return [NSString stringForRatio: [group ratio]];
2565            else
2566            {
2567                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2568                return [NSString stringForSpeed: rate];
2569            }
2570        }
2571    }
2572}
2573
2574- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2575{
2576    //only allow reordering of rows if sorting by order
2577    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2578    {
2579        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2580        for (id torrent in items)
2581        {
2582            if (![torrent isKindOfClass: [Torrent class]])
2583                return NO;
2584           
2585            [indexSet addIndex: [fTableView rowForItem: torrent]];
2586        }
2587       
2588        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2589        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2590        return YES;
2591    }
2592    return NO;
2593}
2594
2595- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2596    proposedChildIndex: (NSInteger) index
2597{
2598    NSPasteboard * pasteboard = [info draggingPasteboard];
2599    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2600    {
2601        if ([fDefaults boolForKey: @"SortByGroup"])
2602        {
2603            if (!item)
2604                return NSDragOperationNone;
2605           
2606            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2607            {
2608                if ([item isKindOfClass: [Torrent class]])
2609                {
2610                    TorrentGroup * group = [fTableView parentForItem: item];
2611                    index = [[group torrents] indexOfObject: item] + 1;
2612                    item = group;
2613                }
2614            }
2615            else
2616            {
2617                if ([item isKindOfClass: [Torrent class]])
2618                    item = [fTableView parentForItem: item];
2619                index = NSOutlineViewDropOnItemIndex;
2620            }
2621        }
2622        else
2623        {
2624            if (item)
2625            {
2626                index = [fTableView rowForItem: item] + 1;
2627                item = nil;
2628            }
2629        }
2630       
2631        [fTableView setDropItem: item dropChildIndex: index];
2632        return NSDragOperationGeneric;
2633    }
2634   
2635    return NSDragOperationNone;
2636}
2637
2638- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2639    childIndex: (NSInteger) newRow
2640{
2641    NSPasteboard * pasteboard = [info draggingPasteboard];
2642    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2643    {
2644        //remember selected rows
2645        NSArray * selectedValues = [fTableView selectedValues];
2646   
2647        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2648       
2649        //get the torrents to move
2650        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2651        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2652            [movingTorrents addObject: [fTableView itemAtRow: i]];
2653       
2654        //reset groups
2655        if (item)
2656        {
2657            //change groups
2658            NSInteger groupValue = [item groupIndex];
2659            for (Torrent * torrent in movingTorrents)
2660            {
2661                //have to reset objects here to avoid weird crash
2662                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2663                [[item torrents] addObject: torrent];
2664               
2665                [torrent setGroupValue: groupValue];
2666            }
2667            //part 2 of avoiding weird crash
2668            [fTableView reloadItem: nil reloadChildren: YES];
2669        }
2670       
2671        //reorder queue order
2672        if (newRow != NSOutlineViewDropOnItemIndex)
2673        {
2674            //find torrent to place under
2675            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2676            Torrent * topTorrent = nil;
2677            for (NSInteger i = newRow-1; i >= 0; i--)
2678            {
2679                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2680                if (![movingTorrents containsObject: tempTorrent])
2681                {
2682                    topTorrent = tempTorrent;
2683                    break;
2684                }
2685            }
2686           
2687            //remove objects to reinsert
2688            [fTorrents removeObjectsInArray: movingTorrents];
2689           
2690            //insert objects at new location
2691            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2692            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2693            for (Torrent * torrent in movingTorrents)
2694                [torrent setQueuePosition: insertIndex++];
2695            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2696        }
2697       
2698        [self applyFilter];
2699        [fTableView selectValues: selectedValues];
2700    }
2701   
2702    return YES;
2703}
2704
2705- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2706{
2707    [self resetInfo];
2708    [[fWindow toolbar] validateVisibleItems];
2709}
2710
2711- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2712{
2713    NSPasteboard * pasteboard = [info draggingPasteboard];
2714    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2715    {
2716        //check if any torrent files can be added
2717        BOOL torrent = NO;
2718        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2719        for (NSString * file in files)
2720        {
2721            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2722                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2723            {
2724                torrent = YES;
2725                tr_ctor * ctor = tr_ctorNew(fLib);
2726                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2727                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2728                {
2729                    if (!fOverlayWindow)
2730                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2731                    [fOverlayWindow setTorrents: files];
2732                   
2733                    return NSDragOperationCopy;
2734                }
2735                tr_ctorFree(ctor);
2736            }
2737        }
2738       
2739        //create a torrent file if a single file
2740        if (!torrent && [files count] == 1)
2741        {
2742            if (!fOverlayWindow)
2743                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2744            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2745           
2746            return NSDragOperationCopy;
2747        }
2748    }
2749    else if ([[pasteboard types] containsObject: NSURLPboardType])
2750    {
2751        if (!fOverlayWindow)
2752            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2753        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2754       
2755        return NSDragOperationCopy;
2756    }
2757    else;
2758   
2759    return NSDragOperationNone;
2760}
2761
2762- (void) draggingExited: (id <NSDraggingInfo>) info
2763{
2764    if (fOverlayWindow)
2765        [fOverlayWindow fadeOut];
2766}
2767
2768- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2769{
2770    if (fOverlayWindow)
2771        [fOverlayWindow fadeOut];
2772   
2773    NSPasteboard * pasteboard = [info draggingPasteboard];
2774    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2775    {
2776        BOOL torrent = NO, accept = YES;
2777       
2778        //create an array of files that can be opened
2779        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2780        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
2781        for (NSString * file in files)
2782        {
2783            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2784                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2785            {
2786                torrent = YES;
2787                tr_ctor * ctor = tr_ctorNew(fLib);
2788                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2789                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2790                    [filesToOpen addObject: file];
2791                tr_ctorFree(ctor);
2792            }
2793        }
2794       
2795        if ([filesToOpen count] > 0)
2796            [self application: NSApp openFiles: filesToOpen];
2797        else
2798        {
2799            if (!torrent && [files count] == 1)
2800                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2801            else
2802                accept = NO;
2803        }
2804       
2805        return accept;
2806    }
2807    else if ([[pasteboard types] containsObject: NSURLPboardType])
2808    {
2809        NSURL * url;
2810        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2811        {
2812            [self openURL: [url absoluteString]];
2813            return YES;
2814        }
2815    }
2816    else;
2817   
2818    return NO;
2819}
2820
2821- (void) toggleSmallView: (id) sender
2822{
2823    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2824    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2825   
2826    [fTableView setUsesAlternatingRowBackgroundColors: !makeSmall];
2827   
2828    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2829   
2830    if ([NSApp isOnLionOrBetter])
2831        [fTableView beginUpdates];
2832    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2833    if ([NSApp isOnLionOrBetter])
2834        [fTableView endUpdates];
2835   
2836    //resize for larger min height if not set to auto size
2837    if (![fDefaults boolForKey: @"AutoSize"])
2838    {
2839        const NSSize contentSize = [[fWindow contentView] frame].size;
2840       
2841        NSSize contentMinSize = [fWindow contentMinSize];
2842        contentMinSize.height = [self minWindowContentSizeAllowed];
2843        [fWindow setContentMinSize: contentMinSize];
2844       
2845        //make sure the window already isn't too small
2846        if (!makeSmall && contentSize.height < contentMinSize.height)
2847        {
2848            NSRect frame = [fWindow frame];
2849            CGFloat heightChange = contentMinSize.height - contentSize.height;
2850            frame.size.height += heightChange;
2851            frame.origin.y -= heightChange;
2852           
2853            [fWindow setFrame: frame display: YES];
2854        }
2855    }
2856    else
2857        [self setWindowSizeToFit];
2858}
2859
2860- (void) togglePiecesBar: (id) sender
2861{
2862    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2863    [fTableView togglePiecesBar];
2864}
2865
2866- (void) toggleAvailabilityBar: (id) sender
2867{
2868    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2869    [fTableView display];
2870}
2871
2872#warning elliminate when 10.7-only
2873- (void) toggleStatusString: (id) sender
2874{
2875    if ([fDefaults boolForKey: @"SmallView"])
2876        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2877    else
2878        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2879   
2880    [fTableView setNeedsDisplay: YES];
2881}
2882
2883- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2884{
2885    NSScrollView * scrollView = [fTableView enclosingScrollView];
2886   
2887    //convert pixels to points
2888    NSRect windowFrame = [fWindow frame];
2889    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2890    windowSize.height += height;
2891   
2892    if (check)
2893    {
2894        //we can't call minSize, since it might be set to the current size (auto size)
2895        const CGFloat minHeight = [self minWindowContentSizeAllowed]
2896                                    + (NSHeight([fWindow frame]) - NSHeight([[fWindow contentView] frame])); //contentView to window
2897       
2898        if (windowSize.height < minHeight)
2899            windowSize.height =minHeight;
2900        else
2901        {
2902            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2903            if (!fStatusBar)
2904                maxSize.height -= STATUS_BAR_HEIGHT;
2905            if (!fFilterBar)
2906                maxSize.height -= FILTER_BAR_HEIGHT;
2907            if (windowSize.height > maxSize.height)
2908                windowSize.height = maxSize.height;
2909        }
2910    }
2911
2912    //convert points to pixels
2913    windowSize = [scrollView convertSize: windowSize toView: nil];
2914
2915    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2916    windowFrame.size.height = windowSize.height;
2917    return windowFrame;
2918}
2919
2920- (void) toggleStatusBar: (id) sender
2921{
2922    const BOOL show = fStatusBar == nil;
2923    [self showStatusBar: show animate: YES];
2924    [fDefaults setBool: show forKey: @"StatusBar"];
2925}
2926
2927//doesn't save shown state
2928- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2929{
2930    const BOOL prevShown = fStatusBar != nil;
2931    if (show == prevShown)
2932        return;
2933   
2934    if (show)
2935    {
2936        fStatusBar = [[StatusBarController alloc] initWithLib: fLib];
2937       
2938        NSView * contentView = [fWindow contentView];
2939        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
2940       
2941        NSRect statusBarFrame = [[fStatusBar view] frame];
2942        statusBarFrame.size.width = windowSize.width;
2943        [[fStatusBar view] setFrame: statusBarFrame];
2944       
2945        [contentView addSubview: [fStatusBar view]];
2946        [[fStatusBar view] setFrameOrigin: NSMakePoint(0.0, NSMaxY([contentView frame]))];
2947    }
2948   
2949    NSRect frame;
2950    CGFloat heightChange = [[fStatusBar view] frame].size.height;
2951    if (!show)
2952        heightChange *= -1;
2953   
2954    //allow bar to show even if not enough room
2955    if (show && ![fDefaults boolForKey: @"AutoSize"])
2956    {
2957        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2958        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2959        if (change < 0.0)
2960        {
2961            frame = [fWindow frame];
2962            frame.size.height += change;
2963            frame.origin.y -= change;
2964            [fWindow setFrame: frame display: NO animate: NO];
2965        }
2966    }
2967   
2968    [self updateUI];
2969   
2970    NSScrollView * scrollView = [fTableView enclosingScrollView];
2971   
2972    //set views to not autoresize
2973    const NSUInteger statsMask = [[fStatusBar view] autoresizingMask];
2974    [[fStatusBar view] setAutoresizingMask: NSViewNotSizable];
2975    NSUInteger filterMask;
2976    if (fFilterBar)
2977    {
2978        filterMask = [[fFilterBar view] autoresizingMask];
2979        [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
2980    }
2981    const NSUInteger scrollMask = [scrollView autoresizingMask];
2982    [scrollView setAutoresizingMask: NSViewNotSizable];
2983   
2984    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2985    [fWindow setFrame: frame display: YES animate: animate];
2986   
2987    //re-enable autoresize
2988    [[fStatusBar view] setAutoresizingMask: statsMask];
2989    if (fFilterBar)
2990        [[fFilterBar view] setAutoresizingMask: filterMask];
2991    [scrollView setAutoresizingMask: scrollMask];
2992   
2993    if (!show)
2994    {
2995        [[fStatusBar view] removeFromSuperviewWithoutNeedingDisplay];
2996        [fStatusBar release];
2997        fStatusBar = nil;
2998    }
2999   
3000    if ([fDefaults boolForKey: @"AutoSize"])
3001        [self setWindowMinMaxToCurrent];
3002    else
3003    {
3004        //change min size
3005        NSSize minSize = [fWindow contentMinSize];
3006        minSize.height += heightChange;
3007        [fWindow setContentMinSize: minSize];
3008    }
3009}
3010
3011- (void) toggleFilterBar: (id) sender
3012{
3013    const BOOL show = fFilterBar == nil;
3014   
3015    [self showFilterBar: show animate: YES];
3016    [fDefaults setBool: show forKey: @"FilterBar"];
3017    [[fWindow toolbar] validateVisibleItems];
3018   
3019    //disable filtering when hiding
3020    if (!show)
3021    {
3022        [[NSUserDefaults standardUserDefaults] setObject: FILTER_NONE forKey: @"Filter"];
3023        [[NSUserDefaults standardUserDefaults] setInteger: GROUP_FILTER_ALL_TAG forKey: @"FilterGroup"];
3024        [[NSUserDefaults standardUserDefaults] removeObjectForKey: @"FilterSearchString"];
3025    }
3026   
3027    [self applyFilter]; //do even if showing to ensure tooltips are updated
3028}
3029
3030//doesn't save shown state
3031- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3032{
3033    const BOOL prevShown = fFilterBar != nil;
3034    if (show == prevShown)
3035        return;
3036   
3037    if (show)
3038    {
3039        fFilterBar = [[FilterBarController alloc] init];
3040       
3041        NSView * contentView = [fWindow contentView];
3042        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
3043       
3044        NSRect filterBarFrame = [[fFilterBar view] frame];
3045        filterBarFrame.size.width = windowSize.width;
3046        [[fFilterBar view] setFrame: filterBarFrame];
3047       
3048        if (fStatusBar)
3049            [contentView addSubview: [fFilterBar view] positioned: NSWindowBelow relativeTo: [fStatusBar view]];
3050        else
3051            [contentView addSubview: [fFilterBar view]];
3052        const CGFloat originY = fStatusBar ? NSMinY([[fStatusBar view] frame]) : NSMaxY([contentView frame]);
3053        [[fFilterBar view] setFrameOrigin: NSMakePoint(0.0, originY)];
3054    }
3055    else
3056        [fWindow makeFirstResponder: fTableView];
3057   
3058    CGFloat heightChange = NSHeight([[fFilterBar view] frame]);
3059    if (!show)
3060        heightChange *= -1;
3061   
3062    //allow bar to show even if not enough room
3063    if (show && ![fDefaults boolForKey: @"AutoSize"])
3064    {
3065        NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3066        const CGFloat change = NSHeight([[fWindow screen] visibleFrame]) - NSHeight(frame);
3067        if (change < 0.0)
3068        {
3069            frame = [fWindow frame];
3070            frame.size.height += change;
3071            frame.origin.y -= change;
3072            [fWindow setFrame: frame display: NO animate: NO];
3073        }
3074    }
3075   
3076    NSScrollView * scrollView = [fTableView enclosingScrollView];
3077
3078    //set views to not autoresize
3079    const NSUInteger filterMask = [[fFilterBar view] autoresizingMask];
3080    const NSUInteger scrollMask = [scrollView autoresizingMask];
3081    [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
3082    [scrollView setAutoresizingMask: NSViewNotSizable];
3083   
3084    const NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3085    [fWindow setFrame: frame display: YES animate: animate];
3086   
3087    //re-enable autoresize
3088    [[fFilterBar view] setAutoresizingMask: filterMask];
3089    [scrollView setAutoresizingMask: scrollMask];
3090   
3091    if (!show)
3092    {
3093        [[fFilterBar view] removeFromSuperviewWithoutNeedingDisplay];
3094        [fFilterBar release];
3095        fFilterBar = nil;
3096    }
3097   
3098    if ([fDefaults boolForKey: @"AutoSize"])
3099        [self setWindowMinMaxToCurrent];
3100    else
3101    {
3102        //change min size
3103        NSSize minSize = [fWindow contentMinSize];
3104        minSize.height += heightChange;
3105        [fWindow setContentMinSize: minSize];
3106    }
3107}
3108
3109- (void) focusFilterField
3110{
3111    if (!fFilterBar)
3112        [self toggleFilterBar: self];
3113    [fFilterBar focusSearchField];
3114}
3115
3116- (BOOL) acceptsPreviewPanelControl: (QLPreviewPanel *) panel
3117{
3118    return !fQuitting;
3119}
3120
3121- (void) beginPreviewPanelControl: (QLPreviewPanel *) panel
3122{
3123    fPreviewPanel = [panel retain];
3124    [fPreviewPanel setDelegate: self];
3125    [fPreviewPanel setDataSource: self];
3126}
3127
3128- (void) endPreviewPanelControl: (QLPreviewPanel *) panel
3129{
3130    [fPreviewPanel release];
3131    fPreviewPanel = nil;
3132}
3133
3134- (NSArray *) quickLookableTorrents
3135{
3136    NSArray * selectedTorrents = [fTableView selectedTorrents];
3137    NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3138   
3139    for (Torrent * torrent in selectedTorrents)
3140        if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation])
3141            [qlArray addObject: torrent];
3142   
3143    return qlArray;
3144}
3145
3146- (NSInteger) numberOfPreviewItemsInPreviewPanel: (QLPreviewPanel *) panel
3147{
3148    if ([fInfoController canQuickLook])
3149        return [[fInfoController quickLookURLs] count];
3150    else
3151        return [[self quickLookableTorrents] count];
3152}
3153
3154- (id <QLPreviewItem>) previewPanel: (QLPreviewPanel *) panel previewItemAtIndex: (NSInteger) index
3155{
3156    if ([fInfoController canQuickLook])
3157        return [[fInfoController quickLookURLs] objectAtIndex: index];
3158    else
3159        return [[self quickLookableTorrents] objectAtIndex: index];
3160}
3161
3162- (BOOL) previewPanel: (QLPreviewPanel *) panel handleEvent: (NSEvent *) event
3163{
3164    /*if ([event type] == NSKeyDown)
3165    {
3166        [super keyDown: event];
3167        return YES;
3168    }*/
3169   
3170    return NO;
3171}
3172
3173- (NSRect) previewPanel: (QLPreviewPanel *) panel sourceFrameOnScreenForPreviewItem: (id <QLPreviewItem>) item
3174{
3175    if ([fInfoController canQuickLook])
3176        return [fInfoController quickLookSourceFrameForPreviewItem: item];
3177    else
3178    {
3179        if (![fWindow isVisible])
3180            return NSZeroRect;
3181       
3182        const NSInteger row = [fTableView rowForItem: item];
3183        if (row == -1)
3184            return NSZeroRect;
3185       
3186        NSRect frame = [fTableView iconRectForRow: row];
3187       
3188        if (!NSIntersectsRect([fTableView visibleRect], frame))
3189            return NSZeroRect;
3190       
3191        frame.origin = [fTableView convertPoint: frame.origin toView: nil];
3192        frame.origin = [fWindow convertBaseToScreen: frame.origin];
3193        frame.origin.y -= frame.size.height;
3194        return frame;
3195    }
3196}
3197
3198- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3199{
3200    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3201   
3202    NSButton * button = [[NSButton alloc] init];
3203    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3204    [button setStringValue: @""];
3205   
3206    [item setView: button];
3207    [button release];
3208   
3209    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3210    [item setMinSize: buttonSize];
3211    [item setMaxSize: buttonSize];
3212   
3213    return [item autorelease];
3214}
3215
3216- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3217{
3218    if ([ident isEqualToString: TOOLBAR_CREATE])
3219    {
3220        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3221       
3222        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3223        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3224        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3225        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3226        [item setTarget: self];
3227        [item setAction: @selector(createFile:)];
3228        [item setAutovalidates: NO];
3229       
3230        return item;
3231    }
3232    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3233    {
3234        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3235       
3236        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3237        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3238        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3239        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3240        [item setTarget: self];
3241        [item setAction: @selector(openShowSheet:)];
3242        [item setAutovalidates: NO];
3243       
3244        return item;
3245    }
3246    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3247    {
3248        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3249       
3250        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3251        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3252        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3253        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3254        [item setTarget: self];
3255        [item setAction: @selector(openURLShowSheet:)];
3256        [item setAutovalidates: NO];
3257       
3258        return item;
3259    }
3260    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3261    {
3262        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3263       
3264        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3265        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3266        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3267        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3268        [item setTarget: self];
3269        [item setAction: @selector(removeNoDelete:)];
3270        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3271       
3272        return item;
3273    }
3274    else if ([ident isEqualToString: TOOLBAR_INFO])
3275    {
3276        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3277        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3278       
3279        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3280        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3281        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3282        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3283        [item setTarget: self];
3284        [item setAction: @selector(showInfo:)];
3285       
3286        return item;
3287    }
3288    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3289    {
3290        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3291       
3292        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3293        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3294        [groupItem setView: segmentedControl];
3295        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3296       
3297        [segmentedControl setSegmentCount: 2];
3298        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3299       
3300        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3301        [groupItem setMinSize: groupSize];
3302        [groupItem setMaxSize: groupSize];
3303       
3304        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3305        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3306        [groupItem setTarget: self];
3307        [groupItem setAction: @selector(allToolbarClicked:)];
3308       
3309        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3310       
3311        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3312        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3313        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3314                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3315       
3316        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3317        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3318        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3319                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3320       
3321        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3322                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3323       
3324        [segmentedControl release];
3325       
3326        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3327       
3328        return [groupItem autorelease];
3329    }
3330    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3331    {
3332        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3333       
3334        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3335        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3336        [groupItem setView: segmentedControl];
3337        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3338       
3339        [segmentedControl setSegmentCount: 2];
3340        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3341       
3342        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3343        [groupItem setMinSize: groupSize];
3344        [groupItem setMaxSize: groupSize];
3345       
3346        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3347        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3348        [groupItem setTarget: self];
3349        [groupItem setAction: @selector(selectedToolbarClicked:)];
3350       
3351        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3352       
3353        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3354        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3355        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3356                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3357       
3358        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3359        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3360        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3361                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3362       
3363        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3364                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3365       
3366        [segmentedControl release];
3367       
3368        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3369       
3370        return [groupItem autorelease];
3371    }
3372    else if ([ident isEqualToString: TOOLBAR_FILTER])
3373    {
3374        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3375        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3376       
3377        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3378        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3379        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3380        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3381        [item setTarget: self];
3382        [item setAction: @selector(toggleFilterBar:)];
3383       
3384        return item;
3385    }
3386    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3387    {
3388        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3389        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3390       
3391        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3392        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3393        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3394        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3395        [item setTarget: self];
3396        [item setAction: @selector(toggleQuickLook:)];
3397        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow];
3398       
3399        return item;
3400    }
3401    else
3402        return nil;
3403}
3404
3405- (void) allToolbarClicked: (id) sender
3406{
3407    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3408                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag];
3409    switch (tagValue)
3410    {
3411        case TOOLBAR_PAUSE_TAG:
3412            [self stopAllTorrents: sender];
3413            break;
3414        case TOOLBAR_RESUME_TAG:
3415            [self resumeAllTorrents: sender];
3416            break;
3417    }
3418}
3419
3420- (void) selectedToolbarClicked: (id) sender
3421{
3422    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3423                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [(NSControl *)sender tag];
3424    switch (tagValue)
3425    {
3426        case TOOLBAR_PAUSE_TAG:
3427            [self stopSelectedTorrents: sender];
3428            break;
3429        case TOOLBAR_RESUME_TAG:
3430            [self resumeSelectedTorrents: sender];
3431            break;
3432    }
3433}
3434
3435- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3436{
3437    return [NSArray arrayWithObjects:
3438            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3439            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3440            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3441            NSToolbarSeparatorItemIdentifier,
3442            NSToolbarSpaceItemIdentifier,
3443            NSToolbarFlexibleSpaceItemIdentifier,
3444            NSToolbarCustomizeToolbarItemIdentifier, nil];
3445}
3446
3447- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3448{
3449    return [NSArray arrayWithObjects:
3450            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSpaceItemIdentifier,
3451            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3452            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3453}
3454
3455- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3456{
3457    NSString * ident = [toolbarItem itemIdentifier];
3458   
3459    //enable remove item
3460    if ([ident isEqualToString: TOOLBAR_REMOVE])
3461        return [fTableView numberOfSelectedRows] > 0;
3462
3463    //enable pause all item
3464    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3465    {
3466        for (Torrent * torrent in fTorrents)
3467            if ([torrent isActive] || [torrent waitingToStart])
3468                return YES;
3469        return NO;
3470    }
3471
3472    //enable resume all item
3473    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3474    {
3475        for (Torrent * torrent in fTorrents)
3476            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
3477                return YES;
3478        return NO;
3479    }
3480
3481    //enable pause item
3482    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3483    {
3484        for (Torrent * torrent in [fTableView selectedTorrents])
3485            if ([torrent isActive] || [torrent waitingToStart])
3486                return YES;
3487        return NO;
3488    }
3489   
3490    //enable resume item
3491    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3492    {
3493        for (Torrent * torrent in [fTableView selectedTorrents])
3494            if (![torrent isActive] && ![torrent waitingToStart])
3495                return YES;
3496        return NO;
3497    }
3498   
3499    //set info item
3500    if ([ident isEqualToString: TOOLBAR_INFO])
3501    {
3502        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3503        return YES;
3504    }
3505   
3506    //set filter item
3507    if ([ident isEqualToString: TOOLBAR_FILTER])
3508    {
3509        [(NSButton *)[toolbarItem view] setState: fFilterBar != nil];
3510        return YES;
3511    }
3512   
3513    //set quick look item
3514    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3515    {
3516        [(NSButton *)[toolbarItem view] setState: [QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible]];
3517        return YES;
3518    }
3519
3520    return YES;
3521}
3522
3523- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3524{
3525    SEL action = [menuItem action];
3526   
3527    if (action == @selector(toggleSpeedLimit:))
3528    {
3529        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3530        return YES;
3531    }
3532   
3533    //only enable some items if it is in a context menu or the window is useable
3534    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3535
3536    //enable open items
3537    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3538        return [fWindow attachedSheet] == nil;
3539   
3540    //enable sort options
3541    if (action == @selector(setSort:))
3542    {
3543        NSString * sortType;
3544        switch ([menuItem tag])
3545        {
3546            case SORT_ORDER_TAG:
3547                sortType = SORT_ORDER;
3548                break;
3549            case SORT_DATE_TAG:
3550                sortType = SORT_DATE;
3551                break;
3552            case SORT_NAME_TAG:
3553                sortType = SORT_NAME;
3554                break;
3555            case SORT_PROGRESS_TAG:
3556                sortType = SORT_PROGRESS;
3557                break;
3558            case SORT_STATE_TAG:
3559                sortType = SORT_STATE;
3560                break;
3561            case SORT_TRACKER_TAG:
3562                sortType = SORT_TRACKER;
3563                break;
3564            case SORT_ACTIVITY_TAG:
3565                sortType = SORT_ACTIVITY;
3566                break;
3567            case SORT_SIZE_TAG:
3568                sortType = SORT_SIZE;
3569                break;
3570            default:
3571                NSAssert1(NO, @"Unknown sort tag received: %d", [menuItem tag]);
3572        }
3573       
3574        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3575        return [fWindow isVisible];
3576    }
3577   
3578    if (action == @selector(setGroup:))
3579    {
3580        BOOL checked = NO;
3581       
3582        NSInteger index = [menuItem tag];
3583        for (Torrent * torrent in [fTableView selectedTorrents])
3584            if (index == [torrent groupValue])
3585            {
3586                checked = YES;
3587                break;
3588            }
3589       
3590        [menuItem setState: checked ? NSOnState : NSOffState];
3591        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3592    }
3593   
3594    if (action == @selector(toggleSmallView:))
3595    {
3596        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3597        return [fWindow isVisible];
3598    }
3599   
3600    if (action == @selector(togglePiecesBar:))
3601    {
3602        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3603        return [fWindow isVisible];
3604    }
3605   
3606    #warning remove when menu is removed (10.7-only)
3607    if (action == @selector(toggleStatusString:))
3608    {
3609        if ([fDefaults boolForKey: @"SmallView"])
3610        {
3611            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3612            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3613        }
3614        else
3615        {
3616            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3617            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3618        }
3619       
3620        return [fWindow isVisible];
3621    }
3622   
3623    if (action == @selector(toggleAvailabilityBar:))
3624    {
3625        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3626        return [fWindow isVisible];
3627    }
3628   
3629    if (action == @selector(setLimitGlobalEnabled:))
3630    {
3631        BOOL upload = [menuItem menu] == fUploadMenu;
3632        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3633        if (limit)
3634            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3635                                    "Action menu -> upload/download limit"),
3636                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3637       
3638        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3639        return YES;
3640    }
3641   
3642    if (action == @selector(setRatioGlobalEnabled:))
3643    {
3644        BOOL check = menuItem == fCheckRatioItem;
3645        if (check)
3646            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3647                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3648       
3649        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3650        return YES;
3651    }
3652
3653    //enable show info
3654    if (action == @selector(showInfo:))
3655    {
3656        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3657                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3658        [menuItem setTitle: title];
3659
3660        return YES;
3661    }
3662   
3663    //enable prev/next inspector tab
3664    if (action == @selector(setInfoTab:))
3665        return [[fInfoController window] isVisible];
3666   
3667    //enable toggle status bar
3668    if (action == @selector(toggleStatusBar:))
3669    {
3670        NSString * title = !fStatusBar ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3671                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3672        [menuItem setTitle: title];
3673
3674        return [fWindow isVisible];
3675    }
3676   
3677    //enable toggle filter bar
3678    if (action == @selector(toggleFilterBar:))
3679    {
3680        NSString * title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3681                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3682        [menuItem setTitle: title];
3683
3684        return [fWindow isVisible];
3685    }
3686   
3687    //enable prev/next filter button
3688    if (action == @selector(switchFilter:))
3689        return [fWindow isVisible] && fFilterBar;
3690   
3691    //enable reveal in finder
3692    if (action == @selector(revealFile:))
3693        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3694
3695    //enable remove items
3696    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
3697    {
3698        BOOL warning = NO;
3699       
3700        for (Torrent * torrent in [fTableView selectedTorrents])
3701        {
3702            if ([torrent isActive])
3703            {
3704                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
3705                {
3706                    warning = YES;
3707                    break;
3708                }
3709            }
3710        }
3711   
3712        //append or remove ellipsis when needed
3713        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3714        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3715        {
3716            if (![title hasSuffix: ellipsis])
3717                [menuItem setTitle: [title stringByAppendingEllipsis]];
3718        }
3719        else
3720        {
3721            if ([title hasSuffix: ellipsis])
3722                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3723        }
3724       
3725        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3726    }
3727   
3728    //remove all completed transfers item
3729    if (action == @selector(clearCompleted:))
3730    {
3731        //append or remove ellipsis when needed
3732        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3733        if ([fDefaults boolForKey: @"WarningRemoveCompleted"])
3734        {
3735            if (![title hasSuffix: ellipsis])
3736                [menuItem setTitle: [title stringByAppendingEllipsis]];
3737        }
3738        else
3739        {
3740            if ([title hasSuffix: ellipsis])
3741                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3742        }
3743       
3744        for (Torrent * torrent in fTorrents)
3745            if ([torrent isFinishedSeeding])
3746                return YES;
3747        return NO;
3748    }
3749
3750    //enable pause all item
3751    if (action == @selector(stopAllTorrents:))
3752    {
3753        for (Torrent * torrent in fTorrents)
3754            if ([torrent isActive] || [torrent waitingToStart])
3755                return YES;
3756        return NO;
3757    }
3758   
3759    //enable resume all item
3760    if (action == @selector(resumeAllTorrents:))
3761    {
3762        for (Torrent * torrent in fTorrents)
3763            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
3764                return YES;
3765        return NO;
3766    }
3767   
3768    //enable resume all waiting item
3769    if (action == @selector(resumeWaitingTorrents:))
3770    {
3771        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3772            return NO;
3773   
3774        for (Torrent * torrent in fTorrents)
3775            if ([torrent waitingToStart])
3776                return YES;
3777        return NO;
3778    }
3779   
3780    //enable resume selected waiting item
3781    if (action == @selector(resumeSelectedTorrentsNoWait:))
3782    {
3783        if (!canUseTable)
3784            return NO;
3785       
3786        for (Torrent * torrent in [fTableView selectedTorrents])
3787            if (![torrent isActive])
3788                return YES;
3789        return NO;
3790    }
3791
3792    //enable pause item
3793    if (action == @selector(stopSelectedTorrents:))
3794    {
3795        if (!canUseTable)
3796            return NO;
3797   
3798        for (Torrent * torrent in [fTableView selectedTorrents])
3799            if ([torrent isActive] || [torrent waitingToStart])
3800                return YES;
3801        return NO;
3802    }
3803   
3804    //enable resume item
3805    if (action == @selector(resumeSelectedTorrents:))
3806    {
3807        if (!canUseTable)
3808            return NO;
3809   
3810        for (Torrent * torrent in [fTableView selectedTorrents])
3811            if (![torrent isActive] && ![torrent waitingToStart])
3812                return YES;
3813        return NO;
3814    }
3815   
3816    //enable manual announce item
3817    if (action == @selector(announceSelectedTorrents:))
3818    {
3819        if (!canUseTable)
3820            return NO;
3821       
3822        for (Torrent * torrent in [fTableView selectedTorrents])
3823            if ([torrent canManualAnnounce])
3824                return YES;
3825        return NO;
3826    }
3827   
3828    //enable reset cache item
3829    if (action == @selector(verifySelectedTorrents:))
3830    {
3831        if (!canUseTable)
3832            return NO;
3833           
3834        for (Torrent * torrent in [fTableView selectedTorrents])
3835            if (![torrent isMagnet])
3836                return YES;
3837        return NO;
3838    }
3839   
3840    //enable move torrent file item
3841    if (action == @selector(moveDataFilesSelected:))
3842        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3843   
3844    //enable copy torrent file item
3845    if (action == @selector(copyTorrentFiles:))
3846    {
3847        if (!canUseTable)
3848            return NO;
3849       
3850        for (Torrent * torrent in [fTableView selectedTorrents])
3851            if (![torrent isMagnet])
3852                return YES;
3853        return NO;
3854    }
3855   
3856    //enable copy torrent file item
3857    if (action == @selector(copyMagnetLinks:))
3858        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3859   
3860    //enable reverse sort item
3861    if (action == @selector(setSortReverse:))
3862    {
3863        const BOOL isReverse = [menuItem tag] == SORT_DESC_TAG;
3864        [menuItem setState: (isReverse == [fDefaults boolForKey: @"SortReverse"]) ? NSOnState : NSOffState];
3865        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3866    }
3867   
3868    //enable group sort item
3869    if (action == @selector(setSortByGroup:))
3870    {
3871        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3872        return YES;
3873    }
3874   
3875    if (action == @selector(toggleQuickLook:))
3876    {
3877        const BOOL visible =[QLPreviewPanel sharedPreviewPanelExists] && [[QLPreviewPanel sharedPreviewPanel] isVisible];
3878        //text consistent with Finder
3879        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
3880                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
3881        [menuItem setTitle: title];
3882       
3883        return YES;
3884    }
3885   
3886    return YES;
3887}
3888
3889- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3890{
3891    switch (messageType)
3892    {
3893        case kIOMessageSystemWillSleep:
3894            //if there are any running transfers, wait 15 seconds for them to stop
3895            for (Torrent * torrent in fTorrents)
3896                if ([torrent isActive])
3897                {
3898                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3899                    for (Torrent * torrent in fTorrents)
3900                        [torrent sleep];
3901                    sleep(15);
3902                    break;
3903                }
3904
3905            IOAllowPowerChange(fRootPort, (long) messageArgument);
3906            break;
3907
3908        case kIOMessageCanSystemSleep:
3909            if ([fDefaults boolForKey: @"SleepPrevent"])
3910            {
3911                //prevent idle sleep unless no torrents are active
3912                for (Torrent * torrent in fTorrents)
3913                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3914                    {
3915                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3916                        return;
3917                    }
3918            }
3919           
3920            IOAllowPowerChange(fRootPort, (long) messageArgument);
3921            break;
3922
3923        case kIOMessageSystemHasPoweredOn:
3924            //resume sleeping transfers after we wake up
3925            for (Torrent * torrent in fTorrents)
3926                [torrent wakeUp];
3927            break;
3928    }
3929}
3930
3931- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3932{
3933    if (fQuitting)
3934        return nil;
3935   
3936    NSInteger seeding = 0, downloading = 0;
3937    for (Torrent * torrent in fTorrents)
3938    {
3939        if ([torrent isSeeding])
3940            seeding++;
3941        else if ([torrent isActive])
3942            downloading++;
3943        else;
3944    }
3945   
3946    NSMenu * menu = [[NSMenu alloc] init];
3947   
3948    if (seeding > 0)
3949    {
3950        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3951        [menu addItemWithTitle: title action: nil keyEquivalent: @""];
3952    }
3953   
3954    if (downloading > 0)
3955    {
3956        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3957        [menu addItemWithTitle: title action: nil keyEquivalent: @""];
3958    }
3959   
3960    if (seeding > 0 || downloading > 0)
3961        [menu addItem: [NSMenuItem separatorItem]];
3962   
3963    [menu addItemWithTitle: NSLocalizedString(@"Pause All", "Dock item") action: @selector(stopAllTorrents:) keyEquivalent: @""];
3964    [menu addItemWithTitle: NSLocalizedString(@"Resume All", "Dock item") action: @selector(resumeAllTorrents:) keyEquivalent: @""];
3965    [menu addItem: [NSMenuItem separatorItem]];
3966    [menu addItemWithTitle: NSLocalizedString(@"Speed Limit", "Dock item") action: @selector(toggleSpeedLimit:) keyEquivalent: @""];
3967   
3968    return [menu autorelease];
3969}
3970
3971- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3972{
3973    //if auto size is enabled, the current frame shouldn't need to change
3974    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3975   
3976    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3977    return frame;
3978}
3979
3980- (void) setWindowSizeToFit
3981{
3982    if ([fDefaults boolForKey: @"AutoSize"])
3983    {
3984        NSScrollView * scrollView = [fTableView enclosingScrollView];
3985       
3986        [scrollView setHasVerticalScroller: NO];
3987        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3988        [scrollView setHasVerticalScroller: YES];
3989       
3990        [self setWindowMinMaxToCurrent];
3991    }
3992}
3993
3994- (NSRect) sizedWindowFrame
3995{
3996    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3997                    ? [fDisplayedTorrents count] : 0;
3998   
3999    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4000                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4001                        - NSHeight([[fTableView enclosingScrollView] frame]);
4002   
4003    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4004}
4005
4006- (void) updateForAutoSize
4007{
4008    if ([fDefaults boolForKey: @"AutoSize"])
4009        [self setWindowSizeToFit];
4010    else
4011    {
4012        NSSize contentMinSize = [fWindow contentMinSize];
4013        contentMinSize.height = [self minWindowContentSizeAllowed];
4014       
4015        [fWindow setContentMinSize: contentMinSize];
4016       
4017        NSSize contentMaxSize = [fWindow contentMaxSize];
4018        contentMaxSize.height = FLT_MAX;
4019        [fWindow setContentMaxSize: contentMaxSize];
4020    }
4021}
4022
4023- (void) setWindowMinMaxToCurrent
4024{
4025    const CGFloat height = NSHeight([[fWindow contentView] frame]);
4026   
4027    NSSize minSize = [fWindow contentMinSize],
4028            maxSize = [fWindow contentMaxSize];
4029    minSize.height = height;
4030    maxSize.height = height;
4031   
4032    [fWindow setContentMinSize: minSize];
4033    [fWindow setContentMaxSize: maxSize];
4034}
4035
4036- (CGFloat) minWindowContentSizeAllowed
4037{
4038    CGFloat contentMinHeight = NSHeight([[fWindow contentView] frame]) - NSHeight([[fTableView enclosingScrollView] frame])
4039                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
4040    return contentMinHeight;
4041}
4042
4043- (void) updateForExpandCollape
4044{
4045    [self setWindowSizeToFit];
4046    [self setBottomCountText: YES];
4047}
4048
4049- (void) showMainWindow: (id) sender
4050{
4051    [fWindow makeKeyAndOrderFront: nil];
4052}
4053
4054- (void) windowDidBecomeMain: (NSNotification *) notification
4055{
4056    [fBadger clearCompleted];
4057    [self updateUI];
4058}
4059
4060- (void) applicationWillUnhide: (NSNotification *) notification
4061{
4062    [self updateUI];
4063}
4064
4065- (void) toggleQuickLook: (id) sender
4066{
4067    if ([[QLPreviewPanel sharedPreviewPanel] isVisible])
4068        [[QLPreviewPanel sharedPreviewPanel] orderOut: nil];
4069    else
4070        [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront: nil];
4071}
4072
4073- (void) linkHomepage: (id) sender
4074{
4075    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4076}
4077
4078- (void) linkForums: (id) sender
4079{
4080    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4081}
4082
4083- (void) linkTrac: (id) sender
4084{
4085    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4086}
4087
4088- (void) linkDonate: (id) sender
4089{
4090    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4091}
4092
4093- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4094{
4095    fQuitRequested = YES;
4096}
4097
4098- (NSDictionary *) registrationDictionaryForGrowl
4099{
4100    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4101                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4102    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4103                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4104}
4105
4106- (void) growlNotificationWasClicked: (id) clickContext
4107{
4108    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4109        return;
4110   
4111    NSString * type = [clickContext objectForKey: @"Type"], * location;
4112    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4113            && (location = [clickContext objectForKey: @"Location"]))
4114    {
4115        NSURL * file = [NSURL fileURLWithPath: location];
4116        [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4117    }
4118}
4119
4120- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4121{
4122    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4123   
4124    //get the torrent
4125    Torrent * torrent = nil;
4126    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED && type != TR_RPC_SESSION_CLOSE))
4127    {
4128        for (torrent in fTorrents)
4129            if (torrentStruct == [torrent torrentStruct])
4130            {
4131                [torrent retain];
4132                break;
4133            }
4134       
4135        if (!torrent)
4136        {
4137            [pool drain];
4138           
4139            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4140            return;
4141        }
4142    }
4143   
4144    switch (type)
4145    {
4146        case TR_RPC_TORRENT_ADDED:
4147            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4148                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4149            break;
4150       
4151        case TR_RPC_TORRENT_STARTED:
4152        case TR_RPC_TORRENT_STOPPED:
4153            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4154            break;
4155       
4156        case TR_RPC_TORRENT_REMOVING:
4157            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4158            break;
4159       
4160        case TR_RPC_TORRENT_TRASHING:
4161            [self performSelectorOnMainThread: @selector(rpcRemoveTorrentDeleteData:) withObject: torrent waitUntilDone: NO];
4162            break;
4163       
4164        case TR_RPC_TORRENT_CHANGED:
4165            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4166            break;
4167       
4168        case TR_RPC_TORRENT_MOVED:
4169            [self performSelectorOnMainThread: @selector(rpcMovedTorrent:) withObject: torrent waitUntilDone: NO];
4170            break;
4171       
4172        case TR_RPC_SESSION_QUEUE_POSITIONS_CHANGED:
4173            [self performSelectorOnMainThread: @selector(rpcUpdateQueue) withObject: nil waitUntilDone: NO];
4174            break;
4175       
4176        case TR_RPC_SESSION_CHANGED:
4177            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4178            break;
4179       
4180        case TR_RPC_SESSION_CLOSE:
4181            fQuitRequested = YES;
4182            [NSApp performSelectorOnMainThread: @selector(terminate:) withObject: self waitUntilDone: NO];
4183            break;
4184       
4185        default:
4186            NSAssert1(NO, @"Unknown RPC command received: %d", type);
4187            [torrent release];
4188    }
4189   
4190    [pool drain];
4191}
4192
4193- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4194{
4195    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4196    [torrentStructPtr release];
4197   
4198    NSString * location = nil;
4199    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4200        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4201   
4202    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4203   
4204    //change the location if the group calls for it (this has to wait until after the torrent is created)
4205    if ([[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
4206    {
4207        location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
4208        [torrent changeDownloadFolderBeforeUsing: location];
4209    }
4210   
4211    [torrent update];
4212    [fTorrents addObject: torrent];
4213    [torrent release];
4214   
4215    [self fullUpdateUI];
4216}
4217
4218- (void) rpcRemoveTorrent: (Torrent *) torrent
4219{
4220    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4221    [torrent release];
4222}
4223
4224- (void) rpcRemoveTorrentDeleteData: (Torrent *) torrent
4225{
4226    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: YES];
4227    [torrent release];
4228}
4229
4230- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4231{
4232    [torrent update];
4233    [torrent release];
4234   
4235    [self updateUI];
4236    [self applyFilter];
4237    [self updateTorrentHistory];
4238}
4239
4240- (void) rpcChangedTorrent: (Torrent *) torrent
4241{
4242    [torrent update];
4243   
4244    if ([[fTableView selectedTorrents] containsObject: torrent])
4245    {
4246        [fInfoController updateInfoStats]; //this will reload the file table
4247        [fInfoController updateOptions];
4248    }
4249   
4250    [torrent release];
4251}
4252
4253- (void) rpcMovedTorrent: (Torrent *) torrent
4254{
4255    [torrent update];
4256    [torrent updateTimeMachineExclude];
4257   
4258    if ([[fTableView selectedTorrents] containsObject: torrent])
4259        [fInfoController updateInfoStats];
4260   
4261    [torrent release];
4262}
4263
4264- (void) rpcUpdateQueue
4265{
4266    for (Torrent * torrent in fTorrents)
4267        [torrent update];
4268   
4269    NSArray * selectedValues = [fTableView selectedValues];
4270   
4271    NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey: @"queuePosition" ascending: YES];
4272    NSArray * descriptors = [NSArray arrayWithObject: descriptor];
4273   
4274    [fTorrents sortUsingDescriptors: descriptors];
4275   
4276    [self fullUpdateUI];
4277   
4278    [fTableView selectValues: selectedValues];
4279}
4280
4281@end
Note: See TracBrowser for help on using the repository browser.