source: trunk/macosx/Controller.m @ 12538

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

#4346 items in the status bar aren't set at launch

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