source: trunk/macosx/Controller.m @ 12499

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

disabling alternating row colors in minimal view

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