source: trunk/macosx/Controller.m @ 9667

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

#2625 Add a menu item to copy a magnet link to the clipboard

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