source: trunk/macosx/Controller.m @ 9617

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

#2624 Message Log's level filter should act as an actual filter, and all messages should be stored

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