source: trunk/macosx/Controller.m @ 12005

Last change on this file since 12005 was 12005, checked in by livings124, 11 years ago

slightly simplify filter code

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