source: trunk/macosx/Controller.m @ 11688

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

#3686 "add rpc command to cleanly shutdown daemon" - added for Mac client

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