source: trunk/macosx/Controller.m @ 9016

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

#2370 On 10.6, revaling files in Finder will select multiple files in the same directory

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