source: trunk/macosx/Controller.m @ 9257

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

on 10.6 simplify the check for already-running Transmission instances

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