source: trunk/macosx/Controller.m @ 12612

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

first go at bringing the libT queue to the Mac client

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