source: trunk/macosx/Controller.m @ 9996

Last change on this file since 9996 was 9996, checked in by livings124, 12 years ago

#2787 allow dragging of URLs onto the dock icon once again

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