source: trunk/macosx/Controller.m @ 9812

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

small code nudges here and there

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