source: trunk/macosx/Controller.m @ 12619

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

rename updateTorrentsInQueue to a more generic (and appropriate) name

  • Property svn:keywords set to Date Rev Author Id
File size: 158.3 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 12619 2011-08-04 02:03:58Z 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(fullUpdateUI)
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 fullUpdateUI];
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 fullUpdateUI];
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 fullUpdateUI];
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 fullUpdateUI];
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 fullUpdateUI];
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    [self fullUpdateUI];
1225}
1226
1227- (void) stopSelectedTorrents: (id) sender
1228{
1229    [self stopTorrents: [fTableView selectedTorrents]];
1230}
1231
1232- (void) stopAllTorrents: (id) sender
1233{
1234    [self stopTorrents: fTorrents];
1235}
1236
1237- (void) stopTorrents: (NSArray *) torrents
1238{
1239#warning look into stopping all without starting any
1240    //don't want any of these starting then stopping
1241    /*for (Torrent * torrent in torrents)
1242        [torrent setWaitToStart: NO];*/
1243   
1244    for (Torrent * torrent in torrents)
1245        [torrent stopTransfer];
1246   
1247    [self fullUpdateUI];
1248}
1249
1250- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1251{
1252    [torrents retain];
1253
1254    if ([fDefaults boolForKey: @"CheckRemove"])
1255    {
1256        NSUInteger active = 0, downloading = 0;
1257        for (Torrent * torrent in torrents)
1258            if ([torrent isActive])
1259            {
1260                ++active;
1261                if (![torrent isSeeding])
1262                    ++downloading;
1263            }
1264
1265        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
1266        {
1267            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
1268                                    torrents, @"Torrents",
1269                                    [NSNumber numberWithBool: deleteData], @"DeleteData", nil];
1270           
1271            NSString * title, * message;
1272           
1273            const NSInteger selected = [torrents count];
1274            if (selected == 1)
1275            {
1276                NSString * torrentName = [[torrents objectAtIndex: 0] name];
1277               
1278                if (deleteData)
1279                    title = [NSString stringWithFormat:
1280                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1281                                " and trash the data file?", "Removal confirm panel -> title"), torrentName];
1282                else
1283                    title = [NSString stringWithFormat:
1284                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1285                                "Removal confirm panel -> title"), torrentName];
1286               
1287                message = NSLocalizedString(@"This transfer is active."
1288                            " Once removed, continuing the transfer will require the torrent file or magnet link.",
1289                            "Removal confirm panel -> message");
1290            }
1291            else
1292            {
1293                if (deleteData)
1294                    title = [NSString stringWithFormat:
1295                                NSLocalizedString(@"Are you sure you want to remove %@ transfers from the transfer list"
1296                                " and trash the data files?", "Removal confirm panel -> title"), [NSString formattedUInteger: selected]];
1297                else
1298                    title = [NSString stringWithFormat:
1299                                NSLocalizedString(@"Are you sure you want to remove %@ transfers from the transfer list?",
1300                                "Removal confirm panel -> title"), [NSString formattedUInteger: selected]];
1301               
1302                if (selected == active)
1303                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %@ active transfers.",
1304                                "Removal confirm panel -> message part 1"), [NSString formattedUInteger: active]];
1305                else
1306                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %@ transfers (%@ active).",
1307                                "Removal confirm panel -> message part 1"), [NSString formattedUInteger: selected], [NSString formattedUInteger: active]];
1308                message = [message stringByAppendingFormat: @" %@",
1309                            NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files or magnet links.",
1310                            "Removal confirm panel -> message part 2")];
1311            }
1312           
1313            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
1314                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
1315                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
1316            return;
1317        }
1318    }
1319   
1320    [self confirmRemoveTorrents: torrents deleteData: deleteData];
1321}
1322
1323- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (NSDictionary *) dict
1324{
1325    NSArray * torrents = [dict objectForKey: @"Torrents"];
1326    if (returnCode == NSAlertDefaultReturn)
1327        [self confirmRemoveTorrents: torrents deleteData: [[dict objectForKey: @"DeleteData"] boolValue]];
1328    else
1329        [torrents release];
1330   
1331    [dict release];
1332}
1333
1334- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1335{
1336    NSMutableArray * selectedValues = [NSMutableArray arrayWithArray: [fTableView selectedValues]];
1337    [selectedValues removeObjectsInArray: torrents];
1338   
1339#warning look into stopping all without starting any
1340    //don't want any of these starting then stopping
1341    /*for (Torrent * torrent in torrents)
1342        [torrent setWaitToStart: NO];*/
1343   
1344    [fTorrents removeObjectsInArray: torrents];
1345   
1346    //if not removed from displayed torrents, fullUpdateUI might cause a crash
1347    if ([fDisplayedTorrents count] > 0)
1348    {
1349        if ([[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1350        {
1351            for (TorrentGroup * group in fDisplayedTorrents)
1352                [[group torrents] removeObjectsInArray: torrents];
1353        }
1354        else
1355            [fDisplayedTorrents removeObjectsInArray: torrents];
1356    }
1357   
1358    for (Torrent * torrent in torrents)
1359    {
1360        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1361        [fTableView removeCollapsedGroup: [torrent groupValue]];
1362       
1363        //we can't assume the window is active - RPC removal, for example
1364        [fBadger removeTorrent: torrent];
1365       
1366        [torrent closeRemoveTorrent: deleteData];
1367    }
1368   
1369    #warning why do we need them retained?
1370    [torrents release];
1371   
1372    [fTableView selectValues: selectedValues];
1373   
1374    [self fullUpdateUI];
1375}
1376
1377- (void) removeNoDelete: (id) sender
1378{
1379    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO];
1380}
1381
1382- (void) removeDeleteData: (id) sender
1383{
1384    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES];
1385}
1386
1387- (void) clearCompleted: (id) sender
1388{
1389    NSMutableArray * torrents = [[NSMutableArray alloc] init];
1390   
1391    for (Torrent * torrent in fTorrents)
1392        if ([torrent isFinishedSeeding])
1393            [torrents addObject: torrent];
1394   
1395    if ([fDefaults boolForKey: @"WarningRemoveCompleted"])
1396    {
1397        NSString * message, * info;
1398        if ([torrents count] == 1)
1399        {
1400            NSString * torrentName = [[torrents objectAtIndex: 0] name];
1401            message = [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1402                                                                  "Remove completed confirm panel -> title"), torrentName];
1403           
1404            info = NSLocalizedString(@"Once removed, continuing the transfer will require the torrent file or magnet link.",
1405                                     "Remove completed confirm panel -> message");
1406        }
1407        else
1408        {
1409            message = [NSString stringWithFormat: NSLocalizedString(@"Are you sure you want to remove %@ completed transfers from the transfer list?",
1410                                                                  "Remove completed confirm panel -> title"), [NSString formattedUInteger: [torrents count]]];
1411           
1412            info = NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files or magnet links.",
1413                                     "Remove completed confirm panel -> message");
1414        }
1415       
1416        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
1417        [alert setMessageText: message];
1418        [alert setInformativeText: info];
1419        [alert setAlertStyle: NSWarningAlertStyle];
1420        [alert addButtonWithTitle: NSLocalizedString(@"Remove", "Remove completed confirm panel -> button")];
1421        [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Remove completed confirm panel -> button")];
1422        [alert setShowsSuppressionButton: YES];
1423       
1424        const NSInteger returnCode = [alert runModal];
1425        if ([[alert suppressionButton] state])
1426            [fDefaults setBool: NO forKey: @"WarningRemoveCompleted"];
1427       
1428        if (returnCode != NSAlertFirstButtonReturn)
1429            return;
1430    }
1431   
1432    [self confirmRemoveTorrents: torrents deleteData: NO];
1433}
1434
1435- (void) moveDataFilesSelected: (id) sender
1436{
1437    [self moveDataFiles: [fTableView selectedTorrents]];
1438}
1439
1440- (void) moveDataFiles: (NSArray *) torrents
1441{
1442    NSOpenPanel * panel = [NSOpenPanel openPanel];
1443    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1444    [panel setAllowsMultipleSelection: NO];
1445    [panel setCanChooseFiles: NO];
1446    [panel setCanChooseDirectories: YES];
1447    [panel setCanCreateDirectories: YES];
1448   
1449    torrents = [torrents retain];
1450    NSInteger count = [torrents count];
1451    if (count == 1)
1452        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1453                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1454    else
1455        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1456                            "Move torrent -> select destination folder"), count]];
1457       
1458    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1459        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1460}
1461
1462- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) torrents
1463{
1464    if (code == NSOKButton)
1465    {
1466        for (Torrent * torrent in torrents)
1467            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1468    }
1469   
1470    [torrents release];
1471}
1472
1473- (void) copyTorrentFiles: (id) sender
1474{
1475    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1476}
1477
1478- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1479{
1480    if ([torrents count] == 0)
1481    {
1482        [torrents release];
1483        return;
1484    }
1485   
1486    Torrent * torrent = [torrents objectAtIndex: 0];
1487   
1488    if (![torrent isMagnet] && [[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1489    {
1490        NSSavePanel * panel = [NSSavePanel savePanel];
1491        [panel setAllowedFileTypes: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]];
1492        [panel setExtensionHidden: NO];
1493       
1494        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1495            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1496    }
1497    else
1498    {
1499        if (![torrent isMagnet])
1500        {
1501            NSAlert * alert = [[NSAlert alloc] init];
1502            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1503            [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1504                                    "Torrent file copy alert -> title"), [torrent name]]];
1505            [alert setInformativeText: [NSString stringWithFormat:
1506                    NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1507                                        [torrent torrentLocation]]];
1508            [alert setAlertStyle: NSWarningAlertStyle];
1509           
1510            [alert runModal];
1511            [alert release];
1512        }
1513       
1514        [torrents removeObjectAtIndex: 0];
1515        [self copyTorrentFileForTorrents: torrents];
1516    }
1517}
1518
1519- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSMutableArray *) torrents
1520{
1521    //copy torrent to new location with name of data file
1522    if (code == NSOKButton)
1523        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1524   
1525    [torrents removeObjectAtIndex: 0];
1526    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1527}
1528
1529- (void) copyMagnetLinks: (id) sender
1530{
1531    NSArray * torrents = [fTableView selectedTorrents];
1532   
1533    if ([torrents count] <= 0)
1534        return;
1535   
1536    NSMutableArray * links = [NSMutableArray arrayWithCapacity: [torrents count]];
1537    for (Torrent * torrent in torrents)
1538        [links addObject: [torrent magnetLink]];
1539   
1540    NSString * text = [links componentsJoinedByString: @"\n"];
1541   
1542    NSPasteboard * pb = [NSPasteboard generalPasteboard];
1543    if ([NSApp isOnSnowLeopardOrBetter])
1544    {
1545        [pb clearContents];
1546        [pb writeObjects: [NSArray arrayWithObject: text]];
1547    }
1548    else
1549    {
1550        [pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: nil];
1551        [pb setString: text forType: NSStringPboardType];
1552    }
1553}
1554
1555- (void) revealFile: (id) sender
1556{
1557    NSArray * selected = [fTableView selectedTorrents];
1558    if ([NSApp isOnSnowLeopardOrBetter])
1559    {
1560        NSMutableArray * paths = [NSMutableArray arrayWithCapacity: [selected count]];
1561        for (Torrent * torrent in selected)
1562        {
1563            NSString * location = [torrent dataLocation];
1564            if (location)
1565                [paths addObject: [NSURL fileURLWithPath: location]];
1566        }
1567       
1568        if ([paths count] > 0)
1569            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: paths];
1570    }
1571    else
1572    {
1573        for (Torrent * torrent in selected)
1574        {
1575            NSString * location = [torrent dataLocation];
1576            if (location)
1577                [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
1578        }
1579    }
1580}
1581
1582- (void) announceSelectedTorrents: (id) sender
1583{
1584    for (Torrent * torrent in [fTableView selectedTorrents])
1585    {
1586        if ([torrent canManualAnnounce])
1587            [torrent manualAnnounce];
1588    }
1589}
1590
1591- (void) verifySelectedTorrents: (id) sender
1592{
1593    [self verifyTorrents: [fTableView selectedTorrents]];
1594}
1595
1596- (void) verifyTorrents: (NSArray *) torrents
1597{
1598    for (Torrent * torrent in torrents)
1599        [torrent resetCache];
1600   
1601    [self applyFilter];
1602}
1603
1604- (void) showPreferenceWindow: (id) sender
1605{
1606    NSWindow * window = [fPrefsController window];
1607    if (![window isVisible])
1608        [window center];
1609
1610    [window makeKeyAndOrderFront: nil];
1611}
1612
1613- (void) showAboutWindow: (id) sender
1614{
1615    [[AboutWindowController aboutController] showWindow: nil];
1616}
1617
1618- (void) showInfo: (id) sender
1619{
1620    if ([[fInfoController window] isVisible])
1621        [fInfoController close];
1622    else
1623    {
1624        [fInfoController updateInfoStats];
1625        [[fInfoController window] orderFront: nil];
1626       
1627        if ([fInfoController canQuickLook]
1628            && [QLPreviewPanelSL sharedPreviewPanelExists] && [[QLPreviewPanelSL sharedPreviewPanel] isVisible])
1629            [[QLPreviewPanelSL sharedPreviewPanel] reloadData];
1630       
1631    }
1632   
1633    [[fWindow toolbar] validateVisibleItems];
1634}
1635
1636- (void) resetInfo
1637{
1638    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1639   
1640    if ([NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
1641        && [[QLPreviewPanelSL sharedPreviewPanel] isVisible])
1642        [[QLPreviewPanelSL sharedPreviewPanel] reloadData];
1643}
1644
1645- (void) setInfoTab: (id) sender
1646{
1647    if (sender == fNextInfoTabItem)
1648        [fInfoController setNextTab];
1649    else
1650        [fInfoController setPreviousTab];
1651}
1652
1653- (void) showMessageWindow: (id) sender
1654{
1655    if (!fMessageController)
1656        fMessageController = [[MessageWindowController alloc] init];
1657    [fMessageController showWindow: nil];
1658}
1659
1660- (void) showStatsWindow: (id) sender
1661{
1662    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1663}
1664
1665- (void) updateUI
1666{
1667    [fTorrents makeObjectsPerformSelector: @selector(update)];
1668   
1669    //pull the upload and download speeds - most consistent by using current stats
1670    CGFloat dlRate = 0.0, ulRate = 0.0;
1671    BOOL completed = NO;
1672    for (Torrent * torrent in fTorrents)
1673    {
1674        dlRate += [torrent downloadRate];
1675        ulRate += [torrent uploadRate];
1676       
1677        completed |= [torrent isFinishedSeeding];
1678    }
1679   
1680    if (![NSApp isHidden])
1681    {
1682        if ([fWindow isVisible])
1683        {
1684            [self sortTorrents];
1685           
1686            [fStatusBar updateWithDownload: dlRate upload: ulRate];
1687           
1688            [fClearCompletedButton setHidden: !completed];
1689        }
1690
1691        //update non-constant parts of info window
1692        if ([[fInfoController window] isVisible])
1693            [fInfoController updateInfoStats];
1694    }
1695   
1696    //badge dock
1697    [fBadger updateBadgeWithDownload: dlRate upload: ulRate];
1698}
1699
1700#warning can this be removed or refined?
1701- (void) fullUpdateUI
1702{
1703    [self updateUI];
1704    [self applyFilter];
1705    [[fWindow toolbar] validateVisibleItems];
1706    [self updateTorrentHistory];
1707}
1708
1709- (void) setBottomCountText: (BOOL) filtering
1710{
1711    NSString * totalTorrentsString;
1712    NSUInteger totalCount = [fTorrents count];
1713    if (totalCount != 1)
1714        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Status bar transfer count"),
1715                                [NSString formattedUInteger: totalCount]];
1716    else
1717        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1718   
1719    if (filtering)
1720    {
1721        NSUInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1722        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1723            count -= [fDisplayedTorrents count];
1724       
1725        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Status bar transfer count"),
1726                                [NSString formattedUInteger: count], totalTorrentsString];
1727    }
1728   
1729    [fTotalTorrentsField setStringValue: totalTorrentsString];
1730}
1731
1732- (void) torrentFinishedDownloading: (NSNotification *) notification
1733{
1734    Torrent * torrent = [notification object];
1735   
1736    if ([[[notification userInfo] objectForKey: @"WasRunning"] boolValue])
1737    {
1738        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1739        {
1740            NSSound * sound;
1741            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1742            {
1743                [sound setDelegate: self];
1744                fSoundPlaying = YES;
1745                [sound play];
1746            }
1747        }
1748       
1749        NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_DOWNLOAD_COMPLETE forKey: @"Type"];
1750       
1751        NSString * location = [torrent dataLocation];
1752        if (location)
1753            [clickContext setObject: location forKey: @"Location"];
1754       
1755        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1756                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1757                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1758       
1759        if (![fWindow isMainWindow])
1760            [fBadger addCompletedTorrent: torrent];
1761       
1762        //bounce download stack
1763        [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"com.apple.DownloadFileFinished"
1764            object: [torrent dataLocation]];
1765    }
1766   
1767    [self fullUpdateUI];
1768}
1769
1770#warning remove?
1771- (void) torrentRestartedDownloading: (NSNotification *) notification
1772{
1773    [self fullUpdateUI];
1774}
1775
1776- (void) torrentFinishedSeeding: (NSNotification *) notification
1777{
1778    Torrent * torrent = [notification object];
1779   
1780    [self fullUpdateUI];
1781   
1782    if ([[fTableView selectedTorrents] containsObject: torrent])
1783    {
1784        [fInfoController updateInfoStats];
1785        [fInfoController updateOptions];
1786    }
1787   
1788    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1789    {
1790        NSSound * sound;
1791        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1792        {
1793            [sound setDelegate: self];
1794            fSoundPlaying = YES;
1795            [sound play];
1796        }
1797    }
1798   
1799    NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_SEEDING_COMPLETE forKey: @"Type"];
1800   
1801    NSString * location = [torrent dataLocation];
1802    if (location)
1803        [clickContext setObject: location forKey: @"Location"];
1804   
1805    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1806                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1807                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1808}
1809
1810- (void) updateTorrentHistory
1811{
1812    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1813   
1814    for (Torrent * torrent in fTorrents)
1815        [history addObject: [torrent history]];
1816   
1817    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST] atomically: YES];
1818}
1819
1820- (void) setSort: (id) sender
1821{
1822    NSString * sortType;
1823    switch ([sender tag])
1824    {
1825        case SORT_ORDER_TAG:
1826            sortType = SORT_ORDER;
1827            [fDefaults setBool: NO forKey: @"SortReverse"];
1828            break;
1829        case SORT_DATE_TAG:
1830            sortType = SORT_DATE;
1831            break;
1832        case SORT_NAME_TAG:
1833            sortType = SORT_NAME;
1834            break;
1835        case SORT_PROGRESS_TAG:
1836            sortType = SORT_PROGRESS;
1837            break;
1838        case SORT_STATE_TAG:
1839            sortType = SORT_STATE;
1840            break;
1841        case SORT_TRACKER_TAG:
1842            sortType = SORT_TRACKER;
1843            break;
1844        case SORT_ACTIVITY_TAG:
1845            sortType = SORT_ACTIVITY;
1846            break;
1847        case SORT_SIZE_TAG:
1848            sortType = SORT_SIZE;
1849            break;
1850        default:
1851            NSAssert1(NO, @"Unknown sort tag received: %d", [sender tag]);
1852            return;
1853    }
1854   
1855    [fDefaults setObject: sortType forKey: @"Sort"];
1856    [self applyFilter]; //better than calling sortTorrents because it will even apply to queue order
1857}
1858
1859- (void) setSortByGroup: (id) sender
1860{
1861    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1862    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1863   
1864    //expand all groups
1865    if (sortByGroup)
1866        [fTableView removeAllCollapsedGroups];
1867   
1868    [self applyFilter];
1869}
1870
1871- (void) setSortReverse: (id) sender
1872{
1873    const BOOL setReverse = [sender tag] == SORT_DESC_TAG;
1874    if (setReverse != [fDefaults boolForKey: @"SortReverse"])
1875    {
1876        [fDefaults setBool: setReverse forKey: @"SortReverse"];
1877        [self sortTorrents];
1878    }
1879}
1880
1881- (void) sortTorrents
1882{
1883    NSArray * selectedValues = [fTableView selectedValues];
1884   
1885    [self sortTorrentsIgnoreSelected]; //actually sort
1886   
1887    [fTableView selectValues: selectedValues];
1888}
1889
1890- (void) sortTorrentsIgnoreSelected
1891{
1892    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1893   
1894    if (![sortType isEqualToString: SORT_ORDER])
1895    {
1896        const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1897       
1898        NSArray * descriptors;
1899        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1900                                                selector: @selector(compareFinder:)] autorelease];
1901       
1902        if ([sortType isEqualToString: SORT_STATE])
1903        {
1904            NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1905                            * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1906                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1907           
1908            descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1909                                                                nameDescriptor, nil];
1910        }
1911        else if ([sortType isEqualToString: SORT_PROGRESS])
1912        {
1913            NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1914                            * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1915                                                            ascending: asc] autorelease],
1916                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1917           
1918            descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1919                                                                nameDescriptor, nil];
1920        }
1921        else if ([sortType isEqualToString: SORT_TRACKER])
1922        {
1923            NSSortDescriptor * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerSortKey" ascending: asc
1924                                                    selector: @selector(localizedCaseInsensitiveCompare:)] autorelease];
1925           
1926            descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, nil];
1927        }
1928        else if ([sortType isEqualToString: SORT_ACTIVITY])
1929        {
1930            NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1931            NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1932                                                        autorelease];
1933           
1934            descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
1935        }
1936        else if ([sortType isEqualToString: SORT_DATE])
1937        {
1938            NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1939           
1940            descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
1941        }
1942        else if ([sortType isEqualToString: SORT_SIZE])
1943        {
1944            NSSortDescriptor * sizeDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"size" ascending: asc] autorelease];
1945           
1946            descriptors = [[NSArray alloc] initWithObjects: sizeDescriptor, nameDescriptor, nil];
1947        }
1948        else
1949            descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, nil];
1950       
1951        //actually sort
1952        if ([fDefaults boolForKey: @"SortByGroup"])
1953        {
1954            for (TorrentGroup * group in fDisplayedTorrents)
1955                [[group torrents] sortUsingDescriptors: descriptors];
1956        }
1957        else
1958            [fDisplayedTorrents sortUsingDescriptors: descriptors];
1959       
1960        [descriptors release];
1961    }
1962   
1963    [fTableView reloadData];
1964}
1965
1966- (void) applyFilter
1967{
1968    //get all the torrents in the table
1969    NSMutableArray * previousTorrents;
1970    if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1971    {
1972        previousTorrents = [NSMutableArray array];
1973       
1974        for (TorrentGroup * group in fDisplayedTorrents)
1975            [previousTorrents addObjectsFromArray: [group torrents]];
1976    }
1977    else
1978        previousTorrents = fDisplayedTorrents;
1979   
1980    NSArray * selectedValues = [fTableView selectedValues];
1981   
1982    NSUInteger active = 0, downloading = 0, seeding = 0, paused = 0;
1983    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1984    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1985    if ([filterType isEqualToString: FILTER_ACTIVE])
1986        filterActive = YES;
1987    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1988        filterDownload = YES;
1989    else if ([filterType isEqualToString: FILTER_SEED])
1990        filterSeed = YES;
1991    else if ([filterType isEqualToString: FILTER_PAUSE])
1992        filterPause = YES;
1993    else
1994        filterStatus = NO;
1995   
1996    const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
1997    const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
1998   
1999    NSString * searchString = [fFilterBar searchString];
2000    if (searchString && [searchString isEqualToString: @""])
2001        searchString = nil;
2002    const BOOL filterTracker = searchString && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
2003   
2004    NSMutableArray * allTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2005   
2006    //get count of each type
2007    for (Torrent * torrent in fTorrents)
2008    {
2009        //check status
2010        if ([torrent isActive] && ![torrent isCheckingWaiting])
2011        {
2012            const BOOL isActive = ![torrent isStalled];
2013            if (isActive)
2014                ++active;
2015           
2016            if ([torrent isSeeding])
2017            {
2018                ++seeding;
2019                if (filterStatus && !((filterActive && isActive) || filterSeed))
2020                    continue;
2021            }
2022            else
2023            {
2024                ++downloading;
2025                if (filterStatus && !((filterActive && isActive) || filterDownload))
2026                    continue;
2027            }
2028        }
2029        else
2030        {
2031            ++paused;
2032            if (filterStatus && !filterPause)
2033                continue;
2034        }
2035       
2036        //checkGroup
2037        if (filterGroup)
2038            if ([torrent groupValue] != groupFilterValue)
2039                continue;
2040       
2041        //check text field
2042        if (searchString)
2043        {
2044            if (filterTracker)
2045            {
2046                BOOL removeTextField = YES;
2047                for (NSString * tracker in [torrent allTrackersFlat])
2048                {
2049                    if ([tracker rangeOfString: searchString options:
2050                            (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound)
2051                    {
2052                        removeTextField = NO;
2053                        break;
2054                    }
2055                }
2056               
2057                if (removeTextField)
2058                    continue;
2059            }
2060            else
2061            {
2062                if ([[torrent name] rangeOfString: searchString options:
2063                        (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound)
2064                    continue;
2065            }
2066        }
2067       
2068        [allTorrents addObject: torrent];
2069    }
2070   
2071    //set button tooltips
2072    if (fFilterBar)
2073        [fFilterBar setCountAll: [fTorrents count] active: active downloading: downloading seeding: seeding paused: paused];
2074   
2075    //clear display cache for not-shown torrents
2076    [previousTorrents removeObjectsInArray: allTorrents];
2077    for (Torrent * torrent in previousTorrents)
2078        [torrent setPreviousFinishedPieces: nil];
2079   
2080    //place torrents into groups
2081    const BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"];
2082    if (groupRows)
2083    {
2084        NSMutableArray * oldTorrentGroups = [NSMutableArray array];
2085        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2086            [oldTorrentGroups addObjectsFromArray: fDisplayedTorrents];
2087       
2088        [fDisplayedTorrents removeAllObjects];
2089       
2090        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2091        [allTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2092       
2093        TorrentGroup * group = nil;
2094        NSInteger lastGroupValue = -2, currentOldGroupIndex = 0;
2095        for (Torrent * torrent in allTorrents)
2096        {
2097            const NSInteger groupValue = [torrent groupValue];
2098            if (groupValue != lastGroupValue)
2099            {
2100                lastGroupValue = groupValue;
2101               
2102                group = nil;
2103               
2104                //try to see if the group already exists
2105                for (; currentOldGroupIndex < [oldTorrentGroups count]; ++currentOldGroupIndex)
2106                {
2107                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
2108                    const NSInteger currentGroupValue = [currentGroup groupIndex];
2109                    if (currentGroupValue == groupValue)
2110                    {
2111                        group = currentGroup;
2112                        [[currentGroup torrents] removeAllObjects];
2113                       
2114                        ++currentOldGroupIndex;
2115                    }
2116                   
2117                    if (currentGroupValue >= groupValue)
2118                        break;
2119                }
2120               
2121                if (!group)
2122                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2123                [fDisplayedTorrents addObject: group];
2124            }
2125           
2126            NSAssert(group != nil, @"No group object to add torrents to");
2127            [[group torrents] addObject: torrent];
2128        }
2129    }
2130    else
2131        [fDisplayedTorrents setArray: allTorrents];
2132   
2133    //actually sort
2134    [self sortTorrentsIgnoreSelected];
2135   
2136    //reset expanded/collapsed rows
2137    if (groupRows)
2138    {
2139        for (TorrentGroup * group in fDisplayedTorrents)
2140        {
2141            if ([fTableView isGroupCollapsed: [group groupIndex]])
2142                [fTableView collapseItem: group];
2143            else
2144                [fTableView expandItem: group];
2145        }
2146    }
2147   
2148    [fTableView selectValues: selectedValues];
2149    [self resetInfo]; //if group is already selected, but the torrents in it change
2150   
2151    [self setBottomCountText: groupRows || filterStatus || filterGroup || searchString];
2152   
2153    [self setWindowSizeToFit];
2154}
2155
2156- (void) switchFilter: (id) sender
2157{
2158    [fFilterBar switchFilter: sender == fNextFilterItem];
2159}
2160
2161- (IBAction) showGlobalPopover: (id) sender
2162{
2163    if ([NSApp isOnLionOrBetter])
2164    {
2165        if (fGlobalPopoverShown)
2166            return;
2167       
2168        NSPopover * popover = [[NSPopoverLion alloc] init];
2169        [popover setBehavior: NSPopoverBehaviorTransient];
2170        GlobalOptionsPopoverViewController * viewController = [[GlobalOptionsPopoverViewController alloc] initWithHandle: [PrefsController handle]];
2171        [popover setContentViewController: viewController];
2172        [popover setDelegate: self];
2173       
2174        [popover showRelativeToRect: [sender frame] ofView: sender preferredEdge: NSMaxYEdge];
2175       
2176        [viewController release];
2177        [popover release];
2178    }
2179    else
2180    {
2181        //place menu below button
2182        NSRect rect = [sender frame];
2183        NSPoint location = rect.origin;
2184        location.y += NSHeight(rect) + 5.0;
2185       
2186        if ([NSApp isOnSnowLeopardOrBetter])
2187            [fActionMenu popUpMenuPositioningItem: nil atLocation: location inView: sender];
2188        else
2189        {
2190            NSEvent * newEvent = [NSEvent mouseEventWithType: NSLeftMouseDown location: location
2191                                               modifierFlags: NSLeftMouseDownMask timestamp: GetCurrentEventTime() windowNumber: [fWindow windowNumber]
2192                                                     context: nil eventNumber: 1 clickCount: 1 pressure: 1];
2193             
2194            [NSMenu popUpContextMenu: fActionMenu withEvent: newEvent forView: sender];
2195        }
2196    }
2197}
2198
2199//don't show multiple popovers when clicking the gear button repeatedly
2200- (void) popoverWillShow: (NSNotification *) notification
2201{
2202    fGlobalPopoverShown = YES;
2203}
2204
2205- (void) popoverWillClose: (NSNotification *) notification
2206{
2207    fGlobalPopoverShown = NO;
2208}
2209
2210- (void) menuNeedsUpdate: (NSMenu *) menu
2211{
2212    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2213    {
2214        for (NSInteger i = [menu numberOfItems]-1; i >= 0; i--)
2215            [menu removeItemAtIndex: i];
2216       
2217        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2218       
2219        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2220        for (NSInteger i = 0; i < groupMenuCount; i++)
2221        {
2222            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2223            [groupMenu removeItemAtIndex: 0];
2224            [menu addItem: item];
2225            [item release];
2226        }
2227    }
2228    else if (menu == fUploadMenu || menu == fDownloadMenu)
2229    {
2230        if ([menu numberOfItems] > 3)
2231            return;
2232       
2233        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2234       
2235        NSMenuItem * item;
2236        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2237        {
2238            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2239                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2240                    keyEquivalent: @""];
2241            [item setTarget: self];
2242            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2243            [menu addItem: item];
2244            [item release];
2245        }
2246    }
2247    else if (menu == fRatioStopMenu)
2248    {
2249        if ([menu numberOfItems] > 3)
2250            return;
2251       
2252        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2253       
2254        NSMenuItem * item;
2255        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2256        {
2257            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2258                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2259            [item setTarget: self];
2260            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2261            [menu addItem: item];
2262            [item release];
2263        }
2264    }
2265    else;
2266}
2267
2268- (void) setGroup: (id) sender
2269{
2270    for (Torrent * torrent in [fTableView selectedTorrents])
2271    {
2272        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2273       
2274        [torrent setGroupValue: [sender tag]];
2275    }
2276   
2277    [self applyFilter];
2278    [self updateUI];
2279    [self updateTorrentHistory];
2280}
2281
2282- (void) toggleSpeedLimit: (id) sender
2283{
2284    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2285    [self speedLimitChanged: sender];
2286}
2287
2288- (void) speedLimitChanged: (id) sender
2289{
2290    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2291    [fStatusBar updateSpeedFieldsToolTips];
2292}
2293
2294//dict has been retained
2295- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2296{
2297    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2298
2299    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2300    [fStatusBar updateSpeedFieldsToolTips];
2301   
2302    if (![[dict objectForKey: @"ByUser"] boolValue])
2303        [GrowlApplicationBridge notifyWithTitle: isLimited
2304                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2305                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2306            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2307            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2308   
2309    [dict release];
2310}
2311
2312- (void) setLimitGlobalEnabled: (id) sender
2313{
2314    BOOL upload = [sender menu] == fUploadMenu;
2315    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2316   
2317    [fPrefsController applySpeedSettings: nil];
2318}
2319
2320- (void) setQuickLimitGlobal: (id) sender
2321{
2322    BOOL upload = [sender menu] == fUploadMenu;
2323    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2324    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2325   
2326    [fPrefsController updateLimitFields];
2327    [fPrefsController applySpeedSettings: nil];
2328}
2329
2330- (void) setRatioGlobalEnabled: (id) sender
2331{
2332    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2333   
2334    [fPrefsController applyRatioSetting: nil];
2335}
2336
2337- (void) setQuickRatioGlobal: (id) sender
2338{
2339    [fDefaults setBool: YES forKey: @"RatioCheck"];
2340    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2341   
2342    [fPrefsController updateRatioStopFieldOld];
2343}
2344
2345- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2346{
2347    fSoundPlaying = NO;
2348}
2349
2350- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2351{
2352    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2353    {
2354        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2355            return;
2356       
2357        if (fAutoImportTimer)
2358        {
2359            if ([fAutoImportTimer isValid])
2360                [fAutoImportTimer invalidate];
2361            [fAutoImportTimer release];
2362            fAutoImportTimer = nil;
2363        }
2364       
2365        //check again in 10 seconds in case torrent file wasn't complete
2366        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2367            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2368       
2369        [self checkAutoImportDirectory];
2370    }
2371}
2372
2373- (void) changeAutoImport
2374{
2375    if (fAutoImportTimer)
2376    {
2377        if ([fAutoImportTimer isValid])
2378            [fAutoImportTimer invalidate];
2379        [fAutoImportTimer release];
2380        fAutoImportTimer = nil;
2381    }
2382   
2383    if (fAutoImportedNames)
2384    {
2385        [fAutoImportedNames release];
2386        fAutoImportedNames = nil;
2387    }
2388   
2389    [self checkAutoImportDirectory];
2390}
2391
2392- (void) checkAutoImportDirectory
2393{
2394    NSString * path;
2395    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2396        return;
2397   
2398    path = [path stringByExpandingTildeInPath];
2399   
2400    NSArray * importedNames;
2401    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2402        return;
2403   
2404    //only check files that have not been checked yet
2405    NSMutableArray * newNames = [importedNames mutableCopy];
2406   
2407    if (fAutoImportedNames)
2408        [newNames removeObjectsInArray: fAutoImportedNames];
2409    else
2410        fAutoImportedNames = [[NSMutableArray alloc] init];
2411    [fAutoImportedNames setArray: importedNames];
2412   
2413    for (NSString * file in newNames)
2414    {
2415        if ([file hasPrefix: @"."])
2416            continue;
2417       
2418        NSString * fullFile = [path stringByAppendingPathComponent: file];
2419       
2420        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2421                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2422            continue;
2423       
2424        tr_ctor * ctor = tr_ctorNew(fLib);
2425        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2426       
2427        switch (tr_torrentParse(ctor, NULL))
2428        {
2429            case TR_PARSE_OK:
2430                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2431               
2432                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2433                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2434                    clickContext: nil];
2435                break;
2436           
2437            case TR_PARSE_ERR:
2438                [fAutoImportedNames removeObject: file];
2439                break;
2440           
2441            case TR_PARSE_DUPLICATE: //let's ignore this (but silence a warning)
2442                break;
2443        }
2444       
2445        tr_ctorFree(ctor);
2446    }
2447   
2448    [newNames release];
2449}
2450
2451- (void) beginCreateFile: (NSNotification *) notification
2452{
2453    if (![fDefaults boolForKey: @"AutoImport"])
2454        return;
2455   
2456    NSString * location = [notification object],
2457            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2458   
2459    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2460                                    isEqualToString: [path stringByExpandingTildeInPath]])
2461        [fAutoImportedNames addObject: [location lastPathComponent]];
2462}
2463
2464- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2465{
2466    if (item)
2467        return [[item torrents] count];
2468    else
2469        return [fDisplayedTorrents count];
2470}
2471
2472- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2473{
2474    if (item)
2475        return [[item torrents] objectAtIndex: index];
2476    else
2477        return [fDisplayedTorrents objectAtIndex: index];
2478}
2479
2480- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2481{
2482    return ![item isKindOfClass: [Torrent class]];
2483}
2484
2485- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2486{
2487    if ([item isKindOfClass: [Torrent class]]) {
2488        if (tableColumn)
2489            return nil;
2490        return [item hashString];
2491    }
2492    else
2493    {
2494        NSString * ident = [tableColumn identifier];
2495        if ([ident isEqualToString: @"Group"])
2496        {
2497            NSInteger group = [item groupIndex];
2498            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2499                                : NSLocalizedString(@"No Group", "Group table row");
2500        }
2501        else if ([ident isEqualToString: @"Color"])
2502        {
2503            NSInteger group = [item groupIndex];
2504            return [[GroupsController groups] imageForIndex: group];
2505        }
2506        else if ([ident isEqualToString: @"DL Image"])
2507            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2508        else if ([ident isEqualToString: @"UL Image"])
2509            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2510                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2511        else
2512        {
2513            TorrentGroup * group = (TorrentGroup *)item;
2514           
2515            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2516                return [NSString stringForRatio: [group ratio]];
2517            else
2518            {
2519                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2520                return [NSString stringForSpeed: rate];
2521            }
2522        }
2523    }
2524}
2525
2526- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2527{
2528    //only allow reordering of rows if sorting by order
2529    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2530    {
2531        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2532        for (id torrent in items)
2533        {
2534            if (![torrent isKindOfClass: [Torrent class]])
2535                return NO;
2536           
2537            [indexSet addIndex: [fTableView rowForItem: torrent]];
2538        }
2539       
2540        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2541        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2542        return YES;
2543    }
2544    return NO;
2545}
2546
2547- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2548    proposedChildIndex: (NSInteger) index
2549{
2550    NSPasteboard * pasteboard = [info draggingPasteboard];
2551    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2552    {
2553        if ([fDefaults boolForKey: @"SortByGroup"])
2554        {
2555            if (!item)
2556                return NSDragOperationNone;
2557           
2558            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2559            {
2560                if ([item isKindOfClass: [Torrent class]])
2561                {
2562                    TorrentGroup * group = [fTableView parentForItem: item];
2563                    index = [[group torrents] indexOfObject: item] + 1;
2564                    item = group;
2565                }
2566            }
2567            else
2568            {
2569                if ([item isKindOfClass: [Torrent class]])
2570                    item = [fTableView parentForItem: item];
2571                index = NSOutlineViewDropOnItemIndex;
2572            }
2573        }
2574        else
2575        {
2576            if (item)
2577            {
2578                index = [fTableView rowForItem: item] + 1;
2579                item = nil;
2580            }
2581        }
2582       
2583        [fTableView setDropItem: item dropChildIndex: index];
2584        return NSDragOperationGeneric;
2585    }
2586   
2587    return NSDragOperationNone;
2588}
2589
2590- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2591    childIndex: (NSInteger) newRow
2592{
2593    NSPasteboard * pasteboard = [info draggingPasteboard];
2594    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2595    {
2596        //remember selected rows
2597        NSArray * selectedValues = [fTableView selectedValues];
2598   
2599        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2600       
2601        //get the torrents to move
2602        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2603        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2604            [movingTorrents addObject: [fTableView itemAtRow: i]];
2605       
2606        //reset groups
2607        if (item)
2608        {
2609            //change groups
2610            NSInteger groupValue = [item groupIndex];
2611            for (Torrent * torrent in movingTorrents)
2612            {
2613                //have to reset objects here to avoid weird crash
2614                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2615                [[item torrents] addObject: torrent];
2616               
2617                [torrent setGroupValue: groupValue];
2618            }
2619            //part 2 of avoiding weird crash
2620            [fTableView reloadItem: nil reloadChildren: YES];
2621        }
2622       
2623        //reorder queue order
2624        if (newRow != NSOutlineViewDropOnItemIndex)
2625        {
2626            //find torrent to place under
2627            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2628            Torrent * topTorrent = nil;
2629            for (NSInteger i = newRow-1; i >= 0; i--)
2630            {
2631                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2632                if (![movingTorrents containsObject: tempTorrent])
2633                {
2634                    topTorrent = tempTorrent;
2635                    break;
2636                }
2637            }
2638           
2639            //remove objects to reinsert
2640            [fTorrents removeObjectsInArray: movingTorrents];
2641           
2642            //insert objects at new location
2643            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2644            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2645            for (Torrent * torrent in movingTorrents)
2646                [torrent setQueueIndex: insertIndex++];
2647            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2648        }
2649       
2650        [self applyFilter];
2651        [fTableView selectValues: selectedValues];
2652    }
2653   
2654    return YES;
2655}
2656
2657- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2658{
2659    [self resetInfo];
2660    [[fWindow toolbar] validateVisibleItems];
2661}
2662
2663- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2664{
2665    NSPasteboard * pasteboard = [info draggingPasteboard];
2666    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2667    {
2668        //check if any torrent files can be added
2669        BOOL torrent = NO;
2670        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2671        for (NSString * file in files)
2672        {
2673            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2674                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2675            {
2676                torrent = YES;
2677                tr_ctor * ctor = tr_ctorNew(fLib);
2678                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2679                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2680                {
2681                    if (!fOverlayWindow)
2682                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2683                    [fOverlayWindow setTorrents: files];
2684                   
2685                    return NSDragOperationCopy;
2686                }
2687                tr_ctorFree(ctor);
2688            }
2689        }
2690       
2691        //create a torrent file if a single file
2692        if (!torrent && [files count] == 1)
2693        {
2694            if (!fOverlayWindow)
2695                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2696            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2697           
2698            return NSDragOperationCopy;
2699        }
2700    }
2701    else if ([[pasteboard types] containsObject: NSURLPboardType])
2702    {
2703        if (!fOverlayWindow)
2704            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2705        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2706       
2707        return NSDragOperationCopy;
2708    }
2709    else;
2710   
2711    return NSDragOperationNone;
2712}
2713
2714- (void) draggingExited: (id <NSDraggingInfo>) info
2715{
2716    if (fOverlayWindow)
2717        [fOverlayWindow fadeOut];
2718}
2719
2720- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2721{
2722    if (fOverlayWindow)
2723        [fOverlayWindow fadeOut];
2724   
2725    NSPasteboard * pasteboard = [info draggingPasteboard];
2726    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2727    {
2728        BOOL torrent = NO, accept = YES;
2729       
2730        //create an array of files that can be opened
2731        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2732        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
2733        for (NSString * file in files)
2734        {
2735            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2736                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2737            {
2738                torrent = YES;
2739                tr_ctor * ctor = tr_ctorNew(fLib);
2740                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2741                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2742                    [filesToOpen addObject: file];
2743                tr_ctorFree(ctor);
2744            }
2745        }
2746       
2747        if ([filesToOpen count] > 0)
2748            [self application: NSApp openFiles: filesToOpen];
2749        else
2750        {
2751            if (!torrent && [files count] == 1)
2752                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2753            else
2754                accept = NO;
2755        }
2756       
2757        return accept;
2758    }
2759    else if ([[pasteboard types] containsObject: NSURLPboardType])
2760    {
2761        NSURL * url;
2762        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2763        {
2764            [self openURL: [url absoluteString]];
2765            return YES;
2766        }
2767    }
2768    else;
2769   
2770    return NO;
2771}
2772
2773- (void) toggleSmallView: (id) sender
2774{
2775    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2776    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2777   
2778    [fTableView setUsesAlternatingRowBackgroundColors: !makeSmall];
2779   
2780    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2781   
2782    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2783   
2784    //resize for larger min height if not set to auto size
2785    if (![fDefaults boolForKey: @"AutoSize"])
2786    {
2787        const NSSize contentSize = [[fWindow contentView] frame].size;
2788       
2789        NSSize contentMinSize = [fWindow contentMinSize];
2790        contentMinSize.height = [self minWindowContentSizeAllowed];
2791        [fWindow setContentMinSize: contentMinSize];
2792       
2793        //make sure the window already isn't too small
2794        if (!makeSmall && contentSize.height < contentMinSize.height)
2795        {
2796            NSRect frame = [fWindow frame];
2797            CGFloat heightChange = contentMinSize.height - contentSize.height;
2798            frame.size.height += heightChange;
2799            frame.origin.y -= heightChange;
2800           
2801            [fWindow setFrame: frame display: YES];
2802        }
2803    }
2804    else
2805        [self setWindowSizeToFit];
2806}
2807
2808- (void) togglePiecesBar: (id) sender
2809{
2810    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2811    [fTableView togglePiecesBar];
2812}
2813
2814- (void) toggleAvailabilityBar: (id) sender
2815{
2816    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2817    [fTableView display];
2818}
2819
2820- (void) toggleStatusString: (id) sender
2821{
2822    if ([fDefaults boolForKey: @"SmallView"])
2823        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2824    else
2825        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2826   
2827    [fTableView reloadData];
2828}
2829
2830- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2831{
2832    NSScrollView * scrollView = [fTableView enclosingScrollView];
2833   
2834    //convert pixels to points
2835    NSRect windowFrame = [fWindow frame];
2836    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2837    windowSize.height += height;
2838   
2839    if (check)
2840    {
2841        //we can't call minSize, since it might be set to the current size (auto size)
2842        const CGFloat minHeight = [self minWindowContentSizeAllowed]
2843                                    + (NSHeight([fWindow frame]) - NSHeight([[fWindow contentView] frame])); //contentView to window
2844       
2845        if (windowSize.height < minHeight)
2846            windowSize.height =minHeight;
2847        else
2848        {
2849            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2850            if (!fStatusBar)
2851                maxSize.height -= STATUS_BAR_HEIGHT;
2852            if (!fFilterBar)
2853                maxSize.height -= FILTER_BAR_HEIGHT;
2854            if (windowSize.height > maxSize.height)
2855                windowSize.height = maxSize.height;
2856        }
2857    }
2858
2859    //convert points to pixels
2860    windowSize = [scrollView convertSize: windowSize toView: nil];
2861
2862    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2863    windowFrame.size.height = windowSize.height;
2864    return windowFrame;
2865}
2866
2867- (void) toggleStatusBar: (id) sender
2868{
2869    const BOOL show = fStatusBar == nil;
2870    [self showStatusBar: show animate: YES];
2871    [fDefaults setBool: show forKey: @"StatusBar"];
2872}
2873
2874//doesn't save shown state
2875- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2876{
2877    const BOOL prevShown = fStatusBar != nil;
2878    if (show == prevShown)
2879        return;
2880   
2881    if (show)
2882    {
2883        fStatusBar = [[StatusBarController alloc] initWithLib: fLib];
2884       
2885        NSView * contentView = [fWindow contentView];
2886        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
2887       
2888        NSRect statusBarFrame = [[fStatusBar view] frame];
2889        statusBarFrame.size.width = windowSize.width;
2890        [[fStatusBar view] setFrame: statusBarFrame];
2891       
2892        [contentView addSubview: [fStatusBar view]];
2893        [[fStatusBar view] setFrameOrigin: NSMakePoint(0.0, NSMaxY([contentView frame]))];
2894    }
2895   
2896    NSRect frame;
2897    CGFloat heightChange = [[fStatusBar view] frame].size.height;
2898    if (!show)
2899        heightChange *= -1;
2900   
2901    //allow bar to show even if not enough room
2902    if (show && ![fDefaults boolForKey: @"AutoSize"])
2903    {
2904        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2905        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2906        if (change < 0.0)
2907        {
2908            frame = [fWindow frame];
2909            frame.size.height += change;
2910            frame.origin.y -= change;
2911            [fWindow setFrame: frame display: NO animate: NO];
2912        }
2913    }
2914   
2915    [self updateUI];
2916   
2917    NSScrollView * scrollView = [fTableView enclosingScrollView];
2918   
2919    //set views to not autoresize
2920    const NSUInteger statsMask = [[fStatusBar view] autoresizingMask];
2921    [[fStatusBar view] setAutoresizingMask: NSViewNotSizable];
2922    NSUInteger filterMask;
2923    if (fFilterBar)
2924    {
2925        filterMask = [[fFilterBar view] autoresizingMask];
2926        [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
2927    }
2928    const NSUInteger scrollMask = [scrollView autoresizingMask];
2929    [scrollView setAutoresizingMask: NSViewNotSizable];
2930   
2931    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2932    [fWindow setFrame: frame display: YES animate: animate];
2933   
2934    //re-enable autoresize
2935    [[fStatusBar view] setAutoresizingMask: statsMask];
2936    if (fFilterBar)
2937        [[fFilterBar view] setAutoresizingMask: filterMask];
2938    [scrollView setAutoresizingMask: scrollMask];
2939   
2940    if (!show)
2941    {
2942        [[fStatusBar view] removeFromSuperviewWithoutNeedingDisplay];
2943        [fStatusBar release];
2944        fStatusBar = nil;
2945    }
2946   
2947    if ([fDefaults boolForKey: @"AutoSize"])
2948        [self setWindowMinMaxToCurrent];
2949    else
2950    {
2951        //change min size
2952        NSSize minSize = [fWindow contentMinSize];
2953        minSize.height += heightChange;
2954        [fWindow setContentMinSize: minSize];
2955    }
2956}
2957
2958- (void) toggleFilterBar: (id) sender
2959{
2960    const BOOL show = fFilterBar == nil;
2961   
2962    [self showFilterBar: show animate: YES];
2963    [fDefaults setBool: show forKey: @"FilterBar"];
2964    [[fWindow toolbar] validateVisibleItems];
2965   
2966    //disable filtering when hiding
2967    if (!show)
2968    {
2969        [[NSUserDefaults standardUserDefaults] setObject: FILTER_NONE forKey: @"Filter"];
2970        [[NSUserDefaults standardUserDefaults] setInteger: GROUP_FILTER_ALL_TAG forKey: @"FilterGroup"];
2971        [[NSUserDefaults standardUserDefaults] removeObjectForKey: @"FilterSearchString"];
2972    }
2973   
2974    [self applyFilter]; //do even if showing to ensure tooltips are updated
2975}
2976
2977//doesn't save shown state
2978- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2979{
2980    const BOOL prevShown = fFilterBar != nil;
2981    if (show == prevShown)
2982        return;
2983   
2984    if (show)
2985    {
2986        fFilterBar = [[FilterBarController alloc] init];
2987       
2988        NSView * contentView = [fWindow contentView];
2989        const NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
2990       
2991        NSRect filterBarFrame = [[fFilterBar view] frame];
2992        filterBarFrame.size.width = windowSize.width;
2993        [[fFilterBar view] setFrame: filterBarFrame];
2994       
2995        if (fStatusBar)
2996            [contentView addSubview: [fFilterBar view] positioned: NSWindowBelow relativeTo: [fStatusBar view]];
2997        else
2998            [contentView addSubview: [fFilterBar view]];
2999        const CGFloat originY = fStatusBar ? NSMinY([[fStatusBar view] frame]) : NSMaxY([contentView frame]);
3000        [[fFilterBar view] setFrameOrigin: NSMakePoint(0.0, originY)];
3001    }
3002    else
3003        [fWindow makeFirstResponder: fTableView];
3004   
3005    CGFloat heightChange = NSHeight([[fFilterBar view] frame]);
3006    if (!show)
3007        heightChange *= -1;
3008   
3009    //allow bar to show even if not enough room
3010    if (show && ![fDefaults boolForKey: @"AutoSize"])
3011    {
3012        NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3013        const CGFloat change = NSHeight([[fWindow screen] visibleFrame]) - NSHeight(frame);
3014        if (change < 0.0)
3015        {
3016            frame = [fWindow frame];
3017            frame.size.height += change;
3018            frame.origin.y -= change;
3019            [fWindow setFrame: frame display: NO animate: NO];
3020        }
3021    }
3022   
3023    NSScrollView * scrollView = [fTableView enclosingScrollView];
3024
3025    //set views to not autoresize
3026    const NSUInteger filterMask = [[fFilterBar view] autoresizingMask];
3027    const NSUInteger scrollMask = [scrollView autoresizingMask];
3028    [[fFilterBar view] setAutoresizingMask: NSViewNotSizable];
3029    [scrollView setAutoresizingMask: NSViewNotSizable];
3030   
3031    const NSRect frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3032    [fWindow setFrame: frame display: YES animate: animate];
3033   
3034    //re-enable autoresize
3035    [[fFilterBar view] setAutoresizingMask: filterMask];
3036    [scrollView setAutoresizingMask: scrollMask];
3037   
3038    if (!show)
3039    {
3040        [[fFilterBar view] removeFromSuperviewWithoutNeedingDisplay];
3041        [fFilterBar release];
3042        fFilterBar = nil;
3043    }
3044   
3045    if ([fDefaults boolForKey: @"AutoSize"])
3046        [self setWindowMinMaxToCurrent];
3047    else
3048    {
3049        //change min size
3050        NSSize minSize = [fWindow contentMinSize];
3051        minSize.height += heightChange;
3052        [fWindow setContentMinSize: minSize];
3053    }
3054}
3055
3056- (void) focusFilterField
3057{
3058    if (!fFilterBar)
3059        [self toggleFilterBar: self];
3060    [fFilterBar focusSearchField];
3061}
3062
3063#warning change from id to QLPreviewPanel
3064- (BOOL) acceptsPreviewPanelControl: (id) panel
3065{
3066    return !fQuitting;
3067}
3068
3069- (void) beginPreviewPanelControl: (id) panel
3070{
3071    fPreviewPanel = [panel retain];
3072    [fPreviewPanel setDelegate: self];
3073    [fPreviewPanel setDataSource: self];
3074}
3075
3076- (void) endPreviewPanelControl: (id) panel
3077{
3078    [fPreviewPanel release];
3079    fPreviewPanel = nil;
3080}
3081
3082- (NSArray *) quickLookableTorrents
3083{
3084    NSArray * selectedTorrents = [fTableView selectedTorrents];
3085    NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3086   
3087    for (Torrent * torrent in selectedTorrents)
3088        if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation])
3089            [qlArray addObject: torrent];
3090   
3091    return qlArray;
3092}
3093
3094- (NSInteger) numberOfPreviewItemsInPreviewPanel: (id) panel
3095{
3096    if ([fInfoController canQuickLook])
3097        return [[fInfoController quickLookURLs] count];
3098    else
3099        return [[self quickLookableTorrents] count];
3100}
3101
3102- (id /*<QLPreviewItem>*/) previewPanel: (id) panel previewItemAtIndex: (NSInteger) index
3103{
3104    if ([fInfoController canQuickLook])
3105        return [[fInfoController quickLookURLs] objectAtIndex: index];
3106    else
3107        return [[self quickLookableTorrents] objectAtIndex: index];
3108}
3109
3110- (BOOL) previewPanel: (id) panel handleEvent: (NSEvent *) event
3111{
3112    /*if ([event type] == NSKeyDown)
3113    {
3114        [super keyDown: event];
3115        return YES;
3116    }*/
3117   
3118    return NO;
3119}
3120
3121- (NSRect) previewPanel: (id) panel sourceFrameOnScreenForPreviewItem: (id /*<QLPreviewItem>*/) item
3122{
3123    if ([fInfoController canQuickLook])
3124        return [fInfoController quickLookSourceFrameForPreviewItem: item];
3125    else
3126    {
3127        if (![fWindow isVisible])
3128            return NSZeroRect;
3129       
3130        const NSInteger row = [fTableView rowForItem: item];
3131        if (row == -1)
3132            return NSZeroRect;
3133       
3134        NSRect frame = [fTableView iconRectForRow: row];
3135       
3136        if (!NSIntersectsRect([fTableView visibleRect], frame))
3137            return NSZeroRect;
3138       
3139        frame.origin = [fTableView convertPoint: frame.origin toView: nil];
3140        frame.origin = [fWindow convertBaseToScreen: frame.origin];
3141        frame.origin.y -= frame.size.height;
3142        return frame;
3143    }
3144}
3145
3146- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3147{
3148    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3149   
3150    NSButton * button = [[NSButton alloc] init];
3151    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3152    [button setStringValue: @""];
3153   
3154    [item setView: button];
3155    [button release];
3156   
3157    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3158    [item setMinSize: buttonSize];
3159    [item setMaxSize: buttonSize];
3160   
3161    return [item autorelease];
3162}
3163
3164- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3165{
3166    if ([ident isEqualToString: TOOLBAR_CREATE])
3167    {
3168        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3169       
3170        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3171        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3172        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3173        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3174        [item setTarget: self];
3175        [item setAction: @selector(createFile:)];
3176        [item setAutovalidates: NO];
3177       
3178        return item;
3179    }
3180    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3181    {
3182        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3183       
3184        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3185        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3186        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3187        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3188        [item setTarget: self];
3189        [item setAction: @selector(openShowSheet:)];
3190        [item setAutovalidates: NO];
3191       
3192        return item;
3193    }
3194    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3195    {
3196        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3197       
3198        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3199        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3200        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3201        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3202        [item setTarget: self];
3203        [item setAction: @selector(openURLShowSheet:)];
3204        [item setAutovalidates: NO];
3205       
3206        return item;
3207    }
3208    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3209    {
3210        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3211       
3212        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3213        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3214        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3215        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3216        [item setTarget: self];
3217        [item setAction: @selector(removeNoDelete:)];
3218        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3219       
3220        return item;
3221    }
3222    else if ([ident isEqualToString: TOOLBAR_INFO])
3223    {
3224        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3225        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3226       
3227        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3228        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3229        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3230        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3231        [item setTarget: self];
3232        [item setAction: @selector(showInfo:)];
3233       
3234        return item;
3235    }
3236    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3237    {
3238        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3239       
3240        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3241        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3242        [groupItem setView: segmentedControl];
3243        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3244       
3245        [segmentedControl setSegmentCount: 2];
3246        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3247       
3248        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3249        [groupItem setMinSize: groupSize];
3250        [groupItem setMaxSize: groupSize];
3251       
3252        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3253        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3254        [groupItem setTarget: self];
3255        [groupItem setAction: @selector(allToolbarClicked:)];
3256       
3257        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3258       
3259        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3260        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3261        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3262                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3263       
3264        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3265        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3266        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3267                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3268       
3269        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3270                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3271       
3272        [segmentedControl release];
3273       
3274        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3275       
3276        return [groupItem autorelease];
3277    }
3278    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3279    {
3280        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3281       
3282        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3283        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3284        [groupItem setView: segmentedControl];
3285        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3286       
3287        [segmentedControl setSegmentCount: 2];
3288        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3289       
3290        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3291        [groupItem setMinSize: groupSize];
3292        [groupItem setMaxSize: groupSize];
3293       
3294        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3295        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3296        [groupItem setTarget: self];
3297        [groupItem setAction: @selector(selectedToolbarClicked:)];
3298       
3299        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3300       
3301        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3302        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3303        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3304                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3305       
3306        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3307        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3308        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3309                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3310       
3311        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3312                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3313       
3314        [segmentedControl release];
3315       
3316        [groupItem setVisibilityPriority: NSToolbarItemVisibilityPriorityHigh];
3317       
3318        return [groupItem autorelease];
3319    }
3320    else if ([ident isEqualToString: TOOLBAR_FILTER])
3321    {
3322        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3323        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3324       
3325        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3326        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3327        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3328        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3329        [item setTarget: self];
3330        [item setAction: @selector(toggleFilterBar:)];
3331       
3332        return item;
3333    }
3334    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3335    {
3336        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3337        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3338       
3339        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3340        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3341        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3342        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3343        [item setTarget: self];
3344        [item setAction: @selector(toggleQuickLook:)];
3345        [item setVisibilityPriority: NSToolbarItemVisibilityPriorityLow];
3346       
3347        return item;
3348    }
3349    else
3350        return nil;
3351}
3352
3353- (void) allToolbarClicked: (id) sender
3354{
3355    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3356                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3357    switch (tagValue)
3358    {
3359        case TOOLBAR_PAUSE_TAG:
3360            [self stopAllTorrents: sender];
3361            break;
3362        case TOOLBAR_RESUME_TAG:
3363            [self resumeAllTorrents: sender];
3364            break;
3365    }
3366}
3367
3368- (void) selectedToolbarClicked: (id) sender
3369{
3370    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3371                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3372    switch (tagValue)
3373    {
3374        case TOOLBAR_PAUSE_TAG:
3375            [self stopSelectedTorrents: sender];
3376            break;
3377        case TOOLBAR_RESUME_TAG:
3378            [self resumeSelectedTorrents: sender];
3379            break;
3380    }
3381}
3382
3383- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3384{
3385    return [NSArray arrayWithObjects:
3386            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3387            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3388            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3389            NSToolbarSeparatorItemIdentifier,
3390            NSToolbarSpaceItemIdentifier,
3391            NSToolbarFlexibleSpaceItemIdentifier,
3392            NSToolbarCustomizeToolbarItemIdentifier, nil];
3393}
3394
3395- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3396{
3397    return [NSArray arrayWithObjects:
3398            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSpaceItemIdentifier,
3399            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3400            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3401}
3402
3403- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3404{
3405    NSString * ident = [toolbarItem itemIdentifier];
3406   
3407    //enable remove item
3408    if ([ident isEqualToString: TOOLBAR_REMOVE])
3409        return [fTableView numberOfSelectedRows] > 0;
3410
3411    //enable pause all item
3412    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3413    {
3414        for (Torrent * torrent in fTorrents)
3415            if ([torrent isActive] || [torrent waitingToStart])
3416                return YES;
3417        return NO;
3418    }
3419
3420    //enable resume all item
3421    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3422    {
3423        for (Torrent * torrent in fTorrents)
3424            if (![torrent isActive] && ![torrent waitingToStart])
3425                return YES;
3426        return NO;
3427    }
3428
3429    //enable pause item
3430    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3431    {
3432        for (Torrent * torrent in [fTableView selectedTorrents])
3433            if ([torrent isActive] || [torrent waitingToStart])
3434                return YES;
3435        return NO;
3436    }
3437   
3438    //enable resume item
3439    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3440    {
3441        for (Torrent * torrent in [fTableView selectedTorrents])
3442            if (![torrent isActive] && ![torrent waitingToStart])
3443                return YES;
3444        return NO;
3445    }
3446   
3447    //set info item
3448    if ([ident isEqualToString: TOOLBAR_INFO])
3449    {
3450        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3451        return YES;
3452    }
3453   
3454    //set filter item
3455    if ([ident isEqualToString: TOOLBAR_FILTER])
3456    {
3457        [(NSButton *)[toolbarItem view] setState: fFilterBar != nil];
3458        return YES;
3459    }
3460   
3461    //set quick look item
3462    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3463    {
3464        [(NSButton *)[toolbarItem view] setState: [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
3465                                                    && [[QLPreviewPanelSL sharedPreviewPanel] isVisible]];
3466        return [NSApp isOnSnowLeopardOrBetter];
3467    }
3468
3469    return YES;
3470}
3471
3472- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3473{
3474    SEL action = [menuItem action];
3475   
3476    if (action == @selector(toggleSpeedLimit:))
3477    {
3478        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3479        return YES;
3480    }
3481   
3482    //only enable some items if it is in a context menu or the window is useable
3483    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3484
3485    //enable open items
3486    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3487        return [fWindow attachedSheet] == nil;
3488   
3489    //enable sort options
3490    if (action == @selector(setSort:))
3491    {
3492        NSString * sortType;
3493        switch ([menuItem tag])
3494        {
3495            case SORT_ORDER_TAG:
3496                sortType = SORT_ORDER;
3497                break;
3498            case SORT_DATE_TAG:
3499                sortType = SORT_DATE;
3500                break;
3501            case SORT_NAME_TAG:
3502                sortType = SORT_NAME;
3503                break;
3504            case SORT_PROGRESS_TAG:
3505                sortType = SORT_PROGRESS;
3506                break;
3507            case SORT_STATE_TAG:
3508                sortType = SORT_STATE;
3509                break;
3510            case SORT_TRACKER_TAG:
3511                sortType = SORT_TRACKER;
3512                break;
3513            case SORT_ACTIVITY_TAG:
3514                sortType = SORT_ACTIVITY;
3515                break;
3516            case SORT_SIZE_TAG:
3517                sortType = SORT_SIZE;
3518                break;
3519            default:
3520                NSAssert1(NO, @"Unknown sort tag received: %d", [menuItem tag]);
3521        }
3522       
3523        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3524        return [fWindow isVisible];
3525    }
3526   
3527    if (action == @selector(setGroup:))
3528    {
3529        BOOL checked = NO;
3530       
3531        NSInteger index = [menuItem tag];
3532        for (Torrent * torrent in [fTableView selectedTorrents])
3533            if (index == [torrent groupValue])
3534            {
3535                checked = YES;
3536                break;
3537            }
3538       
3539        [menuItem setState: checked ? NSOnState : NSOffState];
3540        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3541    }
3542   
3543    if (action == @selector(toggleSmallView:))
3544    {
3545        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3546        return [fWindow isVisible];
3547    }
3548   
3549    if (action == @selector(togglePiecesBar:))
3550    {
3551        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3552        return [fWindow isVisible];
3553    }
3554   
3555    if (action == @selector(toggleStatusString:))
3556    {
3557        if ([fDefaults boolForKey: @"SmallView"])
3558        {
3559            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3560            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3561        }
3562        else
3563        {
3564            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3565            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3566        }
3567       
3568        return [fWindow isVisible];
3569    }
3570   
3571    if (action == @selector(toggleAvailabilityBar:))
3572    {
3573        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3574        return [fWindow isVisible];
3575    }
3576   
3577    if (action == @selector(setLimitGlobalEnabled:))
3578    {
3579        BOOL upload = [menuItem menu] == fUploadMenu;
3580        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3581        if (limit)
3582            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3583                                    "Action menu -> upload/download limit"),
3584                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3585       
3586        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3587        return YES;
3588    }
3589   
3590    if (action == @selector(setRatioGlobalEnabled:))
3591    {
3592        BOOL check = menuItem == fCheckRatioItem;
3593        if (check)
3594            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3595                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3596       
3597        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3598        return YES;
3599    }
3600
3601    //enable show info
3602    if (action == @selector(showInfo:))
3603    {
3604        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3605                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3606        [menuItem setTitle: title];
3607
3608        return YES;
3609    }
3610   
3611    //enable prev/next inspector tab
3612    if (action == @selector(setInfoTab:))
3613        return [[fInfoController window] isVisible];
3614   
3615    //enable toggle status bar
3616    if (action == @selector(toggleStatusBar:))
3617    {
3618        NSString * title = !fStatusBar ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3619                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3620        [menuItem setTitle: title];
3621
3622        return [fWindow isVisible];
3623    }
3624   
3625    //enable toggle filter bar
3626    if (action == @selector(toggleFilterBar:))
3627    {
3628        NSString * title = !fFilterBar ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3629                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3630        [menuItem setTitle: title];
3631
3632        return [fWindow isVisible];
3633    }
3634   
3635    //enable prev/next filter button
3636    if (action == @selector(switchFilter:))
3637        return [fWindow isVisible] && fFilterBar;
3638   
3639    //enable reveal in finder
3640    if (action == @selector(revealFile:))
3641        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3642
3643    //enable remove items
3644    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
3645    {
3646        BOOL warning = NO;
3647       
3648        for (Torrent * torrent in [fTableView selectedTorrents])
3649        {
3650            if ([torrent isActive])
3651            {
3652                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
3653                {
3654                    warning = YES;
3655                    break;
3656                }
3657            }
3658        }
3659   
3660        //append or remove ellipsis when needed
3661        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3662        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3663        {
3664            if (![title hasSuffix: ellipsis])
3665                [menuItem setTitle: [title stringByAppendingEllipsis]];
3666        }
3667        else
3668        {
3669            if ([title hasSuffix: ellipsis])
3670                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3671        }
3672       
3673        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3674    }
3675   
3676    //remove all completed transfers item
3677    if (action == @selector(clearCompleted:))
3678    {
3679        //append or remove ellipsis when needed
3680        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3681        if ([fDefaults boolForKey: @"WarningRemoveCompleted"])
3682        {
3683            if (![title hasSuffix: ellipsis])
3684                [menuItem setTitle: [title stringByAppendingEllipsis]];
3685        }
3686        else
3687        {
3688            if ([title hasSuffix: ellipsis])
3689                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3690        }
3691       
3692        for (Torrent * torrent in fTorrents)
3693            if ([torrent isFinishedSeeding])
3694                return YES;
3695        return NO;
3696    }
3697
3698    //enable pause all item
3699    if (action == @selector(stopAllTorrents:))
3700    {
3701        for (Torrent * torrent in fTorrents)
3702            if ([torrent isActive] || [torrent waitingToStart])
3703                return YES;
3704        return NO;
3705    }
3706   
3707    //enable resume all item
3708    if (action == @selector(resumeAllTorrents:))
3709    {
3710        for (Torrent * torrent in fTorrents)
3711            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
3712                return YES;
3713        return NO;
3714    }
3715   
3716    //enable resume all waiting item
3717    if (action == @selector(resumeWaitingTorrents:))
3718    {
3719        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3720            return NO;
3721   
3722        for (Torrent * torrent in fTorrents)
3723            if (![torrent isActive] && [torrent waitingToStart])
3724                return YES;
3725        return NO;
3726    }
3727   
3728    //enable resume selected waiting item
3729    if (action == @selector(resumeSelectedTorrentsNoWait:))
3730    {
3731        if (!canUseTable)
3732            return NO;
3733       
3734        for (Torrent * torrent in [fTableView selectedTorrents])
3735            if (![torrent isActive])
3736                return YES;
3737        return NO;
3738    }
3739
3740    //enable pause item
3741    if (action == @selector(stopSelectedTorrents:))
3742    {
3743        if (!canUseTable)
3744            return NO;
3745   
3746        for (Torrent * torrent in [fTableView selectedTorrents])
3747            if ([torrent isActive] || [torrent waitingToStart])
3748                return YES;
3749        return NO;
3750    }
3751   
3752    //enable resume item
3753    if (action == @selector(resumeSelectedTorrents:))
3754    {
3755        if (!canUseTable)
3756            return NO;
3757   
3758        for (Torrent * torrent in [fTableView selectedTorrents])
3759            if (![torrent isActive] && ![torrent waitingToStart])
3760                return YES;
3761        return NO;
3762    }
3763   
3764    //enable manual announce item
3765    if (action == @selector(announceSelectedTorrents:))
3766    {
3767        if (!canUseTable)
3768            return NO;
3769       
3770        for (Torrent * torrent in [fTableView selectedTorrents])
3771            if ([torrent canManualAnnounce])
3772                return YES;
3773        return NO;
3774    }
3775   
3776    //enable reset cache item
3777    if (action == @selector(verifySelectedTorrents:))
3778    {
3779        if (!canUseTable)
3780            return NO;
3781           
3782        for (Torrent * torrent in [fTableView selectedTorrents])
3783            if (![torrent isMagnet])
3784                return YES;
3785        return NO;
3786    }
3787   
3788    //enable move torrent file item
3789    if (action == @selector(moveDataFilesSelected:))
3790        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3791   
3792    //enable copy torrent file item
3793    if (action == @selector(copyTorrentFiles:))
3794    {
3795        if (!canUseTable)
3796            return NO;
3797       
3798        for (Torrent * torrent in [fTableView selectedTorrents])
3799            if (![torrent isMagnet])
3800                return YES;
3801        return NO;
3802    }
3803   
3804    //enable copy torrent file item
3805    if (action == @selector(copyMagnetLinks:))
3806        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3807   
3808    //enable reverse sort item
3809    if (action == @selector(setSortReverse:))
3810    {
3811        const BOOL isReverse = [menuItem tag] == SORT_DESC_TAG;
3812        [menuItem setState: (isReverse == [fDefaults boolForKey: @"SortReverse"]) ? NSOnState : NSOffState];
3813        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3814    }
3815   
3816    //enable group sort item
3817    if (action == @selector(setSortByGroup:))
3818    {
3819        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3820        return YES;
3821    }
3822   
3823    if (action == @selector(toggleQuickLook:))
3824    {
3825        const BOOL visible = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
3826                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
3827        //text consistent with Finder
3828        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
3829                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
3830        [menuItem setTitle: title];
3831       
3832        return [NSApp isOnSnowLeopardOrBetter];
3833    }
3834   
3835    return YES;
3836}
3837
3838- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3839{
3840    switch (messageType)
3841    {
3842        case kIOMessageSystemWillSleep:
3843            //if there are any running transfers, wait 15 seconds for them to stop
3844            for (Torrent * torrent in fTorrents)
3845                if ([torrent isActive])
3846                {
3847                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3848                    for (Torrent * torrent in fTorrents)
3849                        [torrent sleep];
3850                    sleep(15);
3851                    break;
3852                }
3853
3854            IOAllowPowerChange(fRootPort, (long) messageArgument);
3855            break;
3856
3857        case kIOMessageCanSystemSleep:
3858            if ([fDefaults boolForKey: @"SleepPrevent"])
3859            {
3860                //prevent idle sleep unless no torrents are active
3861                for (Torrent * torrent in fTorrents)
3862                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3863                    {
3864                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3865                        return;
3866                    }
3867            }
3868           
3869            IOAllowPowerChange(fRootPort, (long) messageArgument);
3870            break;
3871
3872        case kIOMessageSystemHasPoweredOn:
3873            //resume sleeping transfers after we wake up
3874            for (Torrent * torrent in fTorrents)
3875                [torrent wakeUp];
3876            break;
3877    }
3878}
3879
3880- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3881{
3882    NSInteger seeding = 0, downloading = 0;
3883    for (Torrent * torrent in fTorrents)
3884    {
3885        if ([torrent isSeeding])
3886            seeding++;
3887        else if ([torrent isActive])
3888            downloading++;
3889        else;
3890    }
3891   
3892    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3893            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3894   
3895    BOOL hasSeparator = seedingItem || downloadingItem;
3896   
3897    if (seeding > 0)
3898    {
3899        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3900        if (!seedingItem)
3901        {
3902            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3903            [seedingItem setTag: DOCK_SEEDING_TAG];
3904            [fDockMenu insertItem: seedingItem atIndex: 0];
3905        }
3906        else
3907            [seedingItem setTitle: title];
3908    }
3909    else
3910    {
3911        if (seedingItem)
3912            [fDockMenu removeItem: seedingItem];
3913    }
3914   
3915    if (downloading > 0)
3916    {
3917        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3918        if (!downloadingItem)
3919        {
3920            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3921            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3922            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3923        }
3924        else
3925            [downloadingItem setTitle: title];
3926    }
3927    else
3928    {
3929        if (downloadingItem)
3930            [fDockMenu removeItem: downloadingItem];
3931    }
3932   
3933    if (seeding > 0 || downloading > 0)
3934    {
3935        if (!hasSeparator)
3936            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: (seeding > 0 && downloading > 0) ? 2 : 1];
3937    }
3938    else
3939    {
3940        if (hasSeparator)
3941            [fDockMenu removeItemAtIndex: 0];
3942    }
3943   
3944    return fDockMenu;
3945}
3946
3947- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3948{
3949    //if auto size is enabled, the current frame shouldn't need to change
3950    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3951   
3952    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3953    return frame;
3954}
3955
3956- (void) setWindowSizeToFit
3957{
3958    if ([fDefaults boolForKey: @"AutoSize"])
3959    {
3960        NSScrollView * scrollView = [fTableView enclosingScrollView];
3961       
3962        [scrollView setHasVerticalScroller: NO];
3963        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3964        [scrollView setHasVerticalScroller: YES];
3965       
3966        //hack to ensure scrollbars don't disappear after resizing
3967        if (![NSApp isOnSnowLeopardOrBetter])
3968        {
3969            [scrollView setAutohidesScrollers: NO];
3970            [scrollView setAutohidesScrollers: YES];
3971        }
3972       
3973        [self setWindowMinMaxToCurrent];
3974    }
3975}
3976
3977- (NSRect) sizedWindowFrame
3978{
3979    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3980                    ? [fDisplayedTorrents count] : 0;
3981   
3982    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3983                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3984                        - NSHeight([[fTableView enclosingScrollView] frame]);
3985   
3986    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3987}
3988
3989- (void) updateForAutoSize
3990{
3991    if ([fDefaults boolForKey: @"AutoSize"])
3992        [self setWindowSizeToFit];
3993    else
3994    {
3995        NSSize contentMinSize = [fWindow contentMinSize];
3996        contentMinSize.height = [self minWindowContentSizeAllowed];
3997       
3998        [fWindow setContentMinSize: contentMinSize];
3999       
4000        NSSize contentMaxSize = [fWindow contentMaxSize];
4001        contentMaxSize.height = FLT_MAX;
4002        [fWindow setContentMaxSize: contentMaxSize];
4003    }
4004}
4005
4006- (void) setWindowMinMaxToCurrent
4007{
4008    const CGFloat height = NSHeight([[fWindow contentView] frame]);
4009   
4010    NSSize minSize = [fWindow contentMinSize],
4011            maxSize = [fWindow contentMaxSize];
4012    minSize.height = height;
4013    maxSize.height = height;
4014   
4015    [fWindow setContentMinSize: minSize];
4016    [fWindow setContentMaxSize: maxSize];
4017}
4018
4019- (CGFloat) minWindowContentSizeAllowed
4020{
4021    CGFloat contentMinHeight = NSHeight([[fWindow contentView] frame]) - NSHeight([[fTableView enclosingScrollView] frame])
4022                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
4023    return contentMinHeight;
4024}
4025
4026- (void) updateForExpandCollape
4027{
4028    [self setWindowSizeToFit];
4029    [self setBottomCountText: YES];
4030}
4031
4032- (void) showMainWindow: (id) sender
4033{
4034    [fWindow makeKeyAndOrderFront: nil];
4035}
4036
4037- (void) windowDidBecomeMain: (NSNotification *) notification
4038{
4039    [fBadger clearCompleted];
4040    [self updateUI];
4041}
4042
4043- (void) applicationWillUnhide: (NSNotification *) notification
4044{
4045    [self updateUI];
4046}
4047
4048- (void) toggleQuickLook: (id) sender
4049{
4050    if (![NSApp isOnSnowLeopardOrBetter])
4051        return;
4052   
4053    if ([[QLPreviewPanelSL sharedPreviewPanel] isVisible])
4054        [[QLPreviewPanelSL sharedPreviewPanel] orderOut: nil];
4055    else
4056        [[QLPreviewPanelSL sharedPreviewPanel] makeKeyAndOrderFront: nil];
4057}
4058
4059- (void) linkHomepage: (id) sender
4060{
4061    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4062}
4063
4064- (void) linkForums: (id) sender
4065{
4066    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4067}
4068
4069- (void) linkTrac: (id) sender
4070{
4071    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4072}
4073
4074- (void) linkDonate: (id) sender
4075{
4076    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4077}
4078
4079- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4080{
4081    fQuitRequested = YES;
4082}
4083
4084- (NSDictionary *) registrationDictionaryForGrowl
4085{
4086    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4087                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4088    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4089                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4090}
4091
4092- (void) growlNotificationWasClicked: (id) clickContext
4093{
4094    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4095        return;
4096   
4097    NSString * type = [clickContext objectForKey: @"Type"], * location;
4098    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4099            && (location = [clickContext objectForKey: @"Location"]))
4100    {
4101        if ([NSApp isOnSnowLeopardOrBetter])
4102        {
4103            NSURL * file = [NSURL fileURLWithPath: location];
4104            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4105        }
4106        else
4107            [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4108    }
4109}
4110
4111#warning handle queue state changes
4112- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4113{
4114    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4115   
4116    //get the torrent
4117    Torrent * torrent = nil;
4118    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED && type != TR_RPC_SESSION_CLOSE))
4119    {
4120        for (torrent in fTorrents)
4121            if (torrentStruct == [torrent torrentStruct])
4122            {
4123                [torrent retain];
4124                break;
4125            }
4126       
4127        if (!torrent)
4128        {
4129            [pool drain];
4130           
4131            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4132            return;
4133        }
4134    }
4135   
4136    switch (type)
4137    {
4138        case TR_RPC_TORRENT_ADDED:
4139            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4140                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4141            break;
4142       
4143        case TR_RPC_TORRENT_STARTED:
4144        case TR_RPC_TORRENT_STOPPED:
4145            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4146            break;
4147       
4148        case TR_RPC_TORRENT_REMOVING:
4149            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4150            break;
4151       
4152        case TR_RPC_TORRENT_TRASHING:
4153            [self performSelectorOnMainThread: @selector(rpcRemoveTorrentDeleteData:) withObject: torrent waitUntilDone: NO];
4154            break;
4155       
4156        case TR_RPC_TORRENT_CHANGED:
4157            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4158            break;
4159       
4160        case TR_RPC_TORRENT_MOVED:
4161            [self performSelectorOnMainThread: @selector(rpcMovedTorrent:) withObject: torrent waitUntilDone: NO];
4162            break;
4163       
4164        case TR_RPC_SESSION_CHANGED:
4165            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4166            break;
4167       
4168        case TR_RPC_SESSION_CLOSE:
4169            fQuitRequested = YES;
4170            [NSApp performSelectorOnMainThread: @selector(terminate:) withObject: self waitUntilDone: NO];
4171            break;
4172       
4173        default:
4174            NSAssert1(NO, @"Unknown RPC command received: %d", type);
4175            [torrent release];
4176    }
4177   
4178    [pool drain];
4179}
4180
4181- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4182{
4183    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4184    [torrentStructPtr release];
4185   
4186    NSString * location = nil;
4187    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4188        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4189   
4190    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4191   
4192    [torrent update];
4193    [fTorrents addObject: torrent];
4194    [torrent release];
4195   
4196    [self fullUpdateUI];
4197}
4198
4199- (void) rpcRemoveTorrent: (Torrent *) torrent
4200{
4201    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4202    [torrent release];
4203}
4204
4205- (void) rpcRemoveTorrentDeleteData: (Torrent *) torrent
4206{
4207    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: YES];
4208    [torrent release];
4209}
4210
4211- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4212{
4213    [torrent update];
4214    [torrent release];
4215   
4216    [self updateUI];
4217    [self applyFilter];
4218    [self updateTorrentHistory];
4219}
4220
4221- (void) rpcChangedTorrent: (Torrent *) torrent
4222{
4223    [torrent update];
4224   
4225    if ([[fTableView selectedTorrents] containsObject: torrent])
4226    {
4227        [fInfoController updateInfoStats]; //this will reload the file table
4228        [fInfoController updateOptions];
4229    }
4230   
4231    [torrent release];
4232}
4233
4234- (void) rpcMovedTorrent: (Torrent *) torrent
4235{
4236    [torrent update];
4237    [torrent updateTimeMachineExclude];
4238   
4239    if ([[fTableView selectedTorrents] containsObject: torrent])
4240        [fInfoController updateInfoStats];
4241   
4242    [torrent release];
4243}
4244
4245@end
Note: See TracBrowser for help on using the repository browser.