source: trunk/macosx/Controller.m @ 9744

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

on open, make sure the filter bar's layout is correct

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