source: trunk/macosx/Controller.m @ 9034

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

draft #1 of #2369 - use public API for QuickLook? on 10.6 (and drop the hack for 10.5-support)

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