source: trunk/macosx/Controller.m @ 12118

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

add a button to the bottom-left of the main window to clean up all completed transfers

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