source: trunk/macosx/Controller.m @ 11997

Last change on this file since 11997 was 11997, checked in by livings124, 12 years ago

make sure filter buttons' tooltips are updated when the bar is shown

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