source: trunk/macosx/Controller.m @ 9171

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

fix mac build - tracker info tab info is not fully available for now

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