source: trunk/macosx/Controller.m @ 11849

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

set the visibility priority for high and low priority menu items

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