source: trunk/macosx/Controller.m @ 9348

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

update the time machine exclude list when the file is moved through rpc

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