source: trunk/macosx/Controller.m @ 13127

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

#4694 Don't call reloadData on the main table on each updateUI call (and each sort) if the order hasn't changed; instead call setNeedsDisplay:. Don't call reloadData when toggling the main window per-torrent status string

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