source: trunk/macosx/Controller.m @ 12597

Last change on this file since 12597 was 12597, checked in by livings124, 10 years ago

#4393 Remove "Open Recent" menu item and list of recent torrent files

  • Property svn:keywords set to Date Rev Author Id
File size: 159.1 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 12597 2011-07-27 01:32:46Z 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 "GlobalOptionsPopoverViewController.h"
44#import "ButtonToolbarItem.h"
45#import "GroupToolbarItem.h"
46#import "ToolbarSegmentedCell.h"
47#import "BlocklistDownloader.h"
48#import "StatusBarController.h"
49#import "FilterBarController.h"
50#import "BonjourController.h"
51#import "Badger.h"
52#import "DragOverlayWindow.h"
53#import "NSApplicationAdditions.h"
54#import "NSStringAdditions.h"
55#import "ExpandedPathToPathTransformer.h"
56#import "ExpandedPathToIconTransformer.h"
57
58#import "transmission.h"
59#import "bencode.h"
60#import "utils.h"
61
62#import "UKKQueue.h"
63#import <Sparkle/Sparkle.h>
64
65#define TOOLBAR_CREATE                  @"Toolbar Create"
66#define TOOLBAR_OPEN_FILE               @"Toolbar Open"
67#define TOOLBAR_OPEN_WEB                @"Toolbar Open Web"
68#define TOOLBAR_REMOVE                  @"Toolbar Remove"
69#define TOOLBAR_INFO                    @"Toolbar Info"
70#define TOOLBAR_PAUSE_ALL               @"Toolbar Pause All"
71#define TOOLBAR_RESUME_ALL              @"Toolbar Resume All"
72#define TOOLBAR_PAUSE_RESUME_ALL        @"Toolbar Pause / Resume All"
73#define TOOLBAR_PAUSE_SELECTED          @"Toolbar Pause Selected"
74#define TOOLBAR_RESUME_SELECTED         @"Toolbar Resume Selected"
75#define TOOLBAR_PAUSE_RESUME_SELECTED   @"Toolbar Pause / Resume Selected"
76#define TOOLBAR_FILTER                  @"Toolbar Toggle Filter"
77#define TOOLBAR_QUICKLOOK               @"Toolbar QuickLook"
78
79typedef enum
80{
81    TOOLBAR_PAUSE_TAG = 0,
82    TOOLBAR_RESUME_TAG = 1
83} toolbarGroupTag;
84
85#define SORT_DATE       @"Date"
86#define SORT_NAME       @"Name"
87#define SORT_STATE      @"State"
88#define SORT_PROGRESS   @"Progress"
89#define SORT_TRACKER    @"Tracker"
90#define SORT_ORDER      @"Order"
91#define SORT_ACTIVITY   @"Activity"
92#define SORT_SIZE       @"Size"
93
94typedef enum
95{
96    SORT_ORDER_TAG = 0,
97    SORT_DATE_TAG = 1,
98    SORT_NAME_TAG = 2,
99    SORT_PROGRESS_TAG = 3,
100    SORT_STATE_TAG = 4,
101    SORT_TRACKER_TAG = 5,
102    SORT_ACTIVITY_TAG = 6,
103    SORT_SIZE_TAG = 7
104} sortTag;
105
106typedef enum
107{
108    SORT_ASC_TAG = 0,
109    SORT_DESC_TAG = 1
110} sortOrderTag;
111
112#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
113#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
114#define GROWL_AUTO_ADD          @"Torrent Auto Added"
115#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
116
117#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
118
119#define ROW_HEIGHT_REGULAR      62.0
120#define ROW_HEIGHT_SMALL        22.0
121#define WINDOW_REGULAR_WIDTH    468.0
122
123#define STATUS_BAR_HEIGHT   21.0
124#define FILTER_BAR_HEIGHT   23.0
125
126#define UPDATE_UI_SECONDS   1.0
127
128#define DOCK_SEEDING_TAG        101
129#define DOCK_DOWNLOADING_TAG    102
130
131#define TRANSFER_PLIST  @"/Library/Application Support/Transmission/Transfers.plist"
132
133#define WEBSITE_URL @"http://www.transmissionbt.com/"
134#define FORUM_URL   @"http://forum.transmissionbt.com/"
135#define TRAC_URL    @"http://trac.transmissionbt.com/"
136#define DONATE_URL  @"http://www.transmissionbt.com/donate.php"
137
138#define DONATE_NAG_TIME (60 * 60 * 24 * 7)
139
140static void altSpeedToggledCallback(tr_session * handle UNUSED, bool active, bool byUser, void * controller)
141{
142    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: [[NSNumber alloc] initWithBool: active], @"Active",
143                                [[NSNumber alloc] initWithBool: byUser], @"ByUser", nil];
144    [(Controller *)controller performSelectorOnMainThread: @selector(altSpeedToggledCallbackIsLimited:)
145        withObject: dict waitUntilDone: NO];
146}
147
148static tr_rpc_callback_status rpcCallback(tr_session * handle UNUSED, tr_rpc_callback_type type, struct tr_torrent * torrentStruct,
149                                            void * controller)
150{
151    [(Controller *)controller rpcCallback: type forTorrentStruct: torrentStruct];
152    return TR_RPC_NOREMOVE; //we'll do the remove manually
153}
154
155static void sleepCallback(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
156{
157    [(Controller *)controller sleepCallback: messageType argument: messageArgument];
158}
159
160@implementation Controller
161
162+ (void) initialize
163{
164    //make sure another Transmission.app isn't running already
165    BOOL othersRunning = NO;
166   
167    if ([NSApp isOnSnowLeopardOrBetter])
168    {
169        NSArray * apps = [NSRunningApplicationSL runningApplicationsWithBundleIdentifier: [[NSBundle mainBundle] bundleIdentifier]];
170        othersRunning = [apps count] > 1;
171    }
172    else
173    {
174        NSString * bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
175        const int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
176
177        for (NSDictionary * dic in [[NSWorkspace sharedWorkspace] launchedApplications])
178        {
179            if ([[dic objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]
180                    && [[dic objectForKey: @"NSApplicationProcessIdentifier"] intValue] != processIdentifier)
181                othersRunning = YES;
182        }
183    }
184   
185    if (othersRunning)
186    {
187        NSAlert * alert = [[NSAlert alloc] init];
188        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Transmission already running alert -> button")];
189        [alert setMessageText: NSLocalizedString(@"Transmission is already running.",
190                                                "Transmission already running alert -> title")];
191        [alert setInformativeText: NSLocalizedString(@"There is already a copy of Transmission running. "
192            "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message")];
193        [alert setAlertStyle: NSCriticalAlertStyle];
194       
195        [alert runModal];
196        [alert release];
197       
198        //kill ourselves right away
199        exit(0);
200    }
201   
202    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
203        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
204   
205    //set custom value transformers
206    ExpandedPathToPathTransformer * pathTransformer = [[[ExpandedPathToPathTransformer alloc] init] autorelease];
207    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
208   
209    ExpandedPathToIconTransformer * iconTransformer = [[[ExpandedPathToIconTransformer alloc] init] autorelease];
210    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
211   
212    //cover our asses
213    if ([[NSUserDefaults standardUserDefaults] boolForKey: @"WarningLegal"])
214    {
215        NSAlert * alert = [[NSAlert alloc] init];
216        [alert addButtonWithTitle: NSLocalizedString(@"I Accept", "Legal alert -> button")];
217        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Legal alert -> button")];
218        [alert setMessageText: NSLocalizedString(@"Welcome to Transmission", "Legal alert -> title")];
219        [alert setInformativeText: NSLocalizedString(@"Transmission is a file-sharing program."
220            " When you run a torrent, its data will be made available to others by means of upload."
221            " You and you alone are fully responsible for exercising proper judgement and abiding by your local laws.",
222            "Legal alert -> message")];
223        [alert setAlertStyle: NSInformationalAlertStyle];
224       
225        if ([alert runModal] == NSAlertSecondButtonReturn)
226            exit(0);
227        [alert release];
228       
229        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningLegal"];
230    }
231}
232
233- (id) init
234{
235    if ((self = [super init]))
236    {
237        fDefaults = [NSUserDefaults standardUserDefaults];
238       
239        //checks for old version speeds of -1
240        if ([fDefaults integerForKey: @"UploadLimit"] < 0)
241        {
242            [fDefaults removeObjectForKey: @"UploadLimit"];
243            [fDefaults setBool: NO forKey: @"CheckUpload"];
244        }
245        if ([fDefaults integerForKey: @"DownloadLimit"] < 0)
246        {
247            [fDefaults removeObjectForKey: @"DownloadLimit"];
248            [fDefaults setBool: NO forKey: @"CheckDownload"];
249        }
250       
251        //upgrading from versions < 2.40: clear recent items
252        [[NSDocumentController sharedDocumentController] clearRecentDocuments: nil];
253       
254        tr_benc settings;
255        tr_bencInitDict(&settings, 41);
256        tr_sessionGetDefaultSettings(&settings);
257       
258        const BOOL usesSpeedLimitSched = [fDefaults boolForKey: @"SpeedLimitAuto"];
259        if (!usesSpeedLimitSched)
260            tr_bencDictAddBool(&settings, TR_PREFS_KEY_ALT_SPEED_ENABLED, [fDefaults boolForKey: @"SpeedLimit"]);
261       
262        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_UP_KBps, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]);
263        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_DOWN_KBps, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]);
264       
265        tr_bencDictAddBool(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED, [fDefaults boolForKey: @"SpeedLimitAuto"]);
266        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN, [PrefsController dateToTimeSum:
267                                                                            [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]]);
268        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_END, [PrefsController dateToTimeSum:
269                                                                            [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]]);
270        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_DAY, [fDefaults integerForKey: @"SpeedLimitAutoDay"]);
271       
272        tr_bencDictAddInt(&settings, TR_PREFS_KEY_DSPEED_KBps, [fDefaults integerForKey: @"DownloadLimit"]);
273        tr_bencDictAddBool(&settings, TR_PREFS_KEY_DSPEED_ENABLED, [fDefaults boolForKey: @"CheckDownload"]);
274        tr_bencDictAddInt(&settings, TR_PREFS_KEY_USPEED_KBps, [fDefaults integerForKey: @"UploadLimit"]);
275        tr_bencDictAddBool(&settings, TR_PREFS_KEY_USPEED_ENABLED, [fDefaults boolForKey: @"CheckUpload"]);
276       
277        //hidden prefs
278        if ([fDefaults objectForKey: @"BindAddressIPv4"])
279            tr_bencDictAddStr(&settings, TR_PREFS_KEY_BIND_ADDRESS_IPV4, [[fDefaults stringForKey: @"BindAddressIPv4"] UTF8String]);
280        if ([fDefaults objectForKey: @"BindAddressIPv6"])
281            tr_bencDictAddStr(&settings, TR_PREFS_KEY_BIND_ADDRESS_IPV6, [[fDefaults stringForKey: @"BindAddressIPv6"] UTF8String]);
282       
283        tr_bencDictAddBool(&settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, [fDefaults boolForKey: @"BlocklistNew"]);
284        if ([fDefaults objectForKey: @"BlocklistURL"])
285            tr_bencDictAddStr(&settings, TR_PREFS_KEY_BLOCKLIST_URL, [[fDefaults stringForKey: @"BlocklistURL"] UTF8String]);
286        tr_bencDictAddBool(&settings, TR_PREFS_KEY_DHT_ENABLED, [fDefaults boolForKey: @"DHTGlobal"]);
287        tr_bencDictAddStr(&settings, TR_PREFS_KEY_DOWNLOAD_DIR, [[[fDefaults stringForKey: @"DownloadFolder"]
288                                                                    stringByExpandingTildeInPath] UTF8String]);
289        tr_bencDictAddInt(&settings, TR_PREFS_KEY_IDLE_LIMIT, [fDefaults integerForKey: @"IdleLimitMinutes"]);
290        tr_bencDictAddBool(&settings, TR_PREFS_KEY_IDLE_LIMIT_ENABLED, [fDefaults boolForKey: @"IdleLimitCheck"]);
291        tr_bencDictAddStr(&settings, TR_PREFS_KEY_INCOMPLETE_DIR, [[[fDefaults stringForKey: @"IncompleteDownloadFolder"]
292                                                                    stringByExpandingTildeInPath] UTF8String]);
293        tr_bencDictAddBool(&settings, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED, [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]);
294        tr_bencDictAddBool(&settings, TR_PREFS_KEY_LPD_ENABLED, [fDefaults boolForKey: @"LocalPeerDiscoveryGlobal"]);
295        tr_bencDictAddInt(&settings, TR_PREFS_KEY_MSGLEVEL, TR_MSG_DBG);
296        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, [fDefaults integerForKey: @"PeersTotal"]);
297        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_TORRENT, [fDefaults integerForKey: @"PeersTorrent"]);
298       
299        const BOOL randomPort = [fDefaults boolForKey: @"RandomPort"];
300        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, randomPort);
301        if (!randomPort)
302            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_PORT, [fDefaults integerForKey: @"BindPort"]);
303       
304        //hidden pref
305        if ([fDefaults objectForKey: @"PeerSocketTOS"])
306            tr_bencDictAddStr(&settings, TR_PREFS_KEY_PEER_SOCKET_TOS, [[fDefaults stringForKey: @"PeerSocketTOS"] UTF8String]);
307       
308        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PEX_ENABLED, [fDefaults boolForKey: @"PEXGlobal"]);
309        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PORT_FORWARDING, [fDefaults boolForKey: @"NatTraversal"]);
310        tr_bencDictAddReal(&settings, TR_PREFS_KEY_RATIO, [fDefaults floatForKey: @"RatioLimit"]);
311        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RATIO_ENABLED, [fDefaults boolForKey: @"RatioCheck"]);
312        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RENAME_PARTIAL_FILES, [fDefaults boolForKey: @"RenamePartialFiles"]);
313        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED,  [fDefaults boolForKey: @"RPCAuthorize"]);
314        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_ENABLED,  [fDefaults boolForKey: @"RPC"]);
315        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_PORT, [fDefaults integerForKey: @"RPCPort"]);
316        tr_bencDictAddStr(&settings, TR_PREFS_KEY_RPC_USERNAME,  [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
317        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_WHITELIST_ENABLED,  [fDefaults boolForKey: @"RPCUseWhitelist"]);
318        tr_bencDictAddBool(&settings, TR_PREFS_KEY_START, [fDefaults boolForKey: @"AutoStartDownload"]);
319        tr_bencDictAddBool(&settings, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_ENABLED, [fDefaults boolForKey: @"DoneScriptEnabled"]);
320        tr_bencDictAddStr(&settings, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_FILENAME, [[fDefaults stringForKey: @"DoneScriptPath"] UTF8String]);
321        tr_bencDictAddBool(&settings, TR_PREFS_KEY_UTP_ENABLED, [fDefaults boolForKey: @"UTPGlobal"]);
322       
323        tr_formatter_size_init([NSApp isOnSnowLeopardOrBetter] ? 1000 : 1024,
324                                    [NSLocalizedString(@"KB", "File size - kilobytes") UTF8String],
325                                    [NSLocalizedString(@"MB", "File size - megabytes") UTF8String],
326                                    [NSLocalizedString(@"GB", "File size - gigabytes") UTF8String],
327                                    [NSLocalizedString(@"TB", "File size - terabytes") UTF8String]);
328
329        tr_formatter_speed_init([NSApp isOnSnowLeopardOrBetter] ? 1000 : 1024,
330                                    [NSLocalizedString(@"KB/s", "Transfer speed (kilobytes per second)") UTF8String],
331                                    [NSLocalizedString(@"MB/s", "Transfer speed (megabytes per second)") UTF8String],
332                                    [NSLocalizedString(@"GB/s", "Transfer speed (gigabytes per second)") UTF8String],
333                                    [NSLocalizedString(@"TB/s", "Transfer speed (terabytes per second)") UTF8String]); //why not?
334
335        tr_formatter_mem_init(1024, [NSLocalizedString(@"KB", "Memory size - kilobytes") UTF8String],
336                                    [NSLocalizedString(@"MB", "Memory size - megabytes") UTF8String],
337                                    [NSLocalizedString(@"GB", "Memory size - gigabytes") UTF8String],
338                                    [NSLocalizedString(@"TB", "Memory size - terabytes") UTF8String]);
339       
340        const char * configDir = tr_getDefaultConfigDir("Transmission");
341        fLib = tr_sessionInit("macosx", configDir, YES, &settings);
342        tr_bencFree(&settings);
343       
344        [NSApp setDelegate: self];
345       
346        //register for magnet URLs (has to be in init)
347        [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:)
348            forEventClass: kInternetEventClass andEventID: kAEGetURL];
349       
350        fTorrents = [[NSMutableArray alloc] init];
351        fDisplayedTorrents = [[NSMutableArray alloc] init];
352       
353        fInfoController = [[InfoWindowController alloc] init];
354       
355        [PrefsController setHandle: fLib];
356        fPrefsController = [[PrefsController alloc] init];
357       
358        fQuitting = NO;
359        fSoundPlaying = NO;
360       
361        tr_sessionSetAltSpeedFunc(fLib, altSpeedToggledCallback, self);
362        if (usesSpeedLimitSched)
363            [fDefaults setBool: tr_sessionUsesAltSpeed(fLib) forKey: @"SpeedLimit"];
364       
365        tr_sessionSetRPCCallback(fLib, rpcCallback, self);
366       
367        [GrowlApplicationBridge setGrowlDelegate: self];
368       
369        [[UKKQueue sharedFileWatcher] setDelegate: self];
370       
371        [[SUUpdater sharedUpdater] setDelegate: self];
372        fQuitRequested = NO;
373       
374        fPauseOnLaunch = (GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0;
375    }
376    return self;
377}
378
379- (void) awakeFromNib
380{
381    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"TRMainToolbar"];
382    [toolbar setDelegate: self];
383    [toolbar setAllowsUserCustomization: YES];
384    [toolbar setAutosavesConfiguration: YES];
385    [toolbar setDisplayMode: NSToolbarDisplayModeIconOnly];
386    [fWindow setToolbar: toolbar];
387    [toolbar release];
388   
389    [fWindow setDelegate: self]; //do manually to avoid placement issue
390   
391    [fWindow makeFirstResponder: fTableView];
392    [fWindow setExcludedFromWindowsMenu: YES];
393   
394    //set table size
395    const BOOL small = [fDefaults boolForKey: @"SmallView"];
396    if (small)
397        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
398    [fTableView setUsesAlternatingRowBackgroundColors: !small];
399   
400    [fWindow setContentBorderThickness: NSMinY([[fTableView enclosingScrollView] frame]) forEdge: NSMinYEdge];
401    [fWindow setMovableByWindowBackground: YES];
402   
403    [[fTotalTorrentsField cell] setBackgroundStyle: NSBackgroundStyleRaised];
404   
405    //set up filter bar
406    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
407   
408    //set up status bar
409    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
410   
411    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
412                                "Main window -> 1st bottom left button (action) tooltip")];
413    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
414                                "Main window -> 2nd bottom left button (turtle) tooltip")];
415    [fClearCompletedButton setToolTip: NSLocalizedString(@"Remove all transfers that have completed seeding.",
416                                "Main window -> 3rd bottom left button (remove all) tooltip")];
417   
418    [fTableView registerForDraggedTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE]];
419    [fWindow registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType, NSURLPboardType, nil]];
420   
421    //you would think this would be called later in this method from updateUI, but it's not reached in awakeFromNib
422    //this must be called after showStatusBar:
423    [fStatusBar updateWithDownload: 0.0 upload: 0.0];
424
425    //this should also be after the rest of the setup
426    [self updateForAutoSize];
427   
428    //register for sleep notifications
429    IONotificationPortRef notify;
430    io_object_t iterator;
431    if ((fRootPort = IORegisterForSystemPower(self, & notify, sleepCallback, &iterator)))
432        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
433    else
434        NSLog(@"Could not IORegisterForSystemPower");
435   
436    //load previous transfers
437    NSArray * history = [NSArray arrayWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST]];
438   
439    if (!history)
440    {
441        //old version saved transfer info in prefs file
442        if ((history = [fDefaults arrayForKey: @"History"]))
443            [fDefaults removeObjectForKey: @"History"];
444    }
445   
446    if (history)
447    {
448        for (NSDictionary * historyItem in history)
449        {
450            Torrent * torrent;
451            if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib forcePause: fPauseOnLaunch]))
452            {
453                [fTorrents addObject: torrent];
454                [torrent release];
455            }
456        }
457    }
458   
459    fBadger = [[Badger alloc] initWithLib: fLib];
460   
461    //observe notifications
462    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
463   
464    [nc addObserver: self selector: @selector(updateUI)
465                    name: @"UpdateUI" object: nil];
466   
467    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
468                    name: @"TorrentFinishedDownloading" object: nil];
469   
470    [nc addObserver: self selector: @selector(torrentRestartedDownloading:)
471                    name: @"TorrentRestartedDownloading" object: nil];
472   
473    [nc addObserver: self selector: @selector(torrentFinishedSeeding:)
474                    name: @"TorrentFinishedSeeding" object: nil];
475   
476    //avoids need of setting delegate
477    [nc addObserver: self selector: @selector(torrentTableViewSelectionDidChange:)
478                    name: NSOutlineViewSelectionDidChangeNotification object: fTableView];
479   
480    [nc addObserver: self selector: @selector(changeAutoImport)
481                    name: @"AutoImportSettingChange" object: nil];
482   
483    [nc addObserver: self selector: @selector(updateForAutoSize)
484                    name: @"AutoSizeSettingChange" object: nil];
485   
486    [nc addObserver: self selector: @selector(updateForExpandCollape)
487                    name: @"OutlineExpandCollapse" object: nil];
488   
489    [nc addObserver: fWindow selector: @selector(makeKeyWindow)
490                    name: @"MakeWindowKey" object: nil];
491   
492    [nc addObserver: self selector: @selector(updateTorrentsInQueue)
493                    name: @"UpdateQueue" object: nil];
494   
495    [nc addObserver: self selector: @selector(applyFilter)
496                    name: @"ApplyFilter" object: nil];
497   
498    //open newly created torrent file
499    [nc addObserver: self selector: @selector(beginCreateFile:)
500                    name: @"BeginCreateTorrentFile" object: nil];
501   
502    //open newly created torrent file
503    [nc addObserver: self selector: @selector(openCreatedFile:)
504                    name: @"OpenCreatedTorrentFile" object: nil];
505
506    //timer to update the interface every second
507    [self updateUI];
508    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
509                selector: @selector(updateUI) userInfo: nil repeats: YES];
510    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
511    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
512   
513    [self applyFilter];
514   
515    [fWindow makeKeyAndOrderFront: nil];
516   
517    if ([fDefaults boolForKey: @"InfoVisible"])
518        [self showInfo: nil];
519}
520
521- (void) applicationDidFinishLaunching: (NSNotification *) notification
522{
523    [NSApp setServicesProvider: self];
524   
525    //register for dock icon drags (has to be in applicationDidFinishLaunching: to work)
526    [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:)
527        forEventClass: kCoreEventClass andEventID: kAEOpenContents];
528   
529    //auto importing
530    [self checkAutoImportDirectory];
531   
532    //registering the Web UI to Bonjour
533    if ([fDefaults boolForKey: @"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"])
534        [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]];
535   
536    //shamelessly ask for donations
537    if ([fDefaults boolForKey: @"WarningDonate"])
538    {
539        tr_session_stats stats;
540        tr_sessionGetCumulativeStats(fLib, &stats);
541        const BOOL firstLaunch = stats.sessionCount <= 1;
542       
543        NSDate * lastDonateDate = [fDefaults objectForKey: @"DonateAskDate"];
544        const BOOL timePassed = !lastDonateDate || (-1 * [lastDonateDate timeIntervalSinceNow]) >= DONATE_NAG_TIME;
545       
546        if (!firstLaunch && timePassed)
547        {
548            [fDefaults setObject: [NSDate date] forKey: @"DonateAskDate"];
549           
550            NSAlert * alert = [[NSAlert alloc] init];
551            [alert setMessageText: NSLocalizedString(@"Support open-source indie software", "Donation beg -> title")];
552           
553            NSString * donateMessage = [NSString stringWithFormat: @"%@\n\n%@",
554                NSLocalizedString(@"Transmission is a full-featured torrent application."
555                    " A lot of time and effort have gone into development, coding, and refinement."
556                    " If you enjoy using it, please consider showing your love with a donation.", "Donation beg -> message"),
557                NSLocalizedString(@"Donate or not, there will be no difference to your torrenting experience.", "Donation beg -> message")];
558           
559            [alert setInformativeText: donateMessage];
560            [alert setAlertStyle: NSInformationalAlertStyle];
561           
562            [alert addButtonWithTitle: [NSLocalizedString(@"Donate", "Donation beg -> button") stringByAppendingEllipsis]];
563            NSButton * noDonateButton = [alert addButtonWithTitle: NSLocalizedString(@"Nope", "Donation beg -> button")];
564            [noDonateButton setKeyEquivalent: @"\e"]; //escape key
565           
566            const BOOL allowNeverAgain = lastDonateDate != nil; //hide the "don't show again" check the first time - give them time to try the app
567            [alert setShowsSuppressionButton: allowNeverAgain];
568            if (allowNeverAgain)
569                [[alert suppressionButton] setTitle: NSLocalizedString(@"Don't bug me about this ever again.", "Donation beg -> button")];
570           
571            const NSInteger donateResult = [alert runModal];
572            if (donateResult == NSAlertFirstButtonReturn)
573                [self linkDonate: self];
574           
575            if (allowNeverAgain)
576                [fDefaults setBool: ([[alert suppressionButton] state] != NSOnState) forKey: @"WarningDonate"];
577           
578            [alert release];
579        }
580    }
581}
582
583- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
584{
585    NSWindow * mainWindow = [NSApp mainWindow];
586    if (!mainWindow || ![mainWindow isVisible])
587        [fWindow makeKeyAndOrderFront: nil];
588   
589    return NO;
590}
591
592- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
593{
594    if (!fQuitRequested && [fDefaults boolForKey: @"CheckQuit"])
595    {
596        NSInteger active = 0, downloading = 0;
597        for (Torrent * torrent  in fTorrents)
598            if ([torrent isActive] && ![torrent isStalled])
599            {
600                active++;
601                if (![torrent allDownloaded])
602                    downloading++;
603            }
604       
605        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
606        {
607            NSString * message = active == 1
608                ? NSLocalizedString(@"There is an active transfer that will be paused on quit."
609                    " The transfer will automatically resume on the next launch.", "Confirm Quit panel -> message")
610                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers that will be paused on quit."
611                    " The transfers will automatically resume on the next launch.", "Confirm Quit panel -> message"), active];
612
613            NSBeginAlertSheet(NSLocalizedString(@"Are you sure you want to quit?", "Confirm Quit panel -> title"),
614                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
615                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
616                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
617            return NSTerminateLater;
618        }
619    }
620   
621    return NSTerminateNow;
622}
623
624- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
625{
626    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
627}
628
629- (void) applicationWillTerminate: (NSNotification *) notification
630{
631    fQuitting = YES;
632   
633    //stop the Bonjour service
634    [[BonjourController defaultController] stop];
635
636    //stop blocklist download
637    if ([BlocklistDownloader isRunning])
638        [[BlocklistDownloader downloader] cancelDownload];
639   
640    //stop timers and notification checking
641    [[NSNotificationCenter defaultCenter] removeObserver: self];
642   
643    [fTimer invalidate];
644   
645    if (fAutoImportTimer)
646    {   
647        if ([fAutoImportTimer isValid])
648            [fAutoImportTimer invalidate];
649        [fAutoImportTimer release];
650    }
651   
652    [fBadger setQuitting];
653   
654    //remove all torrent downloads
655    if (fPendingTorrentDownloads)
656    {
657        for (NSDictionary * downloadDict in fPendingTorrentDownloads)
658        {
659            NSURLDownload * download = [downloadDict objectForKey: @"Download"];
660            [download cancel];
661            [download release];
662        }
663        [fPendingTorrentDownloads release];
664    }
665   
666    //remember window states and close all windows
667    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
668   
669    const BOOL quickLookOpen = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
670                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
671    if (quickLookOpen)
672        [[QLPreviewPanelSL sharedPreviewPanel] updateController];
673   
674    for (NSWindow * window in [NSApp windows])
675        [window close];
676   
677    [self showStatusBar: NO animate: NO];
678    [self showFilterBar: NO animate: NO];
679   
680    //save history
681    [self updateTorrentHistory];
682    [fTableView saveCollapsedGroups];
683   
684    //remaining calls the same as dealloc
685    [fInfoController release];
686    [fMessageController release];
687    [fPrefsController release];
688   
689    [fStatusBar release];
690    [fFilterBar release];
691   
692    [fTorrents release];
693    [fDisplayedTorrents release];
694   
695    [fOverlayWindow release];
696    [fBadger release];
697   
698    [fAutoImportedNames release];
699   
700    [fPreviewPanel release];
701   
702    //complete cleanup
703    tr_sessionClose(fLib);
704}
705
706- (void) handleOpenContentsEvent: (NSAppleEventDescriptor *) event replyEvent: (NSAppleEventDescriptor *) replyEvent
707{
708    NSString * urlString = nil;
709
710    NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject];
711    if ([directObject descriptorType] == typeAEList)
712    {
713        for (NSInteger i = 1; i <= [directObject numberOfItems]; i++)
714            if ((urlString = [[directObject descriptorAtIndex: i] stringValue]))
715                break;
716    }
717    else
718        urlString = [directObject stringValue];
719   
720    if (urlString)
721        [self openURL: urlString];
722}
723
724- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) suggestedName
725{
726    if ([[suggestedName pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
727    {
728        [download cancel];
729       
730        NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title"),
731            [NSString stringWithFormat: NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.",
732            "Download not a torrent -> message"), suggestedName,
733            [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]],
734            NSLocalizedString(@"OK", "Download not a torrent -> button"), nil, nil);
735       
736        [download release];
737    }
738    else
739        [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: [suggestedName lastPathComponent]]
740                    allowOverwrite: NO];
741}
742
743-(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path
744{
745    if (!fPendingTorrentDownloads)
746        fPendingTorrentDownloads = [[NSMutableDictionary alloc] init];
747   
748    [fPendingTorrentDownloads setObject: [NSDictionary dictionaryWithObjectsAndKeys:
749                    path, @"Path", download, @"Download", nil] forKey: [[download request] URL]];
750}
751
752- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error
753{
754    NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Torrent download error -> title"),
755        [NSString stringWithFormat: NSLocalizedString(@"The torrent could not be downloaded from %@: %@.",
756        "Torrent download failed -> message"),
757        [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
758        [error localizedDescription]], NSLocalizedString(@"OK", "Torrent download failed -> button"), nil, nil);
759   
760    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
761    if ([fPendingTorrentDownloads count] == 0)
762    {
763        [fPendingTorrentDownloads release];
764        fPendingTorrentDownloads = nil;
765    }
766   
767    [download release];
768}
769
770- (void) downloadDidFinish: (NSURLDownload *) download
771{
772    NSString * path = [[fPendingTorrentDownloads objectForKey: [[download request] URL]] objectForKey: @"Path"];
773   
774    [self openFiles: [NSArray arrayWithObject: path] addType: ADD_URL forcePath: nil];
775   
776    //delete the torrent file after opening
777    [[NSFileManager defaultManager] removeItemAtPath: path error: NULL];
778   
779    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
780    if ([fPendingTorrentDownloads count] == 0)
781    {
782        [fPendingTorrentDownloads release];
783        fPendingTorrentDownloads = nil;
784    }
785   
786    [download release];
787}
788
789- (void) application: (NSApplication *) app openFiles: (NSArray *) filenames
790{
791    [self openFiles: filenames addType: ADD_MANUAL forcePath: nil];
792}
793
794- (void) openFiles: (NSArray *) filenames addType: (addType) type forcePath: (NSString *) path
795{
796    BOOL deleteTorrentFile, canToggleDelete = NO;
797    switch (type)
798    {
799        case ADD_CREATED:
800            deleteTorrentFile = NO;
801            break;
802        case ADD_URL:
803            deleteTorrentFile = YES;
804            break;
805        default:
806            deleteTorrentFile = [fDefaults boolForKey: @"DeleteOriginalTorrent"];
807            canToggleDelete = YES;
808    }
809   
810    for (NSString * torrentPath in filenames)
811    {
812        //ensure torrent doesn't already exist
813        tr_ctor * ctor = tr_ctorNew(fLib);
814        tr_ctorSetMetainfoFromFile(ctor, [torrentPath UTF8String]);
815       
816        tr_info info;
817        const tr_parse_result result = tr_torrentParse(ctor, &info);
818        tr_ctorFree(ctor);
819       
820        if (result != TR_PARSE_OK)
821        {
822            if (result == TR_PARSE_DUPLICATE)
823                [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
824            else if (result == TR_PARSE_ERR)
825            {
826                if (type != ADD_AUTO)
827                    [self invalidOpenAlert: [torrentPath lastPathComponent]];
828            }
829            else
830                NSAssert2(NO, @"Unknown error code (%d) when attempting to open \"%@\"", result, torrentPath);
831           
832            tr_metainfoFree(&info);
833            continue;
834        }
835       
836        //determine download location
837        NSString * location;
838        BOOL lockDestination = NO; //don't override the location with a group location if it has a hardcoded path
839        if (path)
840        {
841            location = [path stringByExpandingTildeInPath];
842            lockDestination = YES;
843        }
844        else if ([fDefaults boolForKey: @"DownloadLocationConstant"])
845            location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
846        else if (type != ADD_URL)
847            location = [torrentPath stringByDeletingLastPathComponent];
848        else
849            location = nil;
850       
851        //determine to show the options window
852        const BOOL showWindow = type == ADD_SHOW_OPTIONS || ([fDefaults boolForKey: @"DownloadAsk"]
853                                    && (info.isMultifile || ![fDefaults boolForKey: @"DownloadAskMulti"])
854                                    && (type != ADD_AUTO || ![fDefaults boolForKey: @"DownloadAskManual"]));
855        tr_metainfoFree(&info);
856       
857        Torrent * torrent;
858        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath location: location
859                            deleteTorrentFile: showWindow ? NO : deleteTorrentFile lib: fLib]))
860            continue;
861       
862        //change the location if the group calls for it (this has to wait until after the torrent is created)
863        if (!lockDestination && [[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
864        {
865            location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
866            [torrent changeDownloadFolderBeforeUsing: location];
867        }
868       
869        //verify the data right away if it was newly created
870        if (type == ADD_CREATED)
871            [torrent resetCache];
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- (IBAction) showGlobalPopover: (id) sender
2219{
2220    if ([NSApp isOnLionOrBetter])
2221    {
2222        NSPopover * popover = [[NSPopoverLion alloc] init];
2223        [popover setBehavior: NSPopoverBehaviorTransient];
2224        GlobalOptionsPopoverViewController * viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle: [PrefsController handle]];
2225        [popover setContentViewController: viewController];
2226       
2227        [popover showRelativeToRect: [sender frame] ofView: sender preferredEdge: NSMaxYEdge];
2228       
2229        [viewController release];
2230        [popover release];
2231    }
2232    else
2233    {
2234        //place menu below button
2235        NSRect rect = [sender frame];
2236        NSPoint location = rect.origin;
2237        location.y += NSHeight(rect) + 5.0;
2238       
2239        if ([NSApp isOnSnowLeopardOrBetter])
2240            [fActionMenu popUpMenuPositioningItem: nil atLocation: location inView: sender];
2241        else
2242        {
2243            NSEvent * newEvent = [NSEvent mouseEventWithType: NSLeftMouseDown location: location
2244                                               modifierFlags: NSLeftMouseDownMask timestamp: GetCurrentEventTime() windowNumber: [fWindow windowNumber]
2245                                                     context: nil eventNumber: 1 clickCount: 1 pressure: 1];
2246             
2247            [NSMenu popUpContextMenu: fActionMenu withEvent: newEvent forView: sender];
2248        }
2249    }
2250}
2251
2252- (void) menuNeedsUpdate: (NSMenu *) menu
2253{
2254    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2255    {
2256        for (NSInteger i = [menu numberOfItems]-1; i >= 0; i--)
2257            [menu removeItemAtIndex: i];
2258       
2259        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2260       
2261        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2262        for (NSInteger i = 0; i < groupMenuCount; i++)
2263        {
2264            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2265            [groupMenu removeItemAtIndex: 0];
2266            [menu addItem: item];
2267            [item release];
2268        }
2269    }
2270    else if (menu == fUploadMenu || menu == fDownloadMenu)
2271    {
2272        if ([menu numberOfItems] > 3)
2273            return;
2274       
2275        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2276       
2277        NSMenuItem * item;
2278        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2279        {
2280            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2281                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2282                    keyEquivalent: @""];
2283            [item setTarget: self];
2284            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2285            [menu addItem: item];
2286            [item release];
2287        }
2288    }
2289    else if (menu == fRatioStopMenu)
2290    {
2291        if ([menu numberOfItems] > 3)
2292            return;
2293       
2294        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2295       
2296        NSMenuItem * item;
2297        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2298        {
2299            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2300                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2301            [item setTarget: self];
2302            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2303            [menu addItem: item];
2304            [item release];
2305        }
2306    }
2307    else;
2308}
2309
2310- (void) setGroup: (id) sender
2311{
2312    for (Torrent * torrent in [fTableView selectedTorrents])
2313    {
2314        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2315       
2316        [torrent setGroupValue: [sender tag]];
2317    }
2318   
2319    [self applyFilter];
2320    [self updateUI];
2321    [self updateTorrentHistory];
2322}
2323
2324- (void) toggleSpeedLimit: (id) sender
2325{
2326    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2327    [self speedLimitChanged: sender];
2328}
2329
2330- (void) speedLimitChanged: (id) sender
2331{
2332    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2333    [fStatusBar updateSpeedFieldsToolTips];
2334}
2335
2336//dict has been retained
2337- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2338{
2339    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2340
2341    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2342    [fStatusBar updateSpeedFieldsToolTips];
2343   
2344    if (![[dict objectForKey: @"ByUser"] boolValue])
2345        [GrowlApplicationBridge notifyWithTitle: isLimited
2346                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2347                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2348            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2349            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2350   
2351    [dict release];
2352}
2353
2354- (void) setLimitGlobalEnabled: (id) sender
2355{
2356    BOOL upload = [sender menu] == fUploadMenu;
2357    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2358   
2359    [fPrefsController applySpeedSettings: nil];
2360}
2361
2362- (void) setQuickLimitGlobal: (id) sender
2363{
2364    BOOL upload = [sender menu] == fUploadMenu;
2365    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2366    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2367   
2368    [fPrefsController updateLimitFields];
2369    [fPrefsController applySpeedSettings: nil];
2370}
2371
2372- (void) setRatioGlobalEnabled: (id) sender
2373{
2374    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2375   
2376    [fPrefsController applyRatioSetting: nil];
2377}
2378
2379- (void) setQuickRatioGlobal: (id) sender
2380{
2381    [fDefaults setBool: YES forKey: @"RatioCheck"];
2382    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2383   
2384    [fPrefsController updateRatioStopFieldOld];
2385}
2386
2387- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2388{
2389    fSoundPlaying = NO;
2390}
2391
2392- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2393{
2394    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2395    {
2396        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2397            return;
2398       
2399        if (fAutoImportTimer)
2400        {
2401            if ([fAutoImportTimer isValid])
2402                [fAutoImportTimer invalidate];
2403            [fAutoImportTimer release];
2404            fAutoImportTimer = nil;
2405        }
2406       
2407        //check again in 10 seconds in case torrent file wasn't complete
2408        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2409            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2410       
2411        [self checkAutoImportDirectory];
2412    }
2413}
2414
2415- (void) changeAutoImport
2416{
2417    if (fAutoImportTimer)
2418    {
2419        if ([fAutoImportTimer isValid])
2420            [fAutoImportTimer invalidate];
2421        [fAutoImportTimer release];
2422        fAutoImportTimer = nil;
2423    }
2424   
2425    if (fAutoImportedNames)
2426    {
2427        [fAutoImportedNames release];
2428        fAutoImportedNames = nil;
2429    }
2430   
2431    [self checkAutoImportDirectory];
2432}
2433
2434- (void) checkAutoImportDirectory
2435{
2436    NSString * path;
2437    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2438        return;
2439   
2440    path = [path stringByExpandingTildeInPath];
2441   
2442    NSArray * importedNames;
2443    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2444        return;
2445   
2446    //only check files that have not been checked yet
2447    NSMutableArray * newNames = [importedNames mutableCopy];
2448   
2449    if (fAutoImportedNames)
2450        [newNames removeObjectsInArray: fAutoImportedNames];
2451    else
2452        fAutoImportedNames = [[NSMutableArray alloc] init];
2453    [fAutoImportedNames setArray: importedNames];
2454   
2455    for (NSString * file in newNames)
2456    {
2457        if ([file hasPrefix: @"."])
2458            continue;
2459       
2460        NSString * fullFile = [path stringByAppendingPathComponent: file];
2461       
2462        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2463                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2464            continue;
2465       
2466        tr_ctor * ctor = tr_ctorNew(fLib);
2467        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2468       
2469        switch (tr_torrentParse(ctor, NULL))
2470        {
2471            case TR_PARSE_OK:
2472                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2473               
2474                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2475                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2476                    clickContext: nil];
2477                break;
2478           
2479            case TR_PARSE_ERR:
2480                [fAutoImportedNames removeObject: file];
2481                break;
2482           
2483            case TR_PARSE_DUPLICATE: //let's ignore this (but silence a warning)
2484                break;
2485        }
2486       
2487        tr_ctorFree(ctor);
2488    }
2489   
2490    [newNames release];
2491}
2492
2493- (void) beginCreateFile: (NSNotification *) notification
2494{
2495    if (![fDefaults boolForKey: @"AutoImport"])
2496        return;
2497   
2498    NSString * location = [notification object],
2499            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2500   
2501    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2502                                    isEqualToString: [path stringByExpandingTildeInPath]])
2503        [fAutoImportedNames addObject: [location lastPathComponent]];
2504}
2505
2506- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2507{
2508    if (item)
2509        return [[item torrents] count];
2510    else
2511        return [fDisplayedTorrents count];
2512}
2513
2514- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2515{
2516    if (item)
2517        return [[item torrents] objectAtIndex: index];
2518    else
2519        return [fDisplayedTorrents objectAtIndex: index];
2520}
2521
2522- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2523{
2524    return ![item isKindOfClass: [Torrent class]];
2525}
2526
2527- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2528{
2529    if ([item isKindOfClass: [Torrent class]]) {
2530        if (tableColumn)
2531            return nil;
2532        return [item hashString];
2533    }
2534    else
2535    {
2536        NSString * ident = [tableColumn identifier];
2537        if ([ident isEqualToString: @"Group"])
2538        {
2539            NSInteger group = [item groupIndex];
2540            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2541                                : NSLocalizedString(@"No Group", "Group table row");
2542        }
2543        else if ([ident isEqualToString: @"Color"])
2544        {
2545            NSInteger group = [item groupIndex];
2546            return [[GroupsController groups] imageForIndex: group];
2547        }
2548        else if ([ident isEqualToString: @"DL Image"])
2549            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2550        else if ([ident isEqualToString: @"UL Image"])
2551            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2552                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2553        else
2554        {
2555            TorrentGroup * group = (TorrentGroup *)item;
2556           
2557            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2558                return [NSString stringForRatio: [group ratio]];
2559            else
2560            {
2561                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2562                return [NSString stringForSpeed: rate];
2563            }
2564        }
2565    }
2566}
2567
2568- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2569{
2570    //only allow reordering of rows if sorting by order
2571    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2572    {
2573        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2574        for (id torrent in items)
2575        {
2576            if (![torrent isKindOfClass: [Torrent class]])
2577                return NO;
2578           
2579            [indexSet addIndex: [fTableView rowForItem: torrent]];
2580        }
2581       
2582        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2583        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2584        return YES;
2585    }
2586    return NO;
2587}
2588
2589- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2590    proposedChildIndex: (NSInteger) index
2591{
2592    NSPasteboard * pasteboard = [info draggingPasteboard];
2593    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2594    {
2595        if ([fDefaults boolForKey: @"SortByGroup"])
2596        {
2597            if (!item)
2598                return NSDragOperationNone;
2599           
2600            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2601            {
2602                if ([item isKindOfClass: [Torrent class]])
2603                {
2604                    TorrentGroup * group = [fTableView parentForItem: item];
2605                    index = [[group torrents] indexOfObject: item] + 1;
2606                    item = group;
2607                }
2608            }
2609            else
2610            {
2611                if ([item isKindOfClass: [Torrent class]])
2612                    item = [fTableView parentForItem: item];
2613                index = NSOutlineViewDropOnItemIndex;
2614            }
2615        }
2616        else
2617        {
2618            if (item)
2619            {
2620                index = [fTableView rowForItem: item] + 1;
2621                item = nil;
2622            }
2623        }
2624       
2625        [fTableView setDropItem: item dropChildIndex: index];
2626        return NSDragOperationGeneric;
2627    }
2628   
2629    return NSDragOperationNone;
2630}
2631
2632- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2633    childIndex: (NSInteger) newRow
2634{
2635    NSPasteboard * pasteboard = [info draggingPasteboard];
2636    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2637    {
2638        //remember selected rows
2639        NSArray * selectedValues = [fTableView selectedValues];
2640   
2641        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2642       
2643        //get the torrents to move
2644        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2645        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2646            [movingTorrents addObject: [fTableView itemAtRow: i]];
2647       
2648        //reset groups
2649        if (item)
2650        {
2651            //change groups
2652            NSInteger groupValue = [item groupIndex];
2653            for (Torrent * torrent in movingTorrents)
2654            {
2655                //have to reset objects here to avoid weird crash
2656                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2657                [[item torrents] addObject: torrent];
2658               
2659                [torrent setGroupValue: groupValue];
2660            }
2661            //part 2 of avoiding weird crash
2662            [fTableView reloadItem: nil reloadChildren: YES];
2663        }
2664       
2665        //reorder queue order
2666        if (newRow != NSOutlineViewDropOnItemIndex)
2667        {
2668            //find torrent to place under
2669            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2670            Torrent * topTorrent = nil;
2671            for (NSInteger i = newRow-1; i >= 0; i--)
2672            {
2673                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2674                if (![movingTorrents containsObject: tempTorrent])
2675                {
2676                    topTorrent = tempTorrent;
2677                    break;
2678                }
2679            }
2680           
2681            //remove objects to reinsert
2682            [fTorrents removeObjectsInArray: movingTorrents];
2683           
2684            //insert objects at new location
2685            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2686            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2687            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2688        }
2689       
2690        [self applyFilter];
2691        [fTableView selectValues: selectedValues];
2692    }
2693   
2694    return YES;
2695}
2696
2697- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2698{
2699    [self resetInfo];
2700    [[fWindow toolbar] validateVisibleItems];
2701}
2702
2703- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2704{
2705    NSPasteboard * pasteboard = [info draggingPasteboard];
2706    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2707    {
2708        //check if any torrent files can be added
2709        BOOL torrent = NO;
2710        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2711        for (NSString * file in files)
2712        {
2713            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2714                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2715            {
2716                torrent = YES;
2717                tr_ctor * ctor = tr_ctorNew(fLib);
2718                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2719                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2720                {
2721                    if (!fOverlayWindow)
2722                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2723                    [fOverlayWindow setTorrents: files];
2724                   
2725                    return NSDragOperationCopy;
2726                }
2727                tr_ctorFree(ctor);
2728            }
2729        }
2730       
2731        //create a torrent file if a single file
2732        if (!torrent && [files count] == 1)
2733        {
2734            if (!fOverlayWindow)
2735                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2736            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2737           
2738            return NSDragOperationCopy;
2739        }
2740    }
2741    else if ([[pasteboard types] containsObject: NSURLPboardType])
2742    {
2743        if (!fOverlayWindow)
2744            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2745        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2746       
2747        return NSDragOperationCopy;
2748    }
2749    else;
2750   
2751    return NSDragOperationNone;
2752}
2753
2754- (void) draggingExited: (id <NSDraggingInfo>) info
2755{
2756    if (fOverlayWindow)
2757        [fOverlayWindow fadeOut];
2758}
2759
2760- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2761{
2762    if (fOverlayWindow)
2763        [fOverlayWindow fadeOut];
2764   
2765    NSPasteboard * pasteboard = [info draggingPasteboard];
2766    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2767    {
2768        BOOL torrent = NO, accept = YES;
2769       
2770        //create an array of files that can be opened
2771        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2772        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
2773        for (NSString * file in files)
2774        {
2775            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2776                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2777            {
2778                torrent = YES;
2779                tr_ctor * ctor = tr_ctorNew(fLib);
2780                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2781                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2782                    [filesToOpen addObject: file];
2783                tr_ctorFree(ctor);
2784            }
2785        }
2786       
2787        if ([filesToOpen count] > 0)
2788            [self application: NSApp openFiles: filesToOpen];
2789        else
2790        {
2791            if (!torrent && [files count] == 1)
2792                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2793            else
2794                accept = NO;
2795        }
2796       
2797        return accept;
2798    }
2799    else if ([[pasteboard types] containsObject: NSURLPboardType])
2800    {
2801        NSURL * url;
2802        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2803        {
2804            [self openURL: [url absoluteString]];
2805            return YES;
2806        }
2807    }
2808    else;
2809   
2810    return NO;
2811}
2812
2813- (void) toggleSmallView: (id) sender
2814{
2815    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2816    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2817   
2818    [fTableView setUsesAlternatingRowBackgroundColors: !makeSmall];
2819   
2820    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2821   
2822    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2823   
2824    //resize for larger min height if not set to auto size
2825    if (![fDefaults boolForKey: @"AutoSize"])
2826    {
2827        const NSSize contentSize = [[fWindow contentView] frame].size;
2828       
2829        NSSize contentMinSize = [fWindow contentMinSize];
2830        contentMinSize.height = [self minWindowContentSizeAllowed];
2831        [fWindow setContentMinSize: contentMinSize];
2832       
2833        //make sure the window already isn't too small
2834        if (!makeSmall && contentSize.height < contentMinSize.height)
2835        {
2836            NSRect frame = [fWindow frame];
2837            CGFloat heightChange = contentMinSize.height - contentSize.height;
2838            frame.size.height += heightChange;
2839            frame.origin.y -= heightChange;
2840           
2841            [fWindow setFrame: frame display: YES];
2842        }
2843    }
2844    else
2845        [self setWindowSizeToFit];
2846}
2847
2848- (void) togglePiecesBar: (id) sender
2849{
2850    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2851    [fTableView togglePiecesBar];
2852}
2853
2854- (void) toggleAvailabilityBar: (id) sender
2855{
2856    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2857    [fTableView display];
2858}
2859
2860- (void) toggleStatusString: (id) sender
2861{
2862    if ([fDefaults boolForKey: @"SmallView"])
2863        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2864    else
2865        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2866   
2867    [fTableView reloadData];
2868}
2869
2870- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2871{
2872    NSScrollView * scrollView = [fTableView enclosingScrollView];
2873   
2874    //convert pixels to points
2875    NSRect windowFrame = [fWindow frame];
2876    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2877    windowSize.height += height;
2878   
2879    if (check)
2880    {
2881        //we can't call minSize, since it might be set to the current size (auto size)
2882        const CGFloat minHeight = [self minWindowContentSizeAllowed]
2883                                    + (NSHeight([fWindow frame]) - NSHeight([[fWindow contentView] frame])); //contentView to window
2884       
2885        if (windowSize.height < minHeight)
2886            windowSize.height =minHeight;
2887        else
2888        {
2889            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2890            if (!fStatusBar)
2891                maxSize.height -= STATUS_BAR_HEIGHT;
2892            if (!fFilterBar)
2893                maxSize.height -= FILTER_BAR_HEIGHT;
2894            if (windowSize.height > maxSize.height)
2895                windowSize.height = maxSize.height;
2896        }
2897    }
2898
2899    //convert points to pixels
2900    windowSize = [scrollView convertSize: windowSize toView: nil];
2901
2902    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2903    windowFrame.size.height = windowSize.height;
2904    return windowFrame;
2905}
2906
2907- (void) toggleStatusBar: (id) sender
2908{
2909    const BOOL show = fStatusBar == nil;
2910    [self showStatusBar: show animate: YES];
2911    [fDefaults setBool: show forKey: @"StatusBar"];
2912}
2913
2914//doesn't save shown state
2915- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2916{
2917    const BOOL prevShown = fStatusBar != nil;
2918    if (show == prevShown)
2919        return;
2920   
2921    if (show)
2922    {
2923        fStatusBar = [[StatusBarController alloc] initWithLib: fLib];
2924       
2925        NSView * contentView = [fWindow contentView];
2926        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
2927       
2928        NSRect statusBarFrame = [[fStatusBar view] frame];
2929        statusBarFrame.size.width = windowSize.width;
2930        [[fStatusBar view] setFrame: statusBarFrame];
2931       
2932        [contentView addSubview: [fStatusBar view]];
2933        [[fStatusBar view] setFrameOrigin: NSMakePoint(0.0, NSMaxY([contentView frame]))];
2934    }
2935   
2936    NSRect frame;
2937    CGFloat heightChange = [[fStatusBar view] frame].size.height;
2938    if (!show)
2939        heightChange *= -1;
2940   
2941    //allow bar to show even if not enough room
2942    if (show && ![fDefaults boolForKey: @"AutoSize"])
2943    {
2944        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2945        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2946        if (change < 0.0)
2947        {
2948            frame = [fWindow frame];
2949            frame.size.height += change;
2950            frame.origin.y -= change;
2951            [fWindow setFrame: frame display: NO animate: NO];
2952        }
2953    }
2954   
2955    [self updateUI];
2956   
2957    NSScrollView * scrollView = [fTableView enclosingScrollView];
2958   
2959    //set views to not autoresize
2960    const NSUInteger statsMask = [[fStatusBar view] autoresizingMask];
2961    [[fStatusBar view] setAutoresizingMask: NSViewNotSizable];
2962    NSUInteger filterMask;
2963    if (fFilterBar)
2964    {
2965        filterMask = [[fFilterBar view] autoresizingMask];
2966        [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
2967    }
2968    const NSUInteger scrollMask = [scrollView autoresizingMask];
2969    [scrollView setAutoresizingMask: NSViewNotSizable];
2970   
2971    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2972    [fWindow setFrame: frame display: YES animate: animate];
2973   
2974    //re-enable autoresize
2975    [[fStatusBar view] setAutoresizingMask: statsMask];
2976    if (fFilterBar)
2977        [[fFilterBar view] setAutoresizingMask: filterMask];
2978    [scrollView setAutoresizingMask: scrollMask];
2979   
2980    if (!show)
2981    {
2982        [[fStatusBar view] removeFromSuperviewWithoutNeedingDisplay];
2983        [fStatusBar release];
2984        fStatusBar = nil;
2985    }
2986   
2987    if ([fDefaults boolForKey: @"AutoSize"])
2988        [self setWindowMinMaxToCurrent];
2989    else
2990    {
2991        //change min size
2992        NSSize minSize = [fWindow contentMinSize];
2993        minSize.height += heightChange;
2994        [fWindow setContentMinSize: minSize];
2995    }
2996}
2997
2998- (void) toggleFilterBar: (id) sender
2999{
3000    const BOOL show = fFilterBar == nil;
3001   
3002    [self showFilterBar: show animate: YES];
3003    [fDefaults setBool: show forKey: @"FilterBar"];
3004    [[fWindow toolbar] validateVisibleItems];
3005   
3006    //disable filtering when hiding
3007    if (!show)
3008    {
3009        [[NSUserDefaults standardUserDefaults] setObject: FILTER_NONE forKey: @"Filter"];
3010        [[NSUserDefaults standardUserDefaults] setInteger: GROUP_FILTER_ALL_TAG forKey: @"FilterGroup"];
3011        [[NSUserDefaults standardUserDefaults] removeObjectForKey: @"FilterSearchString"];
3012    }
3013   
3014    [self applyFilter]; //do even if showing to ensure tooltips are updated
3015}
3016
3017//doesn't save shown state
3018- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3019{
3020    const BOOL prevShown = fFilterBar != nil;
3021    if (show == prevShown)
3022        return;
3023   
3024    if (show)
3025    {
3026        fFilterBar = [[FilterBarController alloc] init];
3027       
3028        NSView * contentView = [fWindow contentView];
3029        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
3030       
3031        NSRect filterBarFrame = [[fFilterBar view] frame];
3032        filterBarFrame.size.width = windowSize.width;
3033        [[fFilterBar view] setFrame: filterBarFrame];
3034       
3035        if (fStatusBar)
3036            [contentView addSubview: [fFilterBar view] positioned: NSWindowBelow relativeTo: [fStatusBar view]];
3037        else
3038            [contentView addSubview: [fFilterBar view]];
3039        const CGFloat originY = fStatusBar ? NSMinY([[fStatusBar view] frame]) : NSMaxY([contentView frame]);
3040        [[fFilterBar view] setFrameOrigin: NSMakePoint(0.0, originY)];
3041    }
3042    else
3043        [fWindow makeFirstResponder: fTableView];
3044   
3045    CGFloat heightChange = NSHeight([[fFilterBar view] frame]);
3046    if (!show)
3047        heightChange *= -1;
3048   
3049    //allow bar to show even if not enough room
3050    if (show && ![fDefaults boolForKey: @"AutoSize"])
3051    {
3052        NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3053        const CGFloat change = NSHeight([[fWindow screen] visibleFrame]) - NSHeight(frame);
3054        if (change < 0.0)
3055        {
3056            frame = [fWindow frame];
3057            frame.size.height += change;
3058            frame.origin.y -= change;
3059            [fWindow setFrame: frame display: NO animate: NO];
3060        }
3061    }
3062   
3063    NSScrollView * scrollView = [fTableView enclosingScrollView];
3064
3065    //set views to not autoresize
3066    const NSUInteger filterMask = [[fFilterBar view] autoresizingMask];
3067    const NSUInteger scrollMask = [scrollView autoresizingMask];
3068    [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
3069    [scrollView setAutoresizingMask: NSViewNotSizable];
3070   
3071    const NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3072    [fWindow setFrame: frame display: YES animate: animate];
3073   
3074    //re-enable autoresize
3075    [[fFilterBar view] setAutoresizingMask: filterMask];
3076    [scrollView setAutoresizingMask: scrollMask];
3077   
3078    if (!show)
3079    {
3080        [[fFilterBar view] removeFromSuperviewWithoutNeedingDisplay];
3081        [fFilterBar release];
3082        fFilterBar = nil;
3083    }
3084   
3085    if ([fDefaults boolForKey: @"AutoSize"])
3086        [self setWindowMinMaxToCurrent];
3087    else
3088    {
3089        //change min size
3090        NSSize minSize = [fWindow contentMinSize];
3091        minSize.height += heightChange;
3092        [fWindow setContentMinSize: minSize];
3093    }
3094}
3095
3096- (void) focusFilterField
3097{
3098    if (!fFilterBar)
3099        [self toggleFilterBar: self];
3100    [fFilterBar focusSearchField];
3101}
3102
3103#warning change from id to QLPreviewPanel
3104- (BOOL) acceptsPreviewPanelControl: (id) panel
3105{
3106    return !fQuitting;
3107}
3108
3109- (void) beginPreviewPanelControl: (id) panel
3110{
3111    fPreviewPanel = [panel retain];
3112    [fPreviewPanel setDelegate: self];
3113    [fPreviewPanel setDataSource: self];
3114}
3115
3116- (void) endPreviewPanelControl: (id) panel
3117{
3118    [fPreviewPanel release];
3119    fPreviewPanel = nil;
3120}
3121
3122- (NSArray *) quickLookableTorrents
3123{
3124    NSArray * selectedTorrents = [fTableView selectedTorrents];
3125    NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3126   
3127    for (Torrent * torrent in selectedTorrents)
3128        if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation])
3129            [qlArray addObject: torrent];
3130   
3131    return qlArray;
3132}
3133
3134- (NSInteger) numberOfPreviewItemsInPreviewPanel: (id) panel
3135{
3136    if ([fInfoController canQuickLook])
3137        return [[fInfoController quickLookURLs] count];
3138    else
3139        return [[self quickLookableTorrents] count];
3140}
3141
3142- (id /*<QLPreviewItem>*/) previewPanel: (id) panel previewItemAtIndex: (NSInteger) index
3143{
3144    if ([fInfoController canQuickLook])
3145        return [[fInfoController quickLookURLs] objectAtIndex: index];
3146    else
3147        return [[self quickLookableTorrents] objectAtIndex: index];
3148}
3149
3150- (BOOL) previewPanel: (id) panel handleEvent: (NSEvent *) event
3151{
3152    /*if ([event type] == NSKeyDown)
3153    {
3154        [super keyDown: event];
3155        return YES;
3156    }*/
3157   
3158    return NO;
3159}
3160
3161- (NSRect) previewPanel: (id) panel sourceFrameOnScreenForPreviewItem: (id /*<QLPreviewItem>*/) item
3162{
3163    if ([fInfoController canQuickLook])
3164        return [fInfoController quickLookSourceFrameForPreviewItem: item];
3165    else
3166    {
3167        if (![fWindow isVisible])
3168            return NSZeroRect;
3169       
3170        const NSInteger row = [fTableView rowForItem: item];
3171        if (row == -1)
3172            return NSZeroRect;
3173       
3174        NSRect frame = [fTableView iconRectForRow: row];
3175       
3176        if (!NSIntersectsRect([fTableView visibleRect], frame))
3177            return NSZeroRect;
3178       
3179        frame.origin = [fTableView convertPoint: frame.origin toView: nil];
3180        frame.origin = [fWindow convertBaseToScreen: frame.origin];
3181        frame.origin.y -= frame.size.height;
3182        return frame;
3183    }
3184}
3185
3186- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3187{
3188    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3189   
3190    NSButton * button = [[NSButton alloc] init];
3191    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3192    [button setStringValue: @""];
3193   
3194    [item setView: button];
3195    [button release];
3196   
3197    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3198    [item setMinSize: buttonSize];
3199    [item setMaxSize: buttonSize];
3200   
3201    return [item autorelease];
3202}
3203
3204- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3205{
3206    if ([ident isEqualToString: TOOLBAR_CREATE])
3207    {
3208        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3209       
3210        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3211        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3212        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3213        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3214        [item setTarget: self];
3215        [item setAction: @selector(createFile:)];
3216        [item setAutovalidates: NO];
3217       
3218        return item;
3219    }
3220    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3221    {
3222        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3223       
3224        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3225        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3226        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3227        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3228        [item setTarget: self];
3229        [item setAction: @selector(openShowSheet:)];
3230        [item setAutovalidates: NO];
3231       
3232        return item;
3233    }
3234    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3235    {
3236        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3237       
3238        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3239        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3240        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3241        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3242        [item setTarget: self];
3243        [item setAction: @selector(openURLShowSheet:)];
3244        [item setAutovalidates: NO];
3245       
3246        return item;
3247    }
3248    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3249    {
3250        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3251       
3252        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3253        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3254        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3255        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3256        [item setTarget: self];
3257        [item setAction: @selector(removeNoDelete:)];
3258        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3259       
3260        return item;
3261    }
3262    else if ([ident isEqualToString: TOOLBAR_INFO])
3263    {
3264        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3265        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3266       
3267        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3268        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3269        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3270        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3271        [item setTarget: self];
3272        [item setAction: @selector(showInfo:)];
3273       
3274        return item;
3275    }
3276    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3277    {
3278        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3279       
3280        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3281        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3282        [groupItem setView: segmentedControl];
3283        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3284       
3285        [segmentedControl setSegmentCount: 2];
3286        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3287       
3288        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3289        [groupItem setMinSize: groupSize];
3290        [groupItem setMaxSize: groupSize];
3291       
3292        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3293        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3294        [groupItem setTarget: self];
3295        [groupItem setAction: @selector(allToolbarClicked:)];
3296       
3297        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3298       
3299        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3300        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3301        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3302                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3303       
3304        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3305        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3306        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3307                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3308       
3309        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3310                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3311       
3312        [segmentedControl release];
3313       
3314        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3315       
3316        return [groupItem autorelease];
3317    }
3318    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3319    {
3320        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3321       
3322        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3323        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3324        [groupItem setView: segmentedControl];
3325        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3326       
3327        [segmentedControl setSegmentCount: 2];
3328        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3329       
3330        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3331        [groupItem setMinSize: groupSize];
3332        [groupItem setMaxSize: groupSize];
3333       
3334        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3335        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3336        [groupItem setTarget: self];
3337        [groupItem setAction: @selector(selectedToolbarClicked:)];
3338       
3339        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3340       
3341        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3342        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3343        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3344                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3345       
3346        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3347        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3348        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3349                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3350       
3351        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3352                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3353       
3354        [segmentedControl release];
3355       
3356        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3357       
3358        return [groupItem autorelease];
3359    }
3360    else if ([ident isEqualToString: TOOLBAR_FILTER])
3361    {
3362        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3363        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3364       
3365        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3366        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3367        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3368        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3369        [item setTarget: self];
3370        [item setAction: @selector(toggleFilterBar:)];
3371       
3372        return item;
3373    }
3374    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3375    {
3376        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3377        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3378       
3379        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3380        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3381        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3382        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3383        [item setTarget: self];
3384        [item setAction: @selector(toggleQuickLook:)];
3385        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow];
3386       
3387        return item;
3388    }
3389    else
3390        return nil;
3391}
3392
3393- (void) allToolbarClicked: (id) sender
3394{
3395    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3396                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3397    switch (tagValue)
3398    {
3399        case TOOLBAR_PAUSE_TAG:
3400            [self stopAllTorrents: sender];
3401            break;
3402        case TOOLBAR_RESUME_TAG:
3403            [self resumeAllTorrents: sender];
3404            break;
3405    }
3406}
3407
3408- (void) selectedToolbarClicked: (id) sender
3409{
3410    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3411                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3412    switch (tagValue)
3413    {
3414        case TOOLBAR_PAUSE_TAG:
3415            [self stopSelectedTorrents: sender];
3416            break;
3417        case TOOLBAR_RESUME_TAG:
3418            [self resumeSelectedTorrents: sender];
3419            break;
3420    }
3421}
3422
3423- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3424{
3425    return [NSArray arrayWithObjects:
3426            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3427            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3428            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3429            NSToolbarSeparatorItemIdentifier,
3430            NSToolbarSpaceItemIdentifier,
3431            NSToolbarFlexibleSpaceItemIdentifier,
3432            NSToolbarCustomizeToolbarItemIdentifier, nil];
3433}
3434
3435- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3436{
3437    return [NSArray arrayWithObjects:
3438            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSpaceItemIdentifier,
3439            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3440            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3441}
3442
3443- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3444{
3445    NSString * ident = [toolbarItem itemIdentifier];
3446   
3447    //enable remove item
3448    if ([ident isEqualToString: TOOLBAR_REMOVE])
3449        return [fTableView numberOfSelectedRows] > 0;
3450
3451    //enable pause all item
3452    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3453    {
3454        for (Torrent * torrent in fTorrents)
3455            if ([torrent isActive] || [torrent waitingToStart])
3456                return YES;
3457        return NO;
3458    }
3459
3460    //enable resume all item
3461    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3462    {
3463        for (Torrent * torrent in fTorrents)
3464            if (![torrent isActive] && ![torrent waitingToStart])
3465                return YES;
3466        return NO;
3467    }
3468
3469    //enable pause item
3470    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3471    {
3472        for (Torrent * torrent in [fTableView selectedTorrents])
3473            if ([torrent isActive] || [torrent waitingToStart])
3474                return YES;
3475        return NO;
3476    }
3477   
3478    //enable resume item
3479    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3480    {
3481        for (Torrent * torrent in [fTableView selectedTorrents])
3482            if (![torrent isActive] && ![torrent waitingToStart])
3483                return YES;
3484        return NO;
3485    }
3486   
3487    //set info item
3488    if ([ident isEqualToString: TOOLBAR_INFO])
3489    {
3490        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3491        return YES;
3492    }
3493   
3494    //set filter item
3495    if ([ident isEqualToString: TOOLBAR_FILTER])
3496    {
3497        [(NSButton *)[toolbarItem view] setState: fFilterBar != nil];
3498        return YES;
3499    }
3500   
3501    //set quick look item
3502    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3503    {
3504        [(NSButton *)[toolbarItem view] setState: [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
3505                                                    && [[QLPreviewPanelSL sharedPreviewPanel] isVisible]];
3506        return [NSApp isOnSnowLeopardOrBetter];
3507    }
3508
3509    return YES;
3510}
3511
3512- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3513{
3514    SEL action = [menuItem action];
3515   
3516    if (action == @selector(toggleSpeedLimit:))
3517    {
3518        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3519        return YES;
3520    }
3521   
3522    //only enable some items if it is in a context menu or the window is useable
3523    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3524
3525    //enable open items
3526    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3527        return [fWindow attachedSheet] == nil;
3528   
3529    //enable sort options
3530    if (action == @selector(setSort:))
3531    {
3532        NSString * sortType;
3533        switch ([menuItem tag])
3534        {
3535            case SORT_ORDER_TAG:
3536                sortType = SORT_ORDER;
3537                break;
3538            case SORT_DATE_TAG:
3539                sortType = SORT_DATE;
3540                break;
3541            case SORT_NAME_TAG:
3542                sortType = SORT_NAME;
3543                break;
3544            case SORT_PROGRESS_TAG:
3545                sortType = SORT_PROGRESS;
3546                break;
3547            case SORT_STATE_TAG:
3548                sortType = SORT_STATE;
3549                break;
3550            case SORT_TRACKER_TAG:
3551                sortType = SORT_TRACKER;
3552                break;
3553            case SORT_ACTIVITY_TAG:
3554                sortType = SORT_ACTIVITY;
3555                break;
3556            case SORT_SIZE_TAG:
3557                sortType = SORT_SIZE;
3558                break;
3559            default:
3560                NSAssert1(NO, @"Unknown sort tag received: %d", [menuItem tag]);
3561        }
3562       
3563        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3564        return [fWindow isVisible];
3565    }
3566   
3567    if (action == @selector(setGroup:))
3568    {
3569        BOOL checked = NO;
3570       
3571        NSInteger index = [menuItem tag];
3572        for (Torrent * torrent in [fTableView selectedTorrents])
3573            if (index == [torrent groupValue])
3574            {
3575                checked = YES;
3576                break;
3577            }
3578       
3579        [menuItem setState: checked ? NSOnState : NSOffState];
3580        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3581    }
3582   
3583    if (action == @selector(toggleSmallView:))
3584    {
3585        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3586        return [fWindow isVisible];
3587    }
3588   
3589    if (action == @selector(togglePiecesBar:))
3590    {
3591        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3592        return [fWindow isVisible];
3593    }
3594   
3595    if (action == @selector(toggleStatusString:))
3596    {
3597        if ([fDefaults boolForKey: @"SmallView"])
3598        {
3599            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3600            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3601        }
3602        else
3603        {
3604            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3605            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3606        }
3607       
3608        return [fWindow isVisible];
3609    }
3610   
3611    if (action == @selector(toggleAvailabilityBar:))
3612    {
3613        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3614        return [fWindow isVisible];
3615    }
3616   
3617    if (action == @selector(setLimitGlobalEnabled:))
3618    {
3619        BOOL upload = [menuItem menu] == fUploadMenu;
3620        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3621        if (limit)
3622            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3623                                    "Action menu -> upload/download limit"),
3624                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3625       
3626        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3627        return YES;
3628    }
3629   
3630    if (action == @selector(setRatioGlobalEnabled:))
3631    {
3632        BOOL check = menuItem == fCheckRatioItem;
3633        if (check)
3634            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3635                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3636       
3637        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3638        return YES;
3639    }
3640
3641    //enable show info
3642    if (action == @selector(showInfo:))
3643    {
3644        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3645                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3646        [menuItem setTitle: title];
3647
3648        return YES;
3649    }
3650   
3651    //enable prev/next inspector tab
3652    if (action == @selector(setInfoTab:))
3653        return [[fInfoController window] isVisible];
3654   
3655    //enable toggle status bar
3656    if (action == @selector(toggleStatusBar:))
3657    {
3658        NSString * title = !fStatusBar ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3659                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3660        [menuItem setTitle: title];
3661
3662        return [fWindow isVisible];
3663    }
3664   
3665    //enable toggle filter bar
3666    if (action == @selector(toggleFilterBar:))
3667    {
3668        NSString * title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3669                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3670        [menuItem setTitle: title];
3671
3672        return [fWindow isVisible];
3673    }
3674   
3675    //enable prev/next filter button
3676    if (action == @selector(switchFilter:))
3677        return [fWindow isVisible] && fFilterBar;
3678   
3679    //enable reveal in finder
3680    if (action == @selector(revealFile:))
3681        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3682
3683    //enable remove items
3684    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
3685    {
3686        BOOL warning = NO;
3687       
3688        for (Torrent * torrent in [fTableView selectedTorrents])
3689        {
3690            if ([torrent isActive])
3691            {
3692                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
3693                {
3694                    warning = YES;
3695                    break;
3696                }
3697            }
3698        }
3699   
3700        //append or remove ellipsis when needed
3701        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3702        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3703        {
3704            if (![title hasSuffix: ellipsis])
3705                [menuItem setTitle: [title stringByAppendingEllipsis]];
3706        }
3707        else
3708        {
3709            if ([title hasSuffix: ellipsis])
3710                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3711        }
3712       
3713        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3714    }
3715   
3716    //remove all completed transfers item
3717    if (action == @selector(clearCompleted:))
3718    {
3719        //append or remove ellipsis when needed
3720        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3721        if ([fDefaults boolForKey: @"WarningRemoveCompleted"])
3722        {
3723            if (![title hasSuffix: ellipsis])
3724                [menuItem setTitle: [title stringByAppendingEllipsis]];
3725        }
3726        else
3727        {
3728            if ([title hasSuffix: ellipsis])
3729                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3730        }
3731       
3732        for (Torrent * torrent in fTorrents)
3733            if ([torrent isFinishedSeeding])
3734                return YES;
3735        return NO;
3736    }
3737
3738    //enable pause all item
3739    if (action == @selector(stopAllTorrents:))
3740    {
3741        for (Torrent * torrent in fTorrents)
3742            if ([torrent isActive] || [torrent waitingToStart])
3743                return YES;
3744        return NO;
3745    }
3746   
3747    //enable resume all item
3748    if (action == @selector(resumeAllTorrents:))
3749    {
3750        for (Torrent * torrent in fTorrents)
3751            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
3752                return YES;
3753        return NO;
3754    }
3755   
3756    //enable resume all waiting item
3757    if (action == @selector(resumeWaitingTorrents:))
3758    {
3759        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3760            return NO;
3761   
3762        for (Torrent * torrent in fTorrents)
3763            if (![torrent isActive] && [torrent waitingToStart])
3764                return YES;
3765        return NO;
3766    }
3767   
3768    //enable resume selected waiting item
3769    if (action == @selector(resumeSelectedTorrentsNoWait:))
3770    {
3771        if (!canUseTable)
3772            return NO;
3773       
3774        for (Torrent * torrent in [fTableView selectedTorrents])
3775            if (![torrent isActive])
3776                return YES;
3777        return NO;
3778    }
3779
3780    //enable pause item
3781    if (action == @selector(stopSelectedTorrents:))
3782    {
3783        if (!canUseTable)
3784            return NO;
3785   
3786        for (Torrent * torrent in [fTableView selectedTorrents])
3787            if ([torrent isActive] || [torrent waitingToStart])
3788                return YES;
3789        return NO;
3790    }
3791   
3792    //enable resume item
3793    if (action == @selector(resumeSelectedTorrents:))
3794    {
3795        if (!canUseTable)
3796            return NO;
3797   
3798        for (Torrent * torrent in [fTableView selectedTorrents])
3799            if (![torrent isActive] && ![torrent waitingToStart])
3800                return YES;
3801        return NO;
3802    }
3803   
3804    //enable manual announce item
3805    if (action == @selector(announceSelectedTorrents:))
3806    {
3807        if (!canUseTable)
3808            return NO;
3809       
3810        for (Torrent * torrent in [fTableView selectedTorrents])
3811            if ([torrent canManualAnnounce])
3812                return YES;
3813        return NO;
3814    }
3815   
3816    //enable reset cache item
3817    if (action == @selector(verifySelectedTorrents:))
3818    {
3819        if (!canUseTable)
3820            return NO;
3821           
3822        for (Torrent * torrent in [fTableView selectedTorrents])
3823            if (![torrent isMagnet])
3824                return YES;
3825        return NO;
3826    }
3827   
3828    //enable move torrent file item
3829    if (action == @selector(moveDataFilesSelected:))
3830        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3831   
3832    //enable copy torrent file item
3833    if (action == @selector(copyTorrentFiles:))
3834    {
3835        if (!canUseTable)
3836            return NO;
3837       
3838        for (Torrent * torrent in [fTableView selectedTorrents])
3839            if (![torrent isMagnet])
3840                return YES;
3841        return NO;
3842    }
3843   
3844    //enable copy torrent file item
3845    if (action == @selector(copyMagnetLinks:))
3846        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3847   
3848    //enable reverse sort item
3849    if (action == @selector(setSortReverse:))
3850    {
3851        const BOOL isReverse = [menuItem tag] == SORT_DESC_TAG;
3852        [menuItem setState: (isReverse == [fDefaults boolForKey: @"SortReverse"]) ? NSOnState : NSOffState];
3853        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3854    }
3855   
3856    //enable group sort item
3857    if (action == @selector(setSortByGroup:))
3858    {
3859        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3860        return YES;
3861    }
3862   
3863    if (action == @selector(toggleQuickLook:))
3864    {
3865        const BOOL visible = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
3866                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
3867        //text consistent with Finder
3868        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
3869                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
3870        [menuItem setTitle: title];
3871       
3872        return [NSApp isOnSnowLeopardOrBetter];
3873    }
3874   
3875    return YES;
3876}
3877
3878- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3879{
3880    switch (messageType)
3881    {
3882        case kIOMessageSystemWillSleep:
3883            //if there are any running transfers, wait 15 seconds for them to stop
3884            for (Torrent * torrent in fTorrents)
3885                if ([torrent isActive])
3886                {
3887                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3888                    for (Torrent * torrent in fTorrents)
3889                        [torrent sleep];
3890                    sleep(15);
3891                    break;
3892                }
3893
3894            IOAllowPowerChange(fRootPort, (long) messageArgument);
3895            break;
3896
3897        case kIOMessageCanSystemSleep:
3898            if ([fDefaults boolForKey: @"SleepPrevent"])
3899            {
3900                //prevent idle sleep unless no torrents are active
3901                for (Torrent * torrent in fTorrents)
3902                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3903                    {
3904                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3905                        return;
3906                    }
3907            }
3908           
3909            IOAllowPowerChange(fRootPort, (long) messageArgument);
3910            break;
3911
3912        case kIOMessageSystemHasPoweredOn:
3913            //resume sleeping transfers after we wake up
3914            for (Torrent * torrent in fTorrents)
3915                [torrent wakeUp];
3916            break;
3917    }
3918}
3919
3920- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3921{
3922    NSInteger seeding = 0, downloading = 0;
3923    for (Torrent * torrent in fTorrents)
3924    {
3925        if ([torrent isSeeding])
3926            seeding++;
3927        else if ([torrent isActive])
3928            downloading++;
3929        else;
3930    }
3931   
3932    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3933            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3934   
3935    BOOL hasSeparator = seedingItem || downloadingItem;
3936   
3937    if (seeding > 0)
3938    {
3939        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3940        if (!seedingItem)
3941        {
3942            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3943            [seedingItem setTag: DOCK_SEEDING_TAG];
3944            [fDockMenu insertItem: seedingItem atIndex: 0];
3945        }
3946        else
3947            [seedingItem setTitle: title];
3948    }
3949    else
3950    {
3951        if (seedingItem)
3952            [fDockMenu removeItem: seedingItem];
3953    }
3954   
3955    if (downloading > 0)
3956    {
3957        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3958        if (!downloadingItem)
3959        {
3960            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3961            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3962            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3963        }
3964        else
3965            [downloadingItem setTitle: title];
3966    }
3967    else
3968    {
3969        if (downloadingItem)
3970            [fDockMenu removeItem: downloadingItem];
3971    }
3972   
3973    if (seeding > 0 || downloading > 0)
3974    {
3975        if (!hasSeparator)
3976            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: (seeding > 0 && downloading > 0) ? 2 : 1];
3977    }
3978    else
3979    {
3980        if (hasSeparator)
3981            [fDockMenu removeItemAtIndex: 0];
3982    }
3983   
3984    return fDockMenu;
3985}
3986
3987- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3988{
3989    //if auto size is enabled, the current frame shouldn't need to change
3990    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3991   
3992    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3993    return frame;
3994}
3995
3996- (void) setWindowSizeToFit
3997{
3998    if ([fDefaults boolForKey: @"AutoSize"])
3999    {
4000        NSScrollView * scrollView = [fTableView enclosingScrollView];
4001       
4002        [scrollView setHasVerticalScroller: NO];
4003        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
4004        [scrollView setHasVerticalScroller: YES];
4005       
4006        //hack to ensure scrollbars don't disappear after resizing
4007        if (![NSApp isOnSnowLeopardOrBetter])
4008        {
4009            [scrollView setAutohidesScrollers: NO];
4010            [scrollView setAutohidesScrollers: YES];
4011        }
4012       
4013        [self setWindowMinMaxToCurrent];
4014    }
4015}
4016
4017- (NSRect) sizedWindowFrame
4018{
4019    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
4020                    ? [fDisplayedTorrents count] : 0;
4021   
4022    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4023                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4024                        - NSHeight([[fTableView enclosingScrollView] frame]);
4025   
4026    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4027}
4028
4029- (void) updateForAutoSize
4030{
4031    if ([fDefaults boolForKey: @"AutoSize"])
4032        [self setWindowSizeToFit];
4033    else
4034    {
4035        NSSize contentMinSize = [fWindow contentMinSize];
4036        contentMinSize.height = [self minWindowContentSizeAllowed];
4037       
4038        [fWindow setContentMinSize: contentMinSize];
4039       
4040        NSSize contentMaxSize = [fWindow contentMaxSize];
4041        contentMaxSize.height = FLT_MAX;
4042        [fWindow setContentMaxSize: contentMaxSize];
4043    }
4044}
4045
4046- (void) setWindowMinMaxToCurrent
4047{
4048    const CGFloat height = NSHeight([[fWindow contentView] frame]);
4049   
4050    NSSize minSize = [fWindow contentMinSize],
4051            maxSize = [fWindow contentMaxSize];
4052    minSize.height = height;
4053    maxSize.height = height;
4054   
4055    [fWindow setContentMinSize: minSize];
4056    [fWindow setContentMaxSize: maxSize];
4057}
4058
4059- (CGFloat) minWindowContentSizeAllowed
4060{
4061    CGFloat contentMinHeight = NSHeight([[fWindow contentView] frame]) - NSHeight([[fTableView enclosingScrollView] frame])
4062                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
4063    return contentMinHeight;
4064}
4065
4066- (void) updateForExpandCollape
4067{
4068    [self setWindowSizeToFit];
4069    [self setBottomCountText: YES];
4070}
4071
4072- (void) showMainWindow: (id) sender
4073{
4074    [fWindow makeKeyAndOrderFront: nil];
4075}
4076
4077- (void) windowDidBecomeMain: (NSNotification *) notification
4078{
4079    [fBadger clearCompleted];
4080    [self updateUI];
4081}
4082
4083- (void) applicationWillUnhide: (NSNotification *) notification
4084{
4085    [self updateUI];
4086}
4087
4088- (void) toggleQuickLook: (id) sender
4089{
4090    if (![NSApp isOnSnowLeopardOrBetter])
4091        return;
4092   
4093    if ([[QLPreviewPanelSL sharedPreviewPanel] isVisible])
4094        [[QLPreviewPanelSL sharedPreviewPanel] orderOut: nil];
4095    else
4096        [[QLPreviewPanelSL sharedPreviewPanel] makeKeyAndOrderFront: nil];
4097}
4098
4099- (void) linkHomepage: (id) sender
4100{
4101    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4102}
4103
4104- (void) linkForums: (id) sender
4105{
4106    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4107}
4108
4109- (void) linkTrac: (id) sender
4110{
4111    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4112}
4113
4114- (void) linkDonate: (id) sender
4115{
4116    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4117}
4118
4119- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4120{
4121    fQuitRequested = YES;
4122}
4123
4124- (NSDictionary *) registrationDictionaryForGrowl
4125{
4126    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4127                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4128    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4129                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4130}
4131
4132- (void) growlNotificationWasClicked: (id) clickContext
4133{
4134    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4135        return;
4136   
4137    NSString * type = [clickContext objectForKey: @"Type"], * location;
4138    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4139            && (location = [clickContext objectForKey: @"Location"]))
4140    {
4141        if ([NSApp isOnSnowLeopardOrBetter])
4142        {
4143            NSURL * file = [NSURL fileURLWithPath: location];
4144            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4145        }
4146        else
4147            [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4148    }
4149}
4150
4151- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4152{
4153    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4154   
4155    //get the torrent
4156    Torrent * torrent = nil;
4157    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED && type != TR_RPC_SESSION_CLOSE))
4158    {
4159        for (torrent in fTorrents)
4160            if (torrentStruct == [torrent torrentStruct])
4161            {
4162                [torrent retain];
4163                break;
4164            }
4165       
4166        if (!torrent)
4167        {
4168            [pool drain];
4169           
4170            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4171            return;
4172        }
4173    }
4174   
4175    switch (type)
4176    {
4177        case TR_RPC_TORRENT_ADDED:
4178            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4179                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4180            break;
4181       
4182        case TR_RPC_TORRENT_STARTED:
4183        case TR_RPC_TORRENT_STOPPED:
4184            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4185            break;
4186       
4187        case TR_RPC_TORRENT_REMOVING:
4188            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4189            break;
4190       
4191        case TR_RPC_TORRENT_TRASHING:
4192            [self performSelectorOnMainThread: @selector(rpcRemoveTorrentDeleteData:) withObject: torrent waitUntilDone: NO];
4193            break;
4194       
4195        case TR_RPC_TORRENT_CHANGED:
4196            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4197            break;
4198       
4199        case TR_RPC_TORRENT_MOVED:
4200            [self performSelectorOnMainThread: @selector(rpcMovedTorrent:) withObject: torrent waitUntilDone: NO];
4201            break;
4202       
4203        case TR_RPC_SESSION_CHANGED:
4204            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4205            break;
4206       
4207        case TR_RPC_SESSION_CLOSE:
4208            fQuitRequested = YES;
4209            [NSApp performSelectorOnMainThread: @selector(terminate:) withObject: self waitUntilDone: NO];
4210            break;
4211       
4212        default:
4213            NSAssert1(NO, @"Unknown RPC command received: %d", type);
4214            [torrent release];
4215    }
4216   
4217    [pool drain];
4218}
4219
4220- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4221{
4222    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4223    [torrentStructPtr release];
4224   
4225    NSString * location = nil;
4226    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4227        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4228   
4229    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4230   
4231    [torrent update];
4232    [fTorrents addObject: torrent];
4233    [torrent release];
4234   
4235    [self updateTorrentsInQueue];
4236}
4237
4238- (void) rpcRemoveTorrent: (Torrent *) torrent
4239{
4240    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4241    [torrent release];
4242}
4243
4244- (void) rpcRemoveTorrentDeleteData: (Torrent *) torrent
4245{
4246    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: YES];
4247    [torrent release];
4248}
4249
4250- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4251{
4252    [torrent update];
4253    [torrent release];
4254   
4255    [self updateUI];
4256    [self applyFilter];
4257    [self updateTorrentHistory];
4258}
4259
4260- (void) rpcChangedTorrent: (Torrent *) torrent
4261{
4262    [torrent update];
4263   
4264    if ([[fTableView selectedTorrents] containsObject: torrent])
4265    {
4266        [fInfoController updateInfoStats]; //this will reload the file table
4267        [fInfoController updateOptions];
4268    }
4269   
4270    [torrent release];
4271}
4272
4273- (void) rpcMovedTorrent: (Torrent *) torrent
4274{
4275    [torrent update];
4276    [torrent updateTimeMachineExclude];
4277   
4278    if ([[fTableView selectedTorrents] containsObject: torrent])
4279        [fInfoController updateInfoStats];
4280   
4281    [torrent release];
4282}
4283
4284@end
Note: See TracBrowser for help on using the repository browser.