source: trunk/macosx/Controller.m @ 12115

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

hard-code the status bar and filter bar height, so that the max window size factors in their height

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