source: trunk/macosx/Controller.m @ 9763

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

possible fix for #2586

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