source: trunk/macosx/Controller.m @ 13602

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

#2794 Don't apply auto-grouping until torrent is demagnetized

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