source: trunk/macosx/Controller.m @ 12598

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

Only show a single popover when excessively clicking the global and per-transfer action buttons

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