source: trunk/macosx/Controller.m @ 13435

Last change on this file since 13435 was 13435, checked in by livings124, 9 years ago

silence warnings about string literals

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