source: trunk/macosx/Controller.m @ 13096

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

#3948 avoid a crash when closing magnet link windows

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