source: trunk/macosx/Controller.m @ 11420

Last change on this file since 11420 was 11420, checked in by livings124, 12 years ago

#3743 properly set the blocklist URL on launch

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