source: trunk/macosx/Controller.m @ 11999

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

silence a warning

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