source: trunk/macosx/Controller.m @ 12045

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

store secondsDownloading and secondsSeeding as ints instead of time_t

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