source: trunk/macosx/Controller.m @ 13122

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

remove accidental line removal in r13121

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