source: trunk/macosx/Controller.m @ 13108

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

eliminate all warnings by switching NSOpenPanel/NSSavePanels to use completion handler blocks

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