source: trunk/macosx/Controller.m @ 9561

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

start laying a little magnet link groundwork, and remove redundant torrent parse when creating torrent objects

  • Property svn:keywords set to Date Rev Author Id
File size: 157.8 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 9561 2009-11-25 04:11:52Z 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    for (NSString * torrentPath in filenames)
850    {
851        //ensure torrent doesn't already exist
852        tr_ctor * ctor = tr_ctorNew(fLib);
853        tr_ctorSetMetainfoFromFile(ctor, [torrentPath UTF8String]);
854       
855        tr_info info;
856        const tr_parse_result result = tr_torrentParse(ctor, &info);
857        tr_ctorFree(ctor);
858       
859        if (result != TR_PARSE_OK)
860        {
861            if (result == TR_PARSE_DUPLICATE)
862                [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
863            else if (result == TR_PARSE_ERR)
864            {
865                if (type != ADD_AUTO)
866                    [self invalidOpenAlert: [torrentPath lastPathComponent]];
867            }
868            else
869                NSAssert2(NO, @"Unknown error code (%d) when attempting to open \"%@\"", result, torrentPath);
870           
871            tr_metainfoFree(&info);
872            continue;
873        }
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        const 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) openMagnet: (NSString *) address
937{
938    Torrent * torrent;
939    if (!(torrent = [[Torrent alloc] initWithMagnetAddress: address location: nil lib: fLib]))
940    {
941        #warning should we do something here?
942        return;
943    }
944   
945    #warning should we do this?
946    [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
947   
948    [torrent update];
949    [fTorrents addObject: torrent];
950    [torrent release];
951
952    [self updateTorrentsInQueue];
953}
954
955- (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add
956{
957    Torrent * torrent = [addController torrent];
958    [addController release];
959   
960    if (add)
961    {
962        [torrent update];
963        [fTorrents addObject: torrent];
964        [torrent release];
965       
966        [self updateTorrentsInQueue];
967    }
968    else
969    {
970        [torrent closeRemoveTorrent];
971        [torrent release];
972    }
973}
974
975- (void) openCreatedFile: (NSNotification *) notification
976{
977    NSDictionary * dict = [notification userInfo];
978    [self openFiles: [NSArray arrayWithObject: [dict objectForKey: @"File"]] addType: ADD_CREATED
979                        forcePath: [dict objectForKey: @"Path"]];
980    [dict release];
981}
982
983- (void) incompleteChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
984{
985    if (code == NSOKButton)
986        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
987    else
988        [fDefaults setBool: NO forKey: @"UseIncompleteDownloadFolder"];
989   
990    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
991}
992
993- (void) downloadChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
994{
995    if (code == NSOKButton)
996    {
997        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"DownloadFolder"];
998        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
999    }
1000    else
1001        [dictionary release];
1002}
1003
1004- (void) openFilesWithDict: (NSDictionary *) dictionary
1005{
1006    [self openFiles: [dictionary objectForKey: @"Filenames"] addType: [[dictionary objectForKey: @"AddType"] intValue] forcePath: nil];
1007   
1008    [dictionary release];
1009}
1010
1011//called on by applescript
1012- (void) open: (NSArray *) files
1013{
1014    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: files, @"Filenames",
1015                                [NSNumber numberWithInt: ADD_MANUAL], @"AddType", nil];
1016    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dict waitUntilDone: NO];
1017}
1018
1019- (void) openShowSheet: (id) sender
1020{
1021    NSOpenPanel * panel = [NSOpenPanel openPanel];
1022
1023    [panel setAllowsMultipleSelection: YES];
1024    [panel setCanChooseFiles: YES];
1025    [panel setCanChooseDirectories: NO];
1026
1027    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]
1028        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
1029        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
1030}
1031
1032- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSNumber *) useOptions
1033{
1034    if (code == NSOKButton)
1035    {
1036        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: [panel filenames], @"Filenames",
1037            [NSNumber numberWithInt: [useOptions boolValue] ? ADD_SHOW_OPTIONS : ADD_MANUAL], @"AddType", nil];
1038        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
1039    }
1040}
1041
1042- (void) invalidOpenAlert: (NSString *) filename
1043{
1044    if (![fDefaults boolForKey: @"WarningInvalidOpen"])
1045        return;
1046   
1047    NSAlert * alert = [[NSAlert alloc] init];
1048    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"\"%@\" is not a valid torrent file.",
1049                            "Open invalid alert -> title"), filename]];
1050    [alert setInformativeText:
1051            NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.",
1052                            "Open invalid alert -> message")];
1053    [alert setAlertStyle: NSWarningAlertStyle];
1054    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open invalid alert -> button")];
1055   
1056    [alert runModal];
1057    if ([[alert suppressionButton] state] == NSOnState)
1058        [fDefaults setBool: NO forKey: @"WarningInvalidOpen"];
1059    [alert release];
1060}
1061
1062- (void) duplicateOpenAlert: (NSString *) name
1063{
1064    if (![fDefaults boolForKey: @"WarningDuplicate"])
1065        return;
1066   
1067    NSAlert * alert = [[NSAlert alloc] init];
1068    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.",
1069                            "Open duplicate alert -> title"), name]];
1070    [alert setInformativeText:
1071            NSLocalizedString(@"The torrent file cannot be opened because it is a duplicate of an already added transfer.",
1072                            "Open duplicate alert -> message")];
1073    [alert setAlertStyle: NSWarningAlertStyle];
1074    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate alert -> button")];
1075    [alert setShowsSuppressionButton: YES];
1076   
1077    [alert runModal];
1078    if ([[alert suppressionButton] state])
1079        [fDefaults setBool: NO forKey: @"WarningDuplicate"];
1080    [alert release];
1081}
1082
1083- (void) openURL: (NSURL *) url
1084{
1085    [[NSURLDownload alloc] initWithRequest: [NSURLRequest requestWithURL: url] delegate: self];
1086}
1087
1088- (void) openURLShowSheet: (id) sender
1089{
1090    [NSApp beginSheet: fURLSheetWindow modalForWindow: fWindow modalDelegate: self
1091            didEndSelector: @selector(urlSheetDidEnd:returnCode:contextInfo:) contextInfo: nil];
1092}
1093
1094- (void) openURLEndSheet: (id) sender
1095{
1096    [fURLSheetWindow orderOut: sender];
1097    [NSApp endSheet: fURLSheetWindow returnCode: 1];
1098}
1099
1100- (void) openURLCancelEndSheet: (id) sender
1101{
1102    [fURLSheetWindow orderOut: sender];
1103    [NSApp endSheet: fURLSheetWindow returnCode: 0];
1104}
1105
1106- (void) controlTextDidChange: (NSNotification *) notification
1107{
1108    if ([notification object] != fURLSheetTextField)
1109        return;
1110   
1111    NSString * string = [fURLSheetTextField stringValue];
1112    BOOL enable = YES;
1113    if ([string isEqualToString: @""])
1114        enable = NO;
1115    else
1116    {
1117        NSRange prefixRange = [string rangeOfString: @"://"];
1118        if (prefixRange.location != NSNotFound && [string length] == NSMaxRange(prefixRange))
1119            enable = NO;
1120    }
1121   
1122    [fURLSheetOpenButton setEnabled: enable];
1123}
1124
1125- (void) urlSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
1126{
1127    [fURLSheetTextField selectText: self];
1128    if (returnCode != 1)
1129        return;
1130   
1131    NSString * urlString = [fURLSheetTextField stringValue];
1132   
1133    if ([urlString compare: @"magnet:" options: (NSAnchoredSearch | NSCaseInsensitiveSearch)])
1134        [self openMagnet: urlString];
1135    else
1136    {
1137        if ([urlString rangeOfString: @"://"].location == NSNotFound)
1138        {
1139            if ([urlString rangeOfString: @"."].location == NSNotFound)
1140            {
1141                NSInteger beforeCom;
1142                if ((beforeCom = [urlString rangeOfString: @"/"].location) != NSNotFound)
1143                    urlString = [NSString stringWithFormat: @"http://www.%@.com/%@",
1144                                    [urlString substringToIndex: beforeCom],
1145                                    [urlString substringFromIndex: beforeCom + 1]];
1146                else
1147                    urlString = [NSString stringWithFormat: @"http://www.%@.com/", urlString];
1148            }
1149            else
1150                urlString = [@"http://" stringByAppendingString: urlString];
1151        }
1152       
1153       
1154        else
1155        {
1156            NSURL * url = [NSURL URLWithString: urlString];
1157            [self performSelectorOnMainThread: @selector(openURL:) withObject: url waitUntilDone: NO];
1158        }
1159    }
1160}
1161
1162- (void) createFile: (id) sender
1163{
1164    [CreatorWindowController createTorrentFile: fLib];
1165}
1166
1167- (void) resumeSelectedTorrents: (id) sender
1168{
1169    [self resumeTorrents: [fTableView selectedTorrents]];
1170}
1171
1172- (void) resumeAllTorrents: (id) sender
1173{
1174    [self resumeTorrents: fTorrents];
1175}
1176
1177- (void) resumeTorrents: (NSArray *) torrents
1178{
1179    for (Torrent * torrent in torrents)
1180        [torrent setWaitToStart: YES];
1181   
1182    [self updateTorrentsInQueue];
1183}
1184
1185- (void) resumeSelectedTorrentsNoWait:  (id) sender
1186{
1187    [self resumeTorrentsNoWait: [fTableView selectedTorrents]];
1188}
1189
1190- (void) resumeWaitingTorrents: (id) sender
1191{
1192    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1193   
1194    for (Torrent * torrent in fTorrents)
1195        if (![torrent isActive] && [torrent waitingToStart])
1196            [torrents addObject: torrent];
1197   
1198    [self resumeTorrentsNoWait: torrents];
1199}
1200
1201- (void) resumeTorrentsNoWait: (NSArray *) torrents
1202{
1203    //iterate through instead of all at once to ensure no conflicts
1204    for (Torrent * torrent in torrents)
1205        [torrent startTransfer];
1206   
1207    [self updateUI];
1208    [self applyFilter: nil];
1209    [self updateTorrentHistory];
1210}
1211
1212- (void) stopSelectedTorrents: (id) sender
1213{
1214    [self stopTorrents: [fTableView selectedTorrents]];
1215}
1216
1217- (void) stopAllTorrents: (id) sender
1218{
1219    [self stopTorrents: fTorrents];
1220}
1221
1222- (void) stopTorrents: (NSArray *) torrents
1223{
1224    //don't want any of these starting then stopping
1225    for (Torrent * torrent in torrents)
1226        [torrent setWaitToStart: NO];
1227
1228    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
1229   
1230    [self updateUI];
1231    [self applyFilter: nil];
1232    [self updateTorrentHistory];
1233}
1234
1235- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1236{
1237    [torrents retain];
1238    NSInteger active = 0, downloading = 0;
1239
1240    if ([fDefaults boolForKey: @"CheckRemove"])
1241    {
1242        for (Torrent * torrent in torrents)
1243            if ([torrent isActive])
1244            {
1245                active++;
1246                if (![torrent isSeeding])
1247                    downloading++;
1248            }
1249
1250        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
1251        {
1252            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
1253                                    torrents, @"Torrents",
1254                                    [NSNumber numberWithBool: deleteData], @"DeleteData", nil];
1255           
1256            NSString * title, * message;
1257           
1258            const NSInteger selected = [torrents count];
1259            if (selected == 1)
1260            {
1261                NSString * torrentName = [[torrents objectAtIndex: 0] name];
1262               
1263                if (deleteData)
1264                    title = [NSString stringWithFormat:
1265                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1266                                " and trash the data file?", "Removal confirm panel -> title"), torrentName];
1267                else
1268                    title = [NSString stringWithFormat:
1269                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1270                                "Removal confirm panel -> title"), torrentName];
1271               
1272                message = NSLocalizedString(@"This transfer is active."
1273                            " Once removed, continuing the transfer will require the torrent file.",
1274                            "Removal confirm panel -> message");
1275            }
1276            else
1277            {
1278                if (deleteData)
1279                    title = [NSString stringWithFormat:
1280                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1281                                " and trash the data files?", "Removal confirm panel -> title"), selected];
1282                else
1283                    title = [NSString stringWithFormat:
1284                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list?",
1285                                "Removal confirm panel -> title"), selected];
1286               
1287                if (selected == active)
1288                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
1289                                "Removal confirm panel -> message part 1"), active];
1290                else
1291                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
1292                                "Removal confirm panel -> message part 1"), selected, active];
1293                message = [message stringByAppendingFormat: @" %@",
1294                                NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files.",
1295                                "Removal confirm panel -> message part 2")];
1296            }
1297           
1298            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
1299                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
1300                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
1301            return;
1302        }
1303    }
1304   
1305    [self confirmRemoveTorrents: torrents deleteData: deleteData];
1306}
1307
1308- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (NSDictionary *) dict
1309{
1310    NSArray * torrents = [dict objectForKey: @"Torrents"];
1311    if (returnCode == NSAlertDefaultReturn)
1312        [self confirmRemoveTorrents: torrents deleteData: [[dict objectForKey: @"DeleteData"] boolValue]];
1313    else
1314        [torrents release];
1315   
1316    [dict release];
1317}
1318
1319- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1320{
1321    //don't want any of these starting then stopping
1322    for (Torrent * torrent in torrents)
1323        [torrent setWaitToStart: NO];
1324   
1325    [fTorrents removeObjectsInArray: torrents];
1326   
1327    for (Torrent * torrent in torrents)
1328    {
1329        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1330        [fTableView removeCollapsedGroup: [torrent groupValue]];
1331       
1332        if (deleteData)
1333            [torrent trashData];
1334       
1335        [torrent closeRemoveTorrent];
1336    }
1337   
1338    [torrents release];
1339   
1340    [fTableView deselectAll: nil];
1341   
1342    [self updateTorrentsInQueue];
1343}
1344
1345- (void) removeNoDelete: (id) sender
1346{
1347    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO];
1348}
1349
1350- (void) removeDeleteData: (id) sender
1351{
1352    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES];
1353}
1354
1355- (void) moveDataFilesSelected: (id) sender
1356{
1357    [self moveDataFiles: [fTableView selectedTorrents]];
1358}
1359
1360- (void) moveDataFiles: (NSArray *) torrents
1361{
1362    NSOpenPanel * panel = [NSOpenPanel openPanel];
1363    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1364    [panel setAllowsMultipleSelection: NO];
1365    [panel setCanChooseFiles: NO];
1366    [panel setCanChooseDirectories: YES];
1367    [panel setCanCreateDirectories: YES];
1368   
1369    torrents = [torrents retain];
1370    NSInteger count = [torrents count];
1371    if (count == 1)
1372        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1373                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1374    else
1375        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1376                            "Move torrent -> select destination folder"), count]];
1377       
1378    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1379        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1380}
1381
1382- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) torrents
1383{
1384    if (code == NSOKButton)
1385    {
1386        for (Torrent * torrent in torrents)
1387            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1388    }
1389   
1390    [torrents release];
1391}
1392
1393- (void) copyTorrentFiles: (id) sender
1394{
1395    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1396}
1397
1398- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1399{
1400    if ([torrents count] <= 0)
1401    {
1402        [torrents release];
1403        return;
1404    }
1405
1406    Torrent * torrent = [torrents objectAtIndex: 0];
1407
1408    //warn user if torrent file can't be found
1409    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1410    {
1411        NSAlert * alert = [[NSAlert alloc] init];
1412        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1413        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1414                                "Torrent file copy alert -> title"), [torrent name]]];
1415        [alert setInformativeText: [NSString stringWithFormat:
1416                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1417                                    [torrent torrentLocation]]];
1418        [alert setAlertStyle: NSWarningAlertStyle];
1419       
1420        [alert runModal];
1421        [alert release];
1422       
1423        [torrents removeObjectAtIndex: 0];
1424        [self copyTorrentFileForTorrents: torrents];
1425    }
1426    else
1427    {
1428        NSSavePanel * panel = [NSSavePanel savePanel];
1429        [panel setAllowedFileTypes: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]];
1430        [panel setCanSelectHiddenExtension: YES];
1431       
1432        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1433            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1434    }
1435}
1436
1437- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSMutableArray *) torrents
1438{
1439    //copy torrent to new location with name of data file
1440    if (code == NSOKButton)
1441        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1442   
1443    [torrents removeObjectAtIndex: 0];
1444    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1445}
1446
1447- (void) revealFile: (id) sender
1448{
1449    NSArray * selected = [fTableView selectedTorrents];
1450    if ([NSApp isOnSnowLeopardOrBetter])
1451    {
1452        NSMutableArray * paths = [NSMutableArray arrayWithCapacity: [selected count]];
1453        for (Torrent * torrent in [fTableView selectedTorrents])
1454        {
1455            NSString * location = [torrent dataLocation];
1456            if (location)
1457                [paths addObject: [NSURL fileURLWithPath: location]];
1458        }
1459       
1460        if ([paths count] > 0)
1461            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: paths];
1462    }
1463    else
1464    {
1465        for (Torrent * torrent in selected)
1466        {
1467            NSString * location = [torrent dataLocation];
1468            if (location)
1469                [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
1470        }
1471    }
1472}
1473
1474- (void) announceSelectedTorrents: (id) sender
1475{
1476    for (Torrent * torrent in [fTableView selectedTorrents])
1477    {
1478        if ([torrent canManualAnnounce])
1479            [torrent manualAnnounce];
1480    }
1481}
1482
1483- (void) verifySelectedTorrents: (id) sender
1484{
1485    [self verifyTorrents: [fTableView selectedTorrents]];
1486}
1487
1488- (void) verifyTorrents: (NSArray *) torrents
1489{
1490    for (Torrent * torrent in torrents)
1491        [torrent resetCache];
1492   
1493    [self applyFilter: nil];
1494}
1495
1496- (void) showPreferenceWindow: (id) sender
1497{
1498    NSWindow * window = [fPrefsController window];
1499    if (![window isVisible])
1500        [window center];
1501
1502    [window makeKeyAndOrderFront: nil];
1503}
1504
1505- (void) showAboutWindow: (id) sender
1506{
1507    [[AboutWindowController aboutController] showWindow: nil];
1508}
1509
1510- (void) showInfo: (id) sender
1511{
1512    if ([[fInfoController window] isVisible])
1513        [fInfoController close];
1514    else
1515    {
1516        [fInfoController updateInfoStats];
1517        [[fInfoController window] orderFront: nil];
1518       
1519        if ([fInfoController canQuickLook]
1520            && [QLPreviewPanelSL sharedPreviewPanelExists] && [[QLPreviewPanelSL sharedPreviewPanel] isVisible])
1521            [[QLPreviewPanelSL sharedPreviewPanel] reloadData];
1522       
1523    }
1524}
1525
1526- (void) resetInfo
1527{
1528    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1529   
1530    if ([NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
1531        && [[QLPreviewPanelSL sharedPreviewPanel] isVisible])
1532        [[QLPreviewPanelSL sharedPreviewPanel] reloadData];
1533}
1534
1535- (void) setInfoTab: (id) sender
1536{
1537    if (sender == fNextInfoTabItem)
1538        [fInfoController setNextTab];
1539    else
1540        [fInfoController setPreviousTab];
1541}
1542
1543- (void) showMessageWindow: (id) sender
1544{
1545    [fMessageController showWindow: nil];
1546}
1547
1548- (void) showStatsWindow: (id) sender
1549{
1550    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1551}
1552
1553- (void) updateUI
1554{
1555    [fTorrents makeObjectsPerformSelector: @selector(update)];
1556   
1557    if (![NSApp isHidden])
1558    {
1559        if ([fWindow isVisible])
1560        {
1561            [self sortTorrents];
1562           
1563            //update status bar
1564            if (![fStatusBar isHidden])
1565            {
1566                //set rates
1567                [fTotalDLField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_DOWN)]];
1568                [fTotalULField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_UP)]];
1569               
1570                //set status button text
1571                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1572                BOOL total;
1573                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1574                {
1575                    tr_session_stats stats;
1576                    if (total)
1577                        tr_sessionGetCumulativeStats(fLib, &stats);
1578                    else
1579                        tr_sessionGetStats(fLib, &stats);
1580                   
1581                    statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") stringByAppendingFormat: @": %@",
1582                                    [NSString stringForRatio: stats.ratio]];
1583                }
1584                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1585                {
1586                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1587                   
1588                    tr_session_stats stats;
1589                    if (total)
1590                        tr_sessionGetCumulativeStats(fLib, &stats);
1591                    else
1592                        tr_sessionGetStats(fLib, &stats);
1593                   
1594                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1595                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1596                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1597                }
1598               
1599                [fStatusButton setTitle: statusString];
1600                [self resizeStatusButton];
1601            }
1602        }
1603
1604        //update non-constant parts of info window
1605        if ([[fInfoController window] isVisible])
1606            [fInfoController updateInfoStats];
1607    }
1608   
1609    //badge dock
1610    [fBadger updateBadge];
1611}
1612
1613- (void) resizeStatusButton
1614{
1615    [fStatusButton sizeToFit];
1616   
1617    //width ends up being too long
1618    NSRect statusFrame = [fStatusButton frame];
1619    statusFrame.size.width -= 25.0;
1620   
1621    CGFloat difference = NSMaxX(statusFrame) + 5.0 - [fTotalDLImageView frame].origin.x;
1622    if (difference > 0)
1623        statusFrame.size.width -= difference;
1624   
1625    [fStatusButton setFrame: statusFrame];
1626}
1627
1628- (void) setBottomCountText: (BOOL) filtering
1629{
1630    NSString * totalTorrentsString;
1631    NSInteger totalCount = [fTorrents count];
1632    if (totalCount != 1)
1633        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1634    else
1635        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1636   
1637    if (filtering)
1638    {
1639        NSInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1640        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1641            count -= [fDisplayedTorrents count];
1642       
1643        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d of %@", "Status bar transfer count"),
1644                                count, totalTorrentsString];
1645    }
1646   
1647    [fTotalTorrentsField setStringValue: totalTorrentsString];
1648}
1649
1650- (void) updateSpeedFieldsToolTips
1651{
1652    NSString * uploadText, * downloadText;
1653   
1654    if ([fDefaults boolForKey: @"SpeedLimit"])
1655    {
1656        NSString * speedString = [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1657                                    NSLocalizedString(@"Speed Limit", "Status Bar -> speed tooltip")];
1658       
1659        uploadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]];
1660        downloadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]];
1661    }
1662    else
1663    {
1664        if ([fDefaults boolForKey: @"CheckUpload"])
1665            uploadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1666                            [fDefaults integerForKey: @"UploadLimit"]];
1667        else
1668            uploadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1669       
1670        if ([fDefaults boolForKey: @"CheckDownload"])
1671            downloadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1672                            [fDefaults integerForKey: @"DownloadLimit"]];
1673        else
1674            downloadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1675    }
1676   
1677    uploadText = [NSLocalizedString(@"Total upload rate", "Status Bar -> speed tooltip")
1678                    stringByAppendingFormat: @": %@", uploadText];
1679    downloadText = [NSLocalizedString(@"Total download rate", "Status Bar -> speed tooltip")
1680                    stringByAppendingFormat: @": %@", downloadText];
1681   
1682    [fTotalULField setToolTip: uploadText];
1683    [fTotalDLField setToolTip: downloadText];
1684}
1685
1686- (void) updateTorrentsInQueue
1687{
1688    NSUInteger desiredDownloadActive = [fDefaults boolForKey: @"Queue"] ? [self numToStartFromQueue: YES] : NSUIntegerMax,
1689                desiredSeedActive = [fDefaults boolForKey: @"QueueSeed"] ? [self numToStartFromQueue: NO] : NSUIntegerMax;
1690   
1691    for (Torrent * torrent in fTorrents)
1692    {
1693        if (desiredDownloadActive == 0 && desiredSeedActive == 0)
1694            break;
1695       
1696        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1697        {
1698            if (![torrent allDownloaded])
1699            {
1700                if (desiredDownloadActive > 0)
1701                {
1702                    [torrent startTransfer];
1703                    if ([torrent isActive])
1704                        --desiredDownloadActive;
1705                    [torrent update];
1706                }
1707            }
1708            else
1709            {
1710                if (desiredSeedActive > 0)
1711                {
1712                    [torrent startTransfer];
1713                    if ([torrent isActive])
1714                        --desiredSeedActive;
1715                    [torrent update];
1716                }
1717            }
1718        }
1719    }
1720   
1721    [self updateUI];
1722    [self applyFilter: nil];
1723    [self updateTorrentHistory];
1724}
1725
1726- (NSUInteger) numToStartFromQueue: (BOOL) downloadQueue
1727{
1728    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1729        return 0;
1730   
1731    NSUInteger desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1732       
1733    for (Torrent * torrent in fTorrents)
1734    {
1735        if (desired == 0)
1736            break;
1737       
1738        if ([torrent isChecking])
1739            --desired;
1740        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1741        {
1742            if ([torrent allDownloaded] != downloadQueue)
1743                --desired;
1744        }
1745        else;
1746    }
1747   
1748    return desired;
1749}
1750
1751- (void) torrentFinishedDownloading: (NSNotification *) notification
1752{
1753    Torrent * torrent = [notification object];
1754   
1755    if ([torrent isActive])
1756    {
1757        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1758        {
1759            NSSound * sound;
1760            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1761            {
1762                [sound setDelegate: self];
1763                fSoundPlaying = YES;
1764                [sound play];
1765            }
1766        }
1767       
1768        NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_DOWNLOAD_COMPLETE forKey: @"Type"];
1769       
1770        NSString * location = [torrent dataLocation];
1771        if (location)
1772            [clickContext setObject: location forKey: @"Location"];
1773       
1774        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1775                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1776                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1777       
1778        if (![fWindow isMainWindow])
1779            [fBadger incrementCompleted];
1780       
1781        //bounce download stack
1782        [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"com.apple.DownloadFileFinished"
1783            object: [torrent dataLocation]];
1784       
1785        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] == 0)
1786        {
1787            [torrent stopTransfer];
1788            [torrent setWaitToStart: YES];
1789        }
1790    }
1791   
1792    [self updateTorrentsInQueue];
1793}
1794
1795- (void) torrentRestartedDownloading: (NSNotification *) notification
1796{
1797    Torrent * torrent = [notification object];
1798    if ([torrent isActive])
1799    {
1800        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] == 0)
1801        {
1802            [torrent stopTransfer];
1803            [torrent setWaitToStart: YES];
1804        }
1805    }
1806   
1807    [self updateTorrentsInQueue];
1808}
1809
1810- (void) torrentStoppedForRatio: (NSNotification *) notification
1811{
1812    Torrent * torrent = [notification object];
1813   
1814    [self updateTorrentsInQueue];
1815   
1816    if ([[fTableView selectedTorrents] containsObject: torrent])
1817    {
1818        [fInfoController updateInfoStats];
1819        [fInfoController updateOptions];
1820    }
1821   
1822    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1823    {
1824        NSSound * sound;
1825        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1826        {
1827            [sound setDelegate: self];
1828            fSoundPlaying = YES;
1829            [sound play];
1830        }
1831    }
1832   
1833    NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_SEEDING_COMPLETE forKey: @"Type"];
1834   
1835    NSString * location = [torrent dataLocation];
1836    if (location)
1837        [clickContext setObject: location forKey: @"Location"];
1838   
1839    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1840                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1841                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1842}
1843
1844- (void) updateTorrentHistory
1845{
1846    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1847   
1848    for (Torrent * torrent in fTorrents)
1849        [history addObject: [torrent history]];
1850   
1851    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST] atomically: YES];
1852}
1853
1854- (void) setSort: (id) sender
1855{
1856    NSString * sortType;
1857    switch ([sender tag])
1858    {
1859        case SORT_ORDER_TAG:
1860            sortType = SORT_ORDER;
1861            [fDefaults setBool: NO forKey: @"SortReverse"];
1862            break;
1863        case SORT_DATE_TAG:
1864            sortType = SORT_DATE;
1865            break;
1866        case SORT_NAME_TAG:
1867            sortType = SORT_NAME;
1868            break;
1869        case SORT_PROGRESS_TAG:
1870            sortType = SORT_PROGRESS;
1871            break;
1872        case SORT_STATE_TAG:
1873            sortType = SORT_STATE;
1874            break;
1875        case SORT_TRACKER_TAG:
1876            sortType = SORT_TRACKER;
1877            break;
1878        case SORT_ACTIVITY_TAG:
1879            sortType = SORT_ACTIVITY;
1880            break;
1881        default:
1882            NSAssert1(NO, @"Unknown sort tag received: %d", [sender tag]);
1883            return;
1884    }
1885   
1886    [fDefaults setObject: sortType forKey: @"Sort"];
1887    [self applyFilter: nil]; //better than calling sortTorrents because it will even apply to queue order
1888}
1889
1890- (void) setSortByGroup: (id) sender
1891{
1892    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1893    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1894   
1895    //expand all groups
1896    if (sortByGroup)
1897        [fTableView removeAllCollapsedGroups];
1898   
1899    [self applyFilter: nil];
1900}
1901
1902- (void) setSortReverse: (id) sender
1903{
1904    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1905    [self sortTorrents];
1906}
1907
1908- (void) sortTorrents
1909{
1910    NSArray * selectedValues = [fTableView selectedValues];
1911   
1912    [self sortTorrentsIgnoreSelected]; //actually sort
1913   
1914    [fTableView selectValues: selectedValues];
1915}
1916
1917- (void) sortTorrentsIgnoreSelected
1918{
1919    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1920   
1921    if (![sortType isEqualToString: SORT_ORDER])
1922    {
1923        const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1924       
1925        NSArray * descriptors;
1926        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1927                                                selector: @selector(compareFinder:)] autorelease];
1928       
1929        if ([sortType isEqualToString: SORT_STATE])
1930        {
1931            NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1932                            * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1933                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1934           
1935            descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1936                                                                nameDescriptor, nil];
1937        }
1938        else if ([sortType isEqualToString: SORT_PROGRESS])
1939        {
1940            NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1941                            * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1942                                                            ascending: asc] autorelease],
1943                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1944           
1945            descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1946                                                                nameDescriptor, nil];
1947        }
1948        else if ([sortType isEqualToString: SORT_TRACKER])
1949        {
1950            NSSortDescriptor * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerSortKey" ascending: asc
1951                                                    selector: @selector(localizedCaseInsensitiveCompare:)] autorelease];
1952           
1953            descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, nil];
1954        }
1955        else if ([sortType isEqualToString: SORT_ACTIVITY])
1956        {
1957            NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1958            NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1959                                                        autorelease];
1960           
1961            descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
1962        }
1963        else if ([sortType isEqualToString: SORT_DATE])
1964        {
1965            NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1966           
1967            descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
1968        }
1969        else
1970            descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, nil];
1971       
1972        //actually sort
1973        if ([fDefaults boolForKey: @"SortByGroup"])
1974        {
1975            for (TorrentGroup * group in fDisplayedTorrents)
1976                [[group torrents] sortUsingDescriptors: descriptors];
1977        }
1978        else
1979            [fDisplayedTorrents sortUsingDescriptors: descriptors];
1980       
1981        [descriptors release];
1982    }
1983   
1984    [fTableView reloadData];
1985}
1986
1987- (void) applyFilter: (id) sender
1988{
1989    //get all the torrents in the table
1990    NSMutableArray * previousTorrents;
1991    if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1992    {
1993        previousTorrents = [NSMutableArray array];
1994       
1995        for (TorrentGroup * group in fDisplayedTorrents)
1996            [previousTorrents addObjectsFromArray: [group torrents]];
1997    }
1998    else
1999        previousTorrents = fDisplayedTorrents;
2000   
2001    NSArray * selectedValues = [fTableView selectedValues];
2002   
2003    NSUInteger active = 0, downloading = 0, seeding = 0, paused = 0;
2004    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2005    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
2006    if ([filterType isEqualToString: FILTER_ACTIVE])
2007        filterActive = YES;
2008    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2009        filterDownload = YES;
2010    else if ([filterType isEqualToString: FILTER_SEED])
2011        filterSeed = YES;
2012    else if ([filterType isEqualToString: FILTER_PAUSE])
2013        filterPause = YES;
2014    else
2015        filterStatus = NO;
2016   
2017    const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
2018    const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
2019   
2020    NSString * searchString = [fSearchFilterField stringValue];
2021    const BOOL filterText = [searchString length] > 0,
2022            filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
2023   
2024    NSMutableArray * allTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2025   
2026    //get count of each type
2027    for (Torrent * torrent in fTorrents)
2028    {
2029        //check status
2030        if ([torrent isActive] && ![torrent isCheckingWaiting])
2031        {
2032            const BOOL isActive = ![torrent isStalled];
2033            if (isActive)
2034                active++;
2035           
2036            if ([torrent isSeeding])
2037            {
2038                seeding++;
2039                if (filterStatus && !((filterActive && isActive) || filterSeed))
2040                    continue;
2041            }
2042            else
2043            {
2044                downloading++;
2045                if (filterStatus && !((filterActive && isActive) || filterDownload))
2046                    continue;
2047            }
2048        }
2049        else
2050        {
2051            paused++;
2052            if (filterStatus && !filterPause)
2053                continue;
2054        }
2055       
2056        //checkGroup
2057        if (filterGroup)
2058            if ([torrent groupValue] != groupFilterValue)
2059                continue;
2060       
2061        //check text field
2062        if (filterText)
2063        {
2064            if (filterTracker)
2065            {
2066                BOOL removeTextField = YES;
2067                for (NSString * tracker in [torrent allTrackersFlat])
2068                {
2069                    if ([tracker rangeOfString: searchString options:
2070                            (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound)
2071                    {
2072                        removeTextField = NO;
2073                        break;
2074                    }
2075                }
2076               
2077                if (removeTextField)
2078                    continue;
2079            }
2080            else
2081            {
2082                if ([[torrent name] rangeOfString: searchString options:
2083                        (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound)
2084                    continue;
2085            }
2086        }
2087       
2088        [allTorrents addObject: torrent];
2089    }
2090   
2091    //set button tooltips
2092    [fNoFilterButton setCount: [fTorrents count]];
2093    [fActiveFilterButton setCount: active];
2094    [fDownloadFilterButton setCount: downloading];
2095    [fSeedFilterButton setCount: seeding];
2096    [fPauseFilterButton setCount: paused];
2097   
2098    //clear display cache for not-shown torrents
2099    [previousTorrents removeObjectsInArray: allTorrents];
2100    for (Torrent * torrent in previousTorrents)
2101        [torrent setPreviousFinishedPieces: nil];
2102   
2103    //place torrents into groups
2104    const BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"];
2105    if (groupRows)
2106    {
2107        NSMutableArray * oldTorrentGroups = [NSMutableArray array];
2108        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2109            [oldTorrentGroups addObjectsFromArray: fDisplayedTorrents];
2110       
2111        [fDisplayedTorrents removeAllObjects];
2112       
2113        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2114        [allTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2115       
2116        NSMutableArray * groupTorrents;
2117        NSInteger lastGroupValue = -2, currentOldGroupIndex = 0;
2118        for (Torrent * torrent in allTorrents)
2119        {
2120            NSInteger groupValue = [torrent groupValue];
2121            if (groupValue != lastGroupValue)
2122            {
2123                lastGroupValue = groupValue;
2124               
2125                TorrentGroup * group = nil;
2126               
2127                //try to see if the group already exists
2128                for (; currentOldGroupIndex < [oldTorrentGroups count]; currentOldGroupIndex++)
2129                {
2130                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
2131                    const NSInteger currentGroupValue = [currentGroup groupIndex];
2132                    if (currentGroupValue == groupValue)
2133                    {
2134                        group = currentGroup;
2135                        [[currentGroup torrents] removeAllObjects];
2136                       
2137                        currentOldGroupIndex++;
2138                    }
2139                   
2140                    if (currentGroupValue >= groupValue)
2141                        break;
2142                }
2143               
2144                if (!group)
2145                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2146                [fDisplayedTorrents addObject: group];
2147               
2148                groupTorrents = [group torrents];
2149            }
2150           
2151            [groupTorrents addObject: torrent];
2152        }
2153    }
2154    else
2155        [fDisplayedTorrents setArray: allTorrents];
2156   
2157    //actually sort
2158    [self sortTorrentsIgnoreSelected];
2159   
2160    //reset expanded/collapsed rows
2161    if (groupRows)
2162    {
2163        for (TorrentGroup * group in fDisplayedTorrents)
2164        {
2165            if ([fTableView isGroupCollapsed: [group groupIndex]])
2166                [fTableView collapseItem: group];
2167            else
2168                [fTableView expandItem: group];
2169        }
2170    }
2171   
2172    [fTableView selectValues: selectedValues];
2173    [self resetInfo]; //if group is already selected, but the torrents in it change
2174   
2175    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2176   
2177    [self setWindowSizeToFit];
2178}
2179
2180//resets filter and sorts torrents
2181- (void) setFilter: (id) sender
2182{
2183    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2184   
2185    NSButton * prevFilterButton;
2186    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2187        prevFilterButton = fPauseFilterButton;
2188    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2189        prevFilterButton = fActiveFilterButton;
2190    else if ([oldFilterType isEqualToString: FILTER_SEED])
2191        prevFilterButton = fSeedFilterButton;
2192    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2193        prevFilterButton = fDownloadFilterButton;
2194    else
2195        prevFilterButton = fNoFilterButton;
2196   
2197    if (sender != prevFilterButton)
2198    {
2199        [prevFilterButton setState: NSOffState];
2200        [sender setState: NSOnState];
2201
2202        NSString * filterType;
2203        if (sender == fActiveFilterButton)
2204            filterType = FILTER_ACTIVE;
2205        else if (sender == fDownloadFilterButton)
2206            filterType = FILTER_DOWNLOAD;
2207        else if (sender == fPauseFilterButton)
2208            filterType = FILTER_PAUSE;
2209        else if (sender == fSeedFilterButton)
2210            filterType = FILTER_SEED;
2211        else
2212            filterType = FILTER_NONE;
2213
2214        [fDefaults setObject: filterType forKey: @"Filter"];
2215    }
2216    else
2217        [sender setState: NSOnState];
2218
2219    [self applyFilter: nil];
2220}
2221
2222- (void) setFilterSearchType: (id) sender
2223{
2224    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2225   
2226    NSInteger prevTag, currentTag = [sender tag];
2227    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2228        prevTag = FILTER_TYPE_TAG_TRACKER;
2229    else
2230        prevTag = FILTER_TYPE_TAG_NAME;
2231   
2232    if (currentTag != prevTag)
2233    {
2234        NSString * filterType;
2235        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2236            filterType = FILTER_TYPE_TRACKER;
2237        else
2238            filterType = FILTER_TYPE_NAME;
2239       
2240        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2241       
2242        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2243    }
2244   
2245    [self applyFilter: nil];
2246}
2247
2248- (void) switchFilter: (id) sender
2249{
2250    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2251   
2252    NSButton * button;
2253    if ([filterType isEqualToString: FILTER_NONE])
2254        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2255    else if ([filterType isEqualToString: FILTER_ACTIVE])
2256        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2257    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2258        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2259    else if ([filterType isEqualToString: FILTER_SEED])
2260        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2261    else if ([filterType isEqualToString: FILTER_PAUSE])
2262        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2263    else
2264        button = fNoFilterButton;
2265   
2266    [self setFilter: button];
2267}
2268
2269- (void) setStatusLabel: (id) sender
2270{
2271    NSString * statusLabel;
2272    switch ([sender tag])
2273    {
2274        case STATUS_RATIO_TOTAL_TAG:
2275            statusLabel = STATUS_RATIO_TOTAL;
2276            break;
2277        case STATUS_RATIO_SESSION_TAG:
2278            statusLabel = STATUS_RATIO_SESSION;
2279            break;
2280        case STATUS_TRANSFER_TOTAL_TAG:
2281            statusLabel = STATUS_TRANSFER_TOTAL;
2282            break;
2283        case STATUS_TRANSFER_SESSION_TAG:
2284            statusLabel = STATUS_TRANSFER_SESSION;
2285            break;
2286        default:
2287            NSAssert1(NO, @"Unknown status label tag received: %d", [sender tag]);
2288            return;
2289    }
2290   
2291    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2292    [self updateUI];
2293}
2294
2295- (void) menuNeedsUpdate: (NSMenu *) menu
2296{
2297    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu || menu == fGroupFilterMenu)
2298    {
2299        const BOOL filter = menu == fGroupFilterMenu;
2300       
2301        const NSInteger remaining = filter ? 3 : 0;
2302        for (NSInteger i = [menu numberOfItems]-1; i >= remaining; i--)
2303            [menu removeItemAtIndex: i];
2304       
2305        NSMenu * groupMenu;
2306        if (!filter)
2307            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2308        else
2309            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:) isSmall: YES];
2310       
2311        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2312        for (NSInteger i = 0; i < groupMenuCount; i++)
2313        {
2314            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2315            [groupMenu removeItemAtIndex: 0];
2316            [menu addItem: item];
2317            [item release];
2318        }
2319    }
2320    else if (menu == fUploadMenu || menu == fDownloadMenu)
2321    {
2322        if ([menu numberOfItems] > 3)
2323            return;
2324       
2325        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2326       
2327        NSMenuItem * item;
2328        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2329        {
2330            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2331                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2332                    keyEquivalent: @""];
2333            [item setTarget: self];
2334            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2335            [menu addItem: item];
2336            [item release];
2337        }
2338    }
2339    else if (menu == fRatioStopMenu)
2340    {
2341        if ([menu numberOfItems] > 3)
2342            return;
2343       
2344        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2345       
2346        NSMenuItem * item;
2347        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2348        {
2349            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2350                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2351            [item setTarget: self];
2352            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2353            [menu addItem: item];
2354            [item release];
2355        }
2356    }
2357    else;
2358}
2359
2360- (void) setGroup: (id) sender
2361{
2362    for (Torrent * torrent in [fTableView selectedTorrents])
2363    {
2364        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2365       
2366        [torrent setGroupValue: [sender tag]];
2367    }
2368   
2369    [self applyFilter: nil];
2370    [self updateUI];
2371    [self updateTorrentHistory];
2372}
2373
2374- (void) setGroupFilter: (id) sender
2375{
2376    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2377    [self updateGroupsFilterButton];
2378    [self applyFilter: nil];
2379}
2380
2381- (void) updateGroupsFilterButton
2382{
2383    NSInteger groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2384   
2385    NSImage * icon;
2386    NSString * toolTip;
2387    if (groupIndex == GROUP_FILTER_ALL_TAG)
2388    {
2389        icon = [NSImage imageNamed: @"PinTemplate.png"];
2390        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2391    }
2392    else
2393    {
2394        icon = [[GroupsController groups] imageForIndex: groupIndex];
2395        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2396                                                : NSLocalizedString(@"None", "Groups -> Button");
2397        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2398    }
2399   
2400    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2401    [fGroupsButton setToolTip: toolTip];
2402}
2403
2404- (void) updateGroupsFilters: (NSNotification *) notification
2405{
2406    [self updateGroupsFilterButton];
2407    [self applyFilter: nil];
2408}
2409
2410- (void) toggleSpeedLimit: (id) sender
2411{
2412    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2413    [self speedLimitChanged: sender];
2414}
2415
2416- (void) speedLimitChanged: (id) sender
2417{
2418    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2419    [self updateSpeedFieldsToolTips];
2420}
2421
2422//dict has been retained
2423- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2424{
2425    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2426
2427    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2428    [self updateSpeedFieldsToolTips];
2429   
2430    if (![[dict objectForKey: @"ByUser"] boolValue])
2431        [GrowlApplicationBridge notifyWithTitle: isLimited
2432                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2433                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2434            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2435            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2436   
2437    [dict release];
2438}
2439
2440- (void) setLimitGlobalEnabled: (id) sender
2441{
2442    BOOL upload = [sender menu] == fUploadMenu;
2443    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2444   
2445    [fPrefsController applySpeedSettings: nil];
2446}
2447
2448- (void) setQuickLimitGlobal: (id) sender
2449{
2450    BOOL upload = [sender menu] == fUploadMenu;
2451    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2452    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2453   
2454    [fPrefsController updateLimitFields];
2455    [fPrefsController applySpeedSettings: nil];
2456}
2457
2458- (void) setRatioGlobalEnabled: (id) sender
2459{
2460    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2461   
2462    [fPrefsController applyRatioSetting: nil];
2463}
2464
2465- (void) setQuickRatioGlobal: (id) sender
2466{
2467    [fDefaults setBool: YES forKey: @"RatioCheck"];
2468    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2469   
2470    [fPrefsController updateRatioStopField];
2471}
2472
2473- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2474{
2475    fSoundPlaying = NO;
2476}
2477
2478- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2479{
2480    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2481    {
2482        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2483            return;
2484       
2485        if (fAutoImportTimer)
2486        {
2487            if ([fAutoImportTimer isValid])
2488                [fAutoImportTimer invalidate];
2489            [fAutoImportTimer release];
2490            fAutoImportTimer = nil;
2491        }
2492       
2493        //check again in 10 seconds in case torrent file wasn't complete
2494        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2495            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2496       
2497        [self checkAutoImportDirectory];
2498    }
2499}
2500
2501- (void) changeAutoImport
2502{
2503    if (fAutoImportTimer)
2504    {
2505        if ([fAutoImportTimer isValid])
2506            [fAutoImportTimer invalidate];
2507        [fAutoImportTimer release];
2508        fAutoImportTimer = nil;
2509    }
2510   
2511    if (fAutoImportedNames)
2512    {
2513        [fAutoImportedNames release];
2514        fAutoImportedNames = nil;
2515    }
2516   
2517    [self checkAutoImportDirectory];
2518}
2519
2520- (void) checkAutoImportDirectory
2521{
2522    NSString * path;
2523    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2524        return;
2525   
2526    path = [path stringByExpandingTildeInPath];
2527   
2528    NSArray * importedNames;
2529    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2530        return;
2531   
2532    //only check files that have not been checked yet
2533    NSMutableArray * newNames = [importedNames mutableCopy];
2534   
2535    if (fAutoImportedNames)
2536        [newNames removeObjectsInArray: fAutoImportedNames];
2537    else
2538        fAutoImportedNames = [[NSMutableArray alloc] init];
2539    [fAutoImportedNames setArray: importedNames];
2540   
2541    for (NSString * file in newNames)
2542    {
2543        if ([file hasPrefix: @"."])
2544            continue;
2545       
2546        NSString * fullFile = [path stringByAppendingPathComponent: file];
2547       
2548        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2549                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2550            continue;
2551       
2552        tr_ctor * ctor = tr_ctorNew(fLib);
2553        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2554       
2555        switch (tr_torrentParse(ctor, NULL))
2556        {
2557            case TR_PARSE_OK:
2558                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2559               
2560                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2561                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2562                    clickContext: nil];
2563                break;
2564           
2565            case TR_PARSE_ERR:
2566                [fAutoImportedNames removeObject: file];
2567        }
2568       
2569        tr_ctorFree(ctor);
2570    }
2571   
2572    [newNames release];
2573}
2574
2575- (void) beginCreateFile: (NSNotification *) notification
2576{
2577    if (![fDefaults boolForKey: @"AutoImport"])
2578        return;
2579   
2580    NSString * location = [notification object],
2581            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2582   
2583    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2584                                    isEqualToString: [path stringByExpandingTildeInPath]])
2585        [fAutoImportedNames addObject: [location lastPathComponent]];
2586}
2587
2588- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2589{
2590    if (item)
2591        return [[item torrents] count];
2592    else
2593        return [fDisplayedTorrents count];
2594}
2595
2596- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2597{
2598    if (item)
2599        return [[item torrents] objectAtIndex: index];
2600    else
2601        return [fDisplayedTorrents objectAtIndex: index];
2602}
2603
2604- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2605{
2606    return ![item isKindOfClass: [Torrent class]];
2607}
2608
2609- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2610{
2611    if ([item isKindOfClass: [Torrent class]])
2612        return [item hashString];
2613    else
2614    {
2615        NSString * ident = [tableColumn identifier];
2616        if ([ident isEqualToString: @"Group"])
2617        {
2618            NSInteger group = [item groupIndex];
2619            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2620                                : NSLocalizedString(@"No Group", "Group table row");
2621        }
2622        else if ([ident isEqualToString: @"Color"])
2623        {
2624            NSInteger group = [item groupIndex];
2625            return [[GroupsController groups] imageForIndex: group];
2626        }
2627        else if ([ident isEqualToString: @"DL Image"])
2628            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2629        else if ([ident isEqualToString: @"UL Image"])
2630            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2631                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2632        else
2633        {
2634            TorrentGroup * group = (TorrentGroup *)item;
2635           
2636            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2637                return [NSString stringForRatio: [group ratio]];
2638            else
2639            {
2640                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2641                return [NSString stringForSpeed: rate];
2642            }
2643        }
2644    }
2645}
2646
2647- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2648{
2649    //only allow reordering of rows if sorting by order
2650    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2651    {
2652        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2653        for (id torrent in items)
2654        {
2655            if (![torrent isKindOfClass: [Torrent class]])
2656                return NO;
2657           
2658            [indexSet addIndex: [fTableView rowForItem: torrent]];
2659        }
2660       
2661        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2662        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2663        return YES;
2664    }
2665    return NO;
2666}
2667
2668- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2669    proposedChildIndex: (NSInteger) index
2670{
2671    NSPasteboard * pasteboard = [info draggingPasteboard];
2672    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2673    {
2674        if ([fDefaults boolForKey: @"SortByGroup"])
2675        {
2676            if (!item)
2677                return NSDragOperationNone;
2678           
2679            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2680            {
2681                if ([item isKindOfClass: [Torrent class]])
2682                {
2683                    TorrentGroup * group = [fTableView parentForItem: item];
2684                    index = [[group torrents] indexOfObject: item] + 1;
2685                    item = group;
2686                }
2687            }
2688            else
2689            {
2690                if ([item isKindOfClass: [Torrent class]])
2691                    item = [fTableView parentForItem: item];
2692                index = NSOutlineViewDropOnItemIndex;
2693            }
2694        }
2695        else
2696        {
2697            if (item)
2698            {
2699                index = [fTableView rowForItem: item] + 1;
2700                item = nil;
2701            }
2702        }
2703       
2704        [fTableView setDropItem: item dropChildIndex: index];
2705        return NSDragOperationGeneric;
2706    }
2707   
2708    return NSDragOperationNone;
2709}
2710
2711- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2712    childIndex: (NSInteger) newRow
2713{
2714    NSPasteboard * pasteboard = [info draggingPasteboard];
2715    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2716    {
2717        //remember selected rows
2718        NSArray * selectedValues = [fTableView selectedValues];
2719   
2720        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2721       
2722        //get the torrents to move
2723        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2724        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2725            [movingTorrents addObject: [fTableView itemAtRow: i]];
2726       
2727        //reset groups
2728        if (item)
2729        {
2730            //change groups
2731            NSInteger groupValue = [item groupIndex];
2732            for (Torrent * torrent in movingTorrents)
2733            {
2734                //have to reset objects here to avoid weird crash
2735                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2736                [[item torrents] addObject: torrent];
2737               
2738                [torrent setGroupValue: groupValue];
2739            }
2740            //part 2 of avoiding weird crash
2741            [fTableView reloadItem: nil reloadChildren: YES];
2742        }
2743       
2744        //reorder queue order
2745        if (newRow != NSOutlineViewDropOnItemIndex)
2746        {
2747            //find torrent to place under
2748            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2749            Torrent * topTorrent = nil;
2750            for (NSInteger i = newRow-1; i >= 0; i--)
2751            {
2752                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2753                if (![movingTorrents containsObject: tempTorrent])
2754                {
2755                    topTorrent = tempTorrent;
2756                    break;
2757                }
2758            }
2759           
2760            //remove objects to reinsert
2761            [fTorrents removeObjectsInArray: movingTorrents];
2762           
2763            //insert objects at new location
2764            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2765            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2766            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2767        }
2768       
2769        [self applyFilter: nil];
2770        [fTableView selectValues: selectedValues];
2771    }
2772   
2773    return YES;
2774}
2775
2776- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2777{
2778    [self resetInfo];
2779}
2780
2781- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2782{
2783    NSPasteboard * pasteboard = [info draggingPasteboard];
2784    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2785    {
2786        //check if any torrent files can be added
2787        BOOL torrent = NO;
2788        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2789        for (NSString * file in files)
2790        {
2791            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2792                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2793            {
2794                torrent = YES;
2795                tr_ctor * ctor = tr_ctorNew(fLib);
2796                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2797                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2798                {
2799                    if (!fOverlayWindow)
2800                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2801                    [fOverlayWindow setTorrents: files];
2802                   
2803                    return NSDragOperationCopy;
2804                }
2805                tr_ctorFree(ctor);
2806            }
2807        }
2808       
2809        //create a torrent file if a single file
2810        if (!torrent && [files count] == 1)
2811        {
2812            if (!fOverlayWindow)
2813                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2814            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2815           
2816            return NSDragOperationCopy;
2817        }
2818    }
2819    else if ([[pasteboard types] containsObject: NSURLPboardType])
2820    {
2821        if (!fOverlayWindow)
2822            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2823        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2824       
2825        return NSDragOperationCopy;
2826    }
2827    else;
2828   
2829    return NSDragOperationNone;
2830}
2831
2832- (void) draggingExited: (id <NSDraggingInfo>) info
2833{
2834    if (fOverlayWindow)
2835        [fOverlayWindow fadeOut];
2836}
2837
2838- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2839{
2840    if (fOverlayWindow)
2841        [fOverlayWindow fadeOut];
2842   
2843    NSPasteboard * pasteboard = [info draggingPasteboard];
2844    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2845    {
2846        BOOL torrent = NO, accept = YES;
2847       
2848        //create an array of files that can be opened
2849        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2850        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
2851        for (NSString * file in files)
2852        {
2853            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2854                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2855            {
2856                torrent = YES;
2857                tr_ctor * ctor = tr_ctorNew(fLib);
2858                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2859                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2860                    [filesToOpen addObject: file];
2861                tr_ctorFree(ctor);
2862            }
2863        }
2864       
2865        if ([filesToOpen count] > 0)
2866            [self application: NSApp openFiles: filesToOpen];
2867        else
2868        {
2869            if (!torrent && [files count] == 1)
2870                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2871            else
2872                accept = NO;
2873        }
2874       
2875        return accept;
2876    }
2877    else if ([[pasteboard types] containsObject: NSURLPboardType])
2878    {
2879        NSURL * url;
2880        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2881        {
2882            [self openURL: url];
2883            return YES;
2884        }
2885    }
2886    else;
2887   
2888    return NO;
2889}
2890
2891- (void) toggleSmallView: (id) sender
2892{
2893    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2894    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2895   
2896    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2897   
2898    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2899   
2900    //window min height
2901    NSSize contentMinSize = [fWindow contentMinSize],
2902            contentSize = [[fWindow contentView] frame].size;
2903    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2904                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2905    [fWindow setContentMinSize: contentMinSize];
2906   
2907    //resize for larger min height if not set to auto size
2908    if (![fDefaults boolForKey: @"AutoSize"])
2909    {
2910        if (!makeSmall && contentSize.height < contentMinSize.height)
2911        {
2912            NSRect frame = [fWindow frame];
2913            CGFloat heightChange = contentMinSize.height - contentSize.height;
2914            frame.size.height += heightChange;
2915            frame.origin.y -= heightChange;
2916           
2917            [fWindow setFrame: frame display: YES];
2918        }
2919    }
2920    else
2921        [self setWindowSizeToFit];
2922}
2923
2924- (void) togglePiecesBar: (id) sender
2925{
2926    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2927    [fTableView togglePiecesBar];
2928}
2929
2930- (void) toggleAvailabilityBar: (id) sender
2931{
2932    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2933    [fTableView display];
2934}
2935
2936- (void) toggleStatusString: (id) sender
2937{
2938    if ([fDefaults boolForKey: @"SmallView"])
2939        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2940    else
2941        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2942   
2943    [fTableView reloadData];
2944}
2945
2946- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2947{
2948    NSScrollView * scrollView = [fTableView enclosingScrollView];
2949   
2950    //convert pixels to points
2951    NSRect windowFrame = [fWindow frame];
2952    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2953    windowSize.height += height;
2954   
2955    if (check)
2956    {
2957        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2958       
2959        if (windowSize.height < minSize.height)
2960            windowSize.height = minSize.height;
2961        else
2962        {
2963            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2964            if ([fStatusBar isHidden])
2965                maxSize.height -= [fStatusBar frame].size.height;
2966            if ([fFilterBar isHidden])
2967                maxSize.height -= [fFilterBar frame].size.height;
2968            if (windowSize.height > maxSize.height)
2969                windowSize.height = maxSize.height;
2970        }
2971    }
2972
2973    //convert points to pixels
2974    windowSize = [scrollView convertSize: windowSize toView: nil];
2975
2976    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2977    windowFrame.size.height = windowSize.height;
2978    return windowFrame;
2979}
2980
2981- (void) toggleStatusBar: (id) sender
2982{
2983    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2984    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2985}
2986
2987//doesn't save shown state
2988- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2989{
2990    if (show != [fStatusBar isHidden])
2991        return;
2992
2993    if (show)
2994        [fStatusBar setHidden: NO];
2995
2996    NSRect frame;
2997    CGFloat heightChange = [fStatusBar frame].size.height;
2998    if (!show)
2999        heightChange *= -1;
3000   
3001    //allow bar to show even if not enough room
3002    if (show && ![fDefaults boolForKey: @"AutoSize"])
3003    {
3004        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3005        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3006        if (change < 0.0)
3007        {
3008            frame = [fWindow frame];
3009            frame.size.height += change;
3010            frame.origin.y -= change;
3011            [fWindow setFrame: frame display: NO animate: NO];
3012        }
3013    }
3014
3015    [self updateUI];
3016   
3017    NSScrollView * scrollView = [fTableView enclosingScrollView];
3018   
3019    //set views to not autoresize
3020    NSUInteger statsMask = [fStatusBar autoresizingMask];
3021    NSUInteger filterMask = [fFilterBar autoresizingMask];
3022    NSUInteger scrollMask = [scrollView autoresizingMask];
3023    [fStatusBar setAutoresizingMask: NSViewNotSizable];
3024    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3025    [scrollView setAutoresizingMask: NSViewNotSizable];
3026   
3027    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3028    [fWindow setFrame: frame display: YES animate: animate];
3029   
3030    //re-enable autoresize
3031    [fStatusBar setAutoresizingMask: statsMask];
3032    [fFilterBar setAutoresizingMask: filterMask];
3033    [scrollView setAutoresizingMask: scrollMask];
3034   
3035    //change min size
3036    NSSize minSize = [fWindow contentMinSize];
3037    minSize.height += heightChange;
3038    [fWindow setContentMinSize: minSize];
3039   
3040    if (!show)
3041        [fStatusBar setHidden: YES];
3042}
3043
3044- (void) toggleFilterBar: (id) sender
3045{
3046    //disable filtering when hiding
3047    if (![fFilterBar isHidden])
3048    {
3049        [fSearchFilterField setStringValue: @""];
3050        [self setFilter: fNoFilterButton];
3051        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3052    }
3053
3054    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3055    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3056}
3057
3058//doesn't save shown state
3059- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3060{
3061    if (show != [fFilterBar isHidden])
3062        return;
3063
3064    if (show)
3065        [fFilterBar setHidden: NO];
3066
3067    NSRect frame;
3068    CGFloat heightChange = [fFilterBar frame].size.height;
3069    if (!show)
3070        heightChange *= -1;
3071   
3072    //allow bar to show even if not enough room
3073    if (show && ![fDefaults boolForKey: @"AutoSize"])
3074    {
3075        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3076        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3077        if (change < 0.0)
3078        {
3079            frame = [fWindow frame];
3080            frame.size.height += change;
3081            frame.origin.y -= change;
3082            [fWindow setFrame: frame display: NO animate: NO];
3083        }
3084    }
3085   
3086    NSScrollView * scrollView = [fTableView enclosingScrollView];
3087
3088    //set views to not autoresize
3089    NSUInteger filterMask = [fFilterBar autoresizingMask];
3090    NSUInteger scrollMask = [scrollView autoresizingMask];
3091    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3092    [scrollView setAutoresizingMask: NSViewNotSizable];
3093   
3094    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3095    [fWindow setFrame: frame display: YES animate: animate];
3096   
3097    //re-enable autoresize
3098    [fFilterBar setAutoresizingMask: filterMask];
3099    [scrollView setAutoresizingMask: scrollMask];
3100   
3101    //change min size
3102    NSSize minSize = [fWindow contentMinSize];
3103    minSize.height += heightChange;
3104    [fWindow setContentMinSize: minSize];
3105   
3106    if (!show)
3107    {
3108        [fFilterBar setHidden: YES];
3109        [fWindow makeFirstResponder: fTableView];
3110    }
3111}
3112
3113- (void) focusFilterField
3114{
3115    [fWindow makeFirstResponder: fSearchFilterField];
3116    if ([fFilterBar isHidden])
3117        [self toggleFilterBar: self];
3118}
3119
3120#warning change from id to QLPreviewPanel
3121- (BOOL) acceptsPreviewPanelControl: (id) panel
3122{
3123    return !fQuitting;
3124}
3125
3126- (void) beginPreviewPanelControl: (id) panel
3127{
3128    fPreviewPanel = [panel retain];
3129    [fPreviewPanel setDelegate: self];
3130    [fPreviewPanel setDataSource: self];
3131}
3132
3133- (void) endPreviewPanelControl: (id) panel
3134{
3135    [fPreviewPanel release];
3136    fPreviewPanel = nil;
3137}
3138
3139- (NSArray *) quickLookableTorrents
3140{
3141    NSArray * selectedTorrents = [fTableView selectedTorrents];
3142    NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3143   
3144    for (Torrent * torrent in selectedTorrents)
3145        if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation])
3146            [qlArray addObject: torrent];
3147   
3148    return qlArray;
3149}
3150
3151- (NSInteger) numberOfPreviewItemsInPreviewPanel: (id) panel
3152{
3153    if ([fInfoController canQuickLook])
3154        return [[fInfoController quickLookURLs] count];
3155    else
3156        return [[self quickLookableTorrents] count];
3157}
3158
3159- (id /*<QLPreviewItem>*/) previewPanel: (id) panel previewItemAtIndex: (NSInteger) index
3160{
3161    if ([fInfoController canQuickLook])
3162        return [[fInfoController quickLookURLs] objectAtIndex: index];
3163    else
3164        return [[self quickLookableTorrents] objectAtIndex: index];
3165}
3166
3167- (BOOL) previewPanel: (id) panel handleEvent: (NSEvent *) event
3168{
3169    /*if ([event type] == NSKeyDown)
3170    {
3171        [super keyDown: event];
3172        return YES;
3173    }*/
3174   
3175    return NO;
3176}
3177
3178- (NSRect) previewPanel: (id) panel sourceFrameOnScreenForPreviewItem: (id /*<QLPreviewItem>*/) item
3179{
3180    if ([fInfoController canQuickLook])
3181        return [fInfoController quickLookSourceFrameForPreviewItem: item];
3182    else
3183    {
3184        if (![fWindow isVisible])
3185            return NSZeroRect;
3186       
3187        const NSInteger row = [fTableView rowForItem: item];
3188        if (row == -1)
3189            return NSZeroRect;
3190       
3191        NSRect frame = [fTableView iconRectForRow: row];
3192       
3193        if (!NSIntersectsRect([fTableView visibleRect], frame))
3194            return NSZeroRect;
3195       
3196        frame.origin = [fTableView convertPoint: frame.origin toView: nil];
3197        frame.origin = [fWindow convertBaseToScreen: frame.origin];
3198        frame.origin.y -= frame.size.height;
3199        return frame;
3200    }
3201}
3202
3203- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3204{
3205    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3206   
3207    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3208    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3209    [button setStringValue: @""];
3210   
3211    [item setView: button];
3212    [button release];
3213   
3214    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3215    [item setMinSize: buttonSize];
3216    [item setMaxSize: buttonSize];
3217   
3218    return [item autorelease];
3219}
3220
3221- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3222{
3223    if ([ident isEqualToString: TOOLBAR_CREATE])
3224    {
3225        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3226       
3227        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3228        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3229        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3230        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3231        [item setTarget: self];
3232        [item setAction: @selector(createFile:)];
3233        [item setAutovalidates: NO];
3234       
3235        return item;
3236    }
3237    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3238    {
3239        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3240       
3241        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3242        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3243        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3244        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3245        [item setTarget: self];
3246        [item setAction: @selector(openShowSheet:)];
3247        [item setAutovalidates: NO];
3248       
3249        return item;
3250    }
3251    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3252    {
3253        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3254       
3255        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3256        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3257        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3258        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3259        [item setTarget: self];
3260        [item setAction: @selector(openURLShowSheet:)];
3261        [item setAutovalidates: NO];
3262       
3263        return item;
3264    }
3265    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3266    {
3267        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3268       
3269        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3270        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3271        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3272        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3273        [item setTarget: self];
3274        [item setAction: @selector(removeNoDelete:)];
3275       
3276        return item;
3277    }
3278    else if ([ident isEqualToString: TOOLBAR_INFO])
3279    {
3280        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3281        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3282       
3283        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3284        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3285        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3286        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3287        [item setTarget: self];
3288        [item setAction: @selector(showInfo:)];
3289       
3290        return item;
3291    }
3292    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3293    {
3294        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3295       
3296        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3297        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3298        [groupItem setView: segmentedControl];
3299        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3300       
3301        [segmentedControl setSegmentCount: 2];
3302        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3303       
3304        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3305        [groupItem setMinSize: groupSize];
3306        [groupItem setMaxSize: groupSize];
3307       
3308        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3309        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3310        [groupItem setTarget: self];
3311        [groupItem setAction: @selector(allToolbarClicked:)];
3312       
3313        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3314       
3315        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3316        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3317        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3318                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3319       
3320        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3321        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3322        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3323                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3324       
3325        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3326                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3327       
3328        [segmentedControl release];
3329        return [groupItem autorelease];
3330    }
3331    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3332    {
3333        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3334       
3335        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3336        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3337        [groupItem setView: segmentedControl];
3338        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3339       
3340        [segmentedControl setSegmentCount: 2];
3341        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3342       
3343        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3344        [groupItem setMinSize: groupSize];
3345        [groupItem setMaxSize: groupSize];
3346       
3347        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3348        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3349        [groupItem setTarget: self];
3350        [groupItem setAction: @selector(selectedToolbarClicked:)];
3351       
3352        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3353       
3354        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3355        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3356        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3357                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3358       
3359        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3360        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3361        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3362                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3363       
3364        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3365                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3366       
3367        [segmentedControl release];
3368        return [groupItem autorelease];
3369    }
3370    else if ([ident isEqualToString: TOOLBAR_FILTER])
3371    {
3372        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3373        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3374       
3375        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3376        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3377        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3378        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3379        [item setTarget: self];
3380        [item setAction: @selector(toggleFilterBar:)];
3381       
3382        return item;
3383    }
3384    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3385    {
3386        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3387        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3388       
3389        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3390        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3391        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3392        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3393        [item setTarget: self];
3394        [item setAction: @selector(toggleQuickLook:)];
3395       
3396        return item;
3397    }
3398    else
3399        return nil;
3400}
3401
3402- (void) allToolbarClicked: (id) sender
3403{
3404    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3405                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3406    switch (tagValue)
3407    {
3408        case TOOLBAR_PAUSE_TAG:
3409            [self stopAllTorrents: sender];
3410            break;
3411        case TOOLBAR_RESUME_TAG:
3412            [self resumeAllTorrents: sender];
3413            break;
3414    }
3415}
3416
3417- (void) selectedToolbarClicked: (id) sender
3418{
3419    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3420                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3421    switch (tagValue)
3422    {
3423        case TOOLBAR_PAUSE_TAG:
3424            [self stopSelectedTorrents: sender];
3425            break;
3426        case TOOLBAR_RESUME_TAG:
3427            [self resumeSelectedTorrents: sender];
3428            break;
3429    }
3430}
3431
3432- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3433{
3434    return [NSArray arrayWithObjects:
3435            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3436            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3437            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3438            NSToolbarSeparatorItemIdentifier,
3439            NSToolbarSpaceItemIdentifier,
3440            NSToolbarFlexibleSpaceItemIdentifier,
3441            NSToolbarCustomizeToolbarItemIdentifier, nil];
3442}
3443
3444- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3445{
3446    return [NSArray arrayWithObjects:
3447            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSeparatorItemIdentifier,
3448            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3449            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3450}
3451
3452- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3453{
3454    NSString * ident = [toolbarItem itemIdentifier];
3455   
3456    //enable remove item
3457    if ([ident isEqualToString: TOOLBAR_REMOVE])
3458        return [fTableView numberOfSelectedRows] > 0;
3459
3460    //enable pause all item
3461    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3462    {
3463        for (Torrent * torrent in fTorrents)
3464            if ([torrent isActive] || [torrent waitingToStart])
3465                return YES;
3466        return NO;
3467    }
3468
3469    //enable resume all item
3470    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3471    {
3472        for (Torrent * torrent in fTorrents)
3473            if (![torrent isActive] && ![torrent waitingToStart])
3474                return YES;
3475        return NO;
3476    }
3477
3478    //enable pause item
3479    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3480    {
3481        for (Torrent * torrent in [fTableView selectedTorrents])
3482            if ([torrent isActive] || [torrent waitingToStart])
3483                return YES;
3484        return NO;
3485    }
3486   
3487    //enable resume item
3488    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3489    {
3490        for (Torrent * torrent in [fTableView selectedTorrents])
3491            if (![torrent isActive] && ![torrent waitingToStart])
3492                return YES;
3493        return NO;
3494    }
3495   
3496    //set info image
3497    if ([ident isEqualToString: TOOLBAR_INFO])
3498    {
3499        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3500        return YES;
3501    }
3502   
3503    //set filter image
3504    if ([ident isEqualToString: TOOLBAR_FILTER])
3505    {
3506        [(NSButton *)[toolbarItem view] setState: ![fFilterBar isHidden]];
3507        return YES;
3508    }
3509   
3510    //set quick look image
3511    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3512    {
3513        [(NSButton *)[toolbarItem view] setState: [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
3514                                                    && [[QLPreviewPanelSL sharedPreviewPanel] isVisible]];
3515        return [NSApp isOnSnowLeopardOrBetter];
3516    }
3517
3518    return YES;
3519}
3520
3521- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3522{
3523    SEL action = [menuItem action];
3524   
3525    if (action == @selector(toggleSpeedLimit:))
3526    {
3527        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3528        return YES;
3529    }
3530   
3531    //only enable some items if it is in a context menu or the window is useable
3532    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3533
3534    //enable open items
3535    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3536        return [fWindow attachedSheet] == nil;
3537   
3538    //enable sort options
3539    if (action == @selector(setSort:))
3540    {
3541        NSString * sortType;
3542        switch ([menuItem tag])
3543        {
3544            case SORT_ORDER_TAG:
3545                sortType = SORT_ORDER;
3546                break;
3547            case SORT_DATE_TAG:
3548                sortType = SORT_DATE;
3549                break;
3550            case SORT_NAME_TAG:
3551                sortType = SORT_NAME;
3552                break;
3553            case SORT_PROGRESS_TAG:
3554                sortType = SORT_PROGRESS;
3555                break;
3556            case SORT_STATE_TAG:
3557                sortType = SORT_STATE;
3558                break;
3559            case SORT_TRACKER_TAG:
3560                sortType = SORT_TRACKER;
3561                break;
3562            case SORT_ACTIVITY_TAG:
3563                sortType = SORT_ACTIVITY;
3564                break;
3565            default:
3566                NSAssert1(NO, @"Unknown sort tag received: %d", [menuItem tag]);
3567        }
3568       
3569        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3570        return [fWindow isVisible];
3571    }
3572   
3573    //enable sort options
3574    if (action == @selector(setStatusLabel:))
3575    {
3576        NSString * statusLabel;
3577        switch ([menuItem tag])
3578        {
3579            case STATUS_RATIO_TOTAL_TAG:
3580                statusLabel = STATUS_RATIO_TOTAL;
3581                break;
3582            case STATUS_RATIO_SESSION_TAG:
3583                statusLabel = STATUS_RATIO_SESSION;
3584                break;
3585            case STATUS_TRANSFER_TOTAL_TAG:
3586                statusLabel = STATUS_TRANSFER_TOTAL;
3587                break;
3588            case STATUS_TRANSFER_SESSION_TAG:
3589                statusLabel = STATUS_TRANSFER_SESSION;
3590                break;
3591            default:
3592                NSAssert1(NO, @"Unknown status label tag received: %d", [menuItem tag]);
3593        }
3594       
3595        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3596        return YES;
3597    }
3598   
3599    if (action == @selector(setGroup:))
3600    {
3601        BOOL checked = NO;
3602       
3603        NSInteger index = [menuItem tag];
3604        for (Torrent * torrent in [fTableView selectedTorrents])
3605            if (index == [torrent groupValue])
3606            {
3607                checked = YES;
3608                break;
3609            }
3610       
3611        [menuItem setState: checked ? NSOnState : NSOffState];
3612        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3613    }
3614   
3615    if (action == @selector(setGroupFilter:))
3616    {
3617        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3618        return YES;
3619    }
3620   
3621    if (action == @selector(toggleSmallView:))
3622    {
3623        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3624        return [fWindow isVisible];
3625    }
3626   
3627    if (action == @selector(togglePiecesBar:))
3628    {
3629        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3630        return [fWindow isVisible];
3631    }
3632   
3633    if (action == @selector(toggleStatusString:))
3634    {
3635        if ([fDefaults boolForKey: @"SmallView"])
3636        {
3637            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3638            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3639        }
3640        else
3641        {
3642            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3643            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3644        }
3645       
3646        return [fWindow isVisible];
3647    }
3648   
3649    if (action == @selector(toggleAvailabilityBar:))
3650    {
3651        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3652        return [fWindow isVisible];
3653    }
3654   
3655    if (action == @selector(setLimitGlobalEnabled:))
3656    {
3657        BOOL upload = [menuItem menu] == fUploadMenu;
3658        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3659        if (limit)
3660            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3661                                    "Action menu -> upload/download limit"),
3662                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3663       
3664        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3665        return YES;
3666    }
3667   
3668    if (action == @selector(setRatioGlobalEnabled:))
3669    {
3670        BOOL check = menuItem == fCheckRatioItem;
3671        if (check)
3672            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3673                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3674       
3675        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3676        return YES;
3677    }
3678
3679    //enable show info
3680    if (action == @selector(showInfo:))
3681    {
3682        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3683                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3684        [menuItem setTitle: title];
3685
3686        return YES;
3687    }
3688   
3689    //enable prev/next inspector tab
3690    if (action == @selector(setInfoTab:))
3691        return [[fInfoController window] isVisible];
3692   
3693    //enable toggle status bar
3694    if (action == @selector(toggleStatusBar:))
3695    {
3696        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3697                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3698        [menuItem setTitle: title];
3699
3700        return [fWindow isVisible];
3701    }
3702   
3703    //enable toggle filter bar
3704    if (action == @selector(toggleFilterBar:))
3705    {
3706        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3707                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3708        [menuItem setTitle: title];
3709
3710        return [fWindow isVisible];
3711    }
3712   
3713    //enable prev/next filter button
3714    if (action == @selector(switchFilter:))
3715        return [fWindow isVisible] && ![fFilterBar isHidden];
3716   
3717    //enable reveal in finder
3718    if (action == @selector(revealFile:))
3719        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3720
3721    //enable remove items
3722    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
3723    {
3724        BOOL warning = NO;
3725       
3726        for (Torrent * torrent in [fTableView selectedTorrents])
3727        {
3728            if ([torrent isActive])
3729            {
3730                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
3731                {
3732                    warning = YES;
3733                    break;
3734                }
3735            }
3736        }
3737   
3738        //append or remove ellipsis when needed
3739        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3740        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3741        {
3742            if (![title hasSuffix: ellipsis])
3743                [menuItem setTitle: [title stringByAppendingEllipsis]];
3744        }
3745        else
3746        {
3747            if ([title hasSuffix: ellipsis])
3748                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3749        }
3750       
3751        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3752    }
3753
3754    //enable pause all item
3755    if (action == @selector(stopAllTorrents:))
3756    {
3757        for (Torrent * torrent in fTorrents)
3758            if ([torrent isActive] || [torrent waitingToStart])
3759                return YES;
3760        return NO;
3761    }
3762   
3763    //enable resume all item
3764    if (action == @selector(resumeAllTorrents:))
3765    {
3766        for (Torrent * torrent in fTorrents)
3767            if (![torrent isActive] && ![torrent waitingToStart])
3768                return YES;
3769        return NO;
3770    }
3771   
3772    //enable resume all waiting item
3773    if (action == @selector(resumeWaitingTorrents:))
3774    {
3775        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3776            return NO;
3777   
3778        for (Torrent * torrent in fTorrents)
3779            if (![torrent isActive] && [torrent waitingToStart])
3780                return YES;
3781        return NO;
3782    }
3783   
3784    //enable resume selected waiting item
3785    if (action == @selector(resumeSelectedTorrentsNoWait:))
3786    {
3787        if (!canUseTable)
3788            return NO;
3789       
3790        for (Torrent * torrent in [fTableView selectedTorrents])
3791            if (![torrent isActive])
3792                return YES;
3793        return NO;
3794    }
3795
3796    //enable pause item
3797    if (action == @selector(stopSelectedTorrents:))
3798    {
3799        if (!canUseTable)
3800            return NO;
3801   
3802        for (Torrent * torrent in [fTableView selectedTorrents])
3803            if ([torrent isActive] || [torrent waitingToStart])
3804                return YES;
3805        return NO;
3806    }
3807   
3808    //enable resume item
3809    if (action == @selector(resumeSelectedTorrents:))
3810    {
3811        if (!canUseTable)
3812            return NO;
3813   
3814        for (Torrent * torrent in [fTableView selectedTorrents])
3815            if (![torrent isActive] && ![torrent waitingToStart])
3816                return YES;
3817        return NO;
3818    }
3819   
3820    //enable manual announce item
3821    if (action == @selector(announceSelectedTorrents:))
3822    {
3823        if (!canUseTable)
3824            return NO;
3825       
3826        for (Torrent * torrent in [fTableView selectedTorrents])
3827            if ([torrent canManualAnnounce])
3828                return YES;
3829        return NO;
3830    }
3831   
3832    //enable reset cache item
3833    if (action == @selector(verifySelectedTorrents:))
3834        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3835   
3836    //enable move torrent file item
3837    if (action == @selector(moveDataFilesSelected:))
3838        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3839   
3840    //enable copy torrent file item
3841    if (action == @selector(copyTorrentFiles:))
3842        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3843   
3844    //enable reverse sort item
3845    if (action == @selector(setSortReverse:))
3846    {
3847        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3848        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3849    }
3850   
3851    //enable group sort item
3852    if (action == @selector(setSortByGroup:))
3853    {
3854        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3855        return YES;
3856    }
3857   
3858    //check proper filter search item
3859    if (action == @selector(setFilterSearchType:))
3860    {
3861        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3862       
3863        BOOL state;
3864        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3865            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3866        else
3867            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3868       
3869        [menuItem setState: state ? NSOnState : NSOffState];
3870        return YES;
3871    }
3872   
3873    if (action == @selector(toggleQuickLook:))
3874    {
3875        const BOOL visible = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
3876                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
3877        //text consistent with Finder
3878        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
3879                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
3880        [menuItem setTitle: title];
3881       
3882        return [NSApp isOnSnowLeopardOrBetter];
3883    }
3884   
3885    return YES;
3886}
3887
3888- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3889{
3890    switch (messageType)
3891    {
3892        case kIOMessageSystemWillSleep:
3893            //if there are any running transfers, wait 15 seconds for them to stop
3894            for (Torrent * torrent in fTorrents)
3895                if ([torrent isActive])
3896                {
3897                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3898                    for (Torrent * torrent in fTorrents)
3899                        [torrent sleep];
3900                    sleep(15);
3901                    break;
3902                }
3903
3904            IOAllowPowerChange(fRootPort, (long) messageArgument);
3905            break;
3906
3907        case kIOMessageCanSystemSleep:
3908            if ([fDefaults boolForKey: @"SleepPrevent"])
3909            {
3910                //prevent idle sleep unless no torrents are active
3911                for (Torrent * torrent in fTorrents)
3912                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3913                    {
3914                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3915                        return;
3916                    }
3917            }
3918           
3919            IOAllowPowerChange(fRootPort, (long) messageArgument);
3920            break;
3921
3922        case kIOMessageSystemHasPoweredOn:
3923            //resume sleeping transfers after we wake up
3924            for (Torrent * torrent in fTorrents)
3925                [torrent wakeUp];
3926            #warning check speed limit timer?
3927            //[self autoSpeedLimitChange: nil];
3928            break;
3929    }
3930}
3931
3932- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3933{
3934    NSInteger seeding = 0, downloading = 0;
3935    for (Torrent * torrent in fTorrents)
3936    {
3937        if ([torrent isSeeding])
3938            seeding++;
3939        else if ([torrent isActive])
3940            downloading++;
3941        else;
3942    }
3943   
3944    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3945            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3946   
3947    BOOL hasSeparator = seedingItem || downloadingItem;
3948   
3949    if (seeding > 0)
3950    {
3951        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3952        if (!seedingItem)
3953        {
3954            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3955            [seedingItem setTag: DOCK_SEEDING_TAG];
3956            [fDockMenu insertItem: seedingItem atIndex: 0];
3957        }
3958        else
3959            [seedingItem setTitle: title];
3960    }
3961    else
3962    {
3963        if (seedingItem)
3964            [fDockMenu removeItem: seedingItem];
3965    }
3966   
3967    if (downloading > 0)
3968    {
3969        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3970        if (!downloadingItem)
3971        {
3972            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3973            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3974            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3975        }
3976        else
3977            [downloadingItem setTitle: title];
3978    }
3979    else
3980    {
3981        if (downloadingItem)
3982            [fDockMenu removeItem: downloadingItem];
3983    }
3984   
3985    if (seeding > 0 || downloading > 0)
3986    {
3987        if (!hasSeparator)
3988            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: (seeding > 0 && downloading > 0) ? 2 : 1];
3989    }
3990    else
3991    {
3992        if (hasSeparator)
3993            [fDockMenu removeItemAtIndex: 0];
3994    }
3995   
3996    return fDockMenu;
3997}
3998
3999- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
4000{
4001    //if auto size is enabled, the current frame shouldn't need to change
4002    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
4003   
4004    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
4005    return frame;
4006}
4007
4008- (void) setWindowSizeToFit
4009{
4010    if ([fDefaults boolForKey: @"AutoSize"])
4011    {
4012        NSScrollView * scrollView = [fTableView enclosingScrollView];
4013       
4014        [scrollView setHasVerticalScroller: NO];
4015        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
4016        [scrollView setHasVerticalScroller: YES];
4017       
4018        //hack to ensure scrollbars don't disappear after resizing
4019        [scrollView setAutohidesScrollers: NO];
4020        [scrollView setAutohidesScrollers: YES];
4021    }
4022}
4023
4024- (NSRect) sizedWindowFrame
4025{
4026    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
4027                    ? [fDisplayedTorrents count] : 0;
4028   
4029    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4030                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4031                        - [[fTableView enclosingScrollView] frame].size.height;
4032   
4033    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4034}
4035
4036- (void) updateForExpandCollape
4037{
4038    [self setWindowSizeToFit];
4039    [self setBottomCountText: YES];
4040}
4041
4042- (void) showMainWindow: (id) sender
4043{
4044    [fWindow makeKeyAndOrderFront: nil];
4045}
4046
4047- (void) windowDidBecomeMain: (NSNotification *) notification
4048{
4049    [fBadger clearCompleted];
4050    [self updateUI];
4051}
4052
4053- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
4054{
4055    //only resize horizontally if autosize is enabled
4056    if ([fDefaults boolForKey: @"AutoSize"])
4057        proposedFrameSize.height = [fWindow frame].size.height;
4058    return proposedFrameSize;
4059}
4060
4061- (void) windowDidResize: (NSNotification *) notification
4062{
4063    if (![fStatusBar isHidden])
4064        [self resizeStatusButton];
4065   
4066    if ([fFilterBar isHidden])
4067        return;
4068   
4069    //replace all buttons
4070    [fNoFilterButton sizeToFit];
4071    [fActiveFilterButton sizeToFit];
4072    [fDownloadFilterButton sizeToFit];
4073    [fSeedFilterButton sizeToFit];
4074    [fPauseFilterButton sizeToFit];
4075   
4076    NSRect allRect = [fNoFilterButton frame];
4077    NSRect activeRect = [fActiveFilterButton frame];
4078    NSRect downloadRect = [fDownloadFilterButton frame];
4079    NSRect seedRect = [fSeedFilterButton frame];
4080    NSRect pauseRect = [fPauseFilterButton frame];
4081   
4082    //size search filter to not overlap buttons
4083    NSRect searchFrame = [fSearchFilterField frame];
4084    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
4085    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
4086   
4087    //make sure it is not too long
4088    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
4089    {
4090        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
4091        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
4092    }
4093    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
4094    {
4095        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
4096        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
4097       
4098        //calculate width the buttons can take up
4099        const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x;
4100        const CGFloat currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect)
4101                                        + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons
4102        const CGFloat ratio = allowedWidth / currentWidth;
4103       
4104        //decrease button widths proportionally
4105        allRect.size.width  = NSWidth(allRect) * ratio;
4106        activeRect.size.width = NSWidth(activeRect) * ratio;
4107        downloadRect.size.width = NSWidth(downloadRect) * ratio;
4108        seedRect.size.width = NSWidth(seedRect) * ratio;
4109        pauseRect.size.width = NSWidth(pauseRect) * ratio;
4110    }
4111    else;
4112   
4113    activeRect.origin.x = NSMaxX(allRect) + 1.0;
4114    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
4115    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4116    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4117   
4118    [fNoFilterButton setFrame: allRect];
4119    [fActiveFilterButton setFrame: activeRect];
4120    [fDownloadFilterButton setFrame: downloadRect];
4121    [fSeedFilterButton setFrame: seedRect];
4122    [fPauseFilterButton setFrame: pauseRect];
4123   
4124    [fSearchFilterField setFrame: searchFrame];
4125}
4126
4127- (void) applicationWillUnhide: (NSNotification *) notification
4128{
4129    [self updateUI];
4130}
4131
4132- (void) toggleQuickLook: (id) sender
4133{
4134    if (![NSApp isOnSnowLeopardOrBetter])
4135        return;
4136   
4137    if ([[QLPreviewPanelSL sharedPreviewPanel] isVisible])
4138        [[QLPreviewPanelSL sharedPreviewPanel] orderOut: nil];
4139    else
4140        [[QLPreviewPanelSL sharedPreviewPanel] makeKeyAndOrderFront: nil];
4141}
4142
4143- (void) linkHomepage: (id) sender
4144{
4145    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4146}
4147
4148- (void) linkForums: (id) sender
4149{
4150    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4151}
4152
4153- (void) linkTrac: (id) sender
4154{
4155    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4156}
4157
4158- (void) linkDonate: (id) sender
4159{
4160    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4161}
4162
4163- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4164{
4165    fUpdateInProgress = YES;
4166}
4167
4168- (NSDictionary *) registrationDictionaryForGrowl
4169{
4170    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4171                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4172    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4173                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4174}
4175
4176- (void) growlNotificationWasClicked: (id) clickContext
4177{
4178    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4179        return;
4180   
4181    NSString * type = [clickContext objectForKey: @"Type"], * location;
4182    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4183            && (location = [clickContext objectForKey: @"Location"]))
4184    {
4185        if ([NSApp isOnSnowLeopardOrBetter])
4186        {
4187            NSURL * file = [NSURL fileURLWithPath: location];
4188            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4189        }
4190        else
4191            [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4192    }
4193}
4194
4195- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4196{
4197    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4198   
4199    //get the torrent
4200    Torrent * torrent = nil;
4201    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4202    {
4203        for (torrent in fTorrents)
4204            if (torrentStruct == [torrent torrentStruct])
4205            {
4206                [torrent retain];
4207                break;
4208            }
4209       
4210        if (!torrent)
4211        {
4212            [pool drain];
4213           
4214            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4215            return;
4216        }
4217    }
4218   
4219    switch (type)
4220    {
4221        case TR_RPC_TORRENT_ADDED:
4222            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4223                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4224            break;
4225       
4226        case TR_RPC_TORRENT_STARTED:
4227        case TR_RPC_TORRENT_STOPPED:
4228            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4229            break;
4230       
4231        case TR_RPC_TORRENT_REMOVING:
4232            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4233            break;
4234       
4235        case TR_RPC_TORRENT_CHANGED:
4236            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4237            break;
4238       
4239        case TR_RPC_TORRENT_MOVED:
4240            [self performSelectorOnMainThread: @selector(rpcMovedTorrent:) withObject: torrent waitUntilDone: NO];
4241            break;
4242       
4243        case TR_RPC_SESSION_CHANGED:
4244            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4245            break;
4246       
4247        default:
4248            NSAssert1(NO, @"Unknown RPC command received: %d", type);
4249            [torrent release];
4250    }
4251   
4252    [pool drain];
4253}
4254
4255- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4256{
4257    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4258    [torrentStructPtr release];
4259   
4260    NSString * location = nil;
4261    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4262        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4263   
4264    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4265   
4266    [torrent update];
4267    [fTorrents addObject: torrent];
4268    [torrent release];
4269   
4270    [self updateTorrentsInQueue];
4271}
4272
4273- (void) rpcRemoveTorrent: (Torrent *) torrent
4274{
4275    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4276    [torrent release];
4277}
4278
4279- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4280{
4281    [torrent update];
4282    [torrent release];
4283   
4284    [self updateUI];
4285    [self applyFilter: nil];
4286    [self updateTorrentHistory];
4287}
4288
4289- (void) rpcChangedTorrent: (Torrent *) torrent
4290{
4291    [torrent update];
4292   
4293    if ([[fTableView selectedTorrents] containsObject: torrent])
4294    {
4295        [fInfoController updateInfoStats]; //this will reload the file table
4296        [fInfoController updateOptions];
4297    }
4298   
4299    [torrent release];
4300}
4301
4302- (void) rpcMovedTorrent: (Torrent *) torrent
4303{
4304    [torrent update];
4305    [torrent updateTimeMachineExclude];
4306   
4307    if ([[fTableView selectedTorrents] containsObject: torrent])
4308        [fInfoController updateInfoStats];
4309   
4310    [torrent release];
4311}
4312
4313@end
Note: See TracBrowser for help on using the repository browser.