source: trunk/macosx/Controller.m @ 11400

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

didn't mean to do that

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