source: trunk/macosx/Controller.m @ 12943

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

remove most instances of deprecated filename and filenames methods

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