source: trunk/macosx/Controller.m @ 9309

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

#2503 When sorting by state, separate queued transfers from paused transfers

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