source: trunk/macosx/Controller.m @ 9431

Last change on this file since 9431 was 9431, checked in by livings124, 13 years ago

remove the mac's redundant location check when adding a transfer

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