source: trunk/macosx/Controller.m @ 9292

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

#2488 when sorting by tracker, first use the tracker that comes first alphabetically

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