source: trunk/macosx/Controller.m @ 12644

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

The Mac UI's "check for stalled transfers" feature now uses the libtransmission hooks

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