source: trunk/macosx/Controller.m @ 11991

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

remove unused variables

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