source: trunk/macosx/Controller.m @ 9648

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

cap the message log count in the Mac UI

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