source: trunk/macosx/Controller.m @ 9285

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

applicationShouldHandleReopen:hasVisibleWindows: hardcoded a check for the main window and prefs window; now check for a visible main window

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