source: trunk/macosx/Controller.m @ 12533

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

#4225 Sort torrents by size

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