source: trunk/macosx/Controller.m @ 9577

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

some more tweaks for magnet links

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