source: trunk/macosx/Controller.m @ 11872

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

fix a crash with the URL window, and memory leak with the URL window, and update the "Open" button of the URL window when shown

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