source: trunk/macosx/Controller.m @ 8969

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

a little cleanup

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