source: trunk/macosx/Controller.m @ 9721

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

better handling of revealing the main window when the dock is clicked

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