source: trunk/macosx/Controller.m @ 9587

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

register to automatically accept when a user clicks a magnet link

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