source: trunk/macosx/Controller.m @ 12522

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

minor NEWS tweaks

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