source: trunk/macosx/Controller.m @ 11867

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

move the "open torrent URL" sheet into its own xib file

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