source: trunk/macosx/Controller.m @ 12768

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

#4448 "Resume all" toolbar button should factor in seeding-complete transfers

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