source: trunk/macosx/Controller.m @ 11617

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

update the copyright years in the Mac code to 2011

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