source: trunk/macosx/Controller.m @ 9433

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

trivial cleanup and update strings file

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