source: trunk/macosx/Controller.m @ 12629

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

don't attempt to generate the dock menu when quitting

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