source: trunk/macosx/Controller.m @ 11868

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

remember the text in the URL sheet

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