source: trunk/macosx/Controller.m @ 11884

Last change on this file since 11884 was 11884, checked in by livings124, 11 years ago

Add option to remove completed transfers

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