source: trunk/macosx/Controller.m @ 11607

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

use autorelease pools when handling downloading/seeding state changes

  • Property svn:keywords set to Date Rev Author Id
File size: 166.5 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 11607 2010-12-30 12:33:37Z livings124 $
3 *
4 * Copyright (c) 2005-2010 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import <IOKit/IOMessage.h>
26#import <IOKit/pwr_mgt/IOPMLib.h>
27#import <Carbon/Carbon.h>
28
29#import "Controller.h"
30#import "Torrent.h"
31#import "TorrentGroup.h"
32#import "TorrentTableView.h"
33#import "CreatorWindowController.h"
34#import "StatsWindowController.h"
35#import "InfoWindowController.h"
36#import "PrefsController.h"
37#import "GroupsController.h"
38#import "AboutWindowController.h"
39#import "AddWindowController.h"
40#import "AddMagnetWindowController.h"
41#import "MessageWindowController.h"
42#import "ButtonToolbarItem.h"
43#import "GroupToolbarItem.h"
44#import "ToolbarSegmentedCell.h"
45#import "BlocklistDownloader.h"
46#import "StatusBarView.h"
47#import "FilterButton.h"
48#import "BonjourController.h"
49#import "Badger.h"
50#import "DragOverlayWindow.h"
51#import "NSApplicationAdditions.h"
52#import "NSStringAdditions.h"
53#import "ExpandedPathToPathTransformer.h"
54#import "ExpandedPathToIconTransformer.h"
55
56#import "transmission.h"
57#import "bencode.h"
58#import "utils.h"
59
60#import "UKKQueue.h"
61#import <Sparkle/Sparkle.h>
62
63#define TOOLBAR_CREATE                  @"Toolbar Create"
64#define TOOLBAR_OPEN_FILE               @"Toolbar Open"
65#define TOOLBAR_OPEN_WEB                @"Toolbar Open Web"
66#define TOOLBAR_REMOVE                  @"Toolbar Remove"
67#define TOOLBAR_INFO                    @"Toolbar Info"
68#define TOOLBAR_PAUSE_ALL               @"Toolbar Pause All"
69#define TOOLBAR_RESUME_ALL              @"Toolbar Resume All"
70#define TOOLBAR_PAUSE_RESUME_ALL        @"Toolbar Pause / Resume All"
71#define TOOLBAR_PAUSE_SELECTED          @"Toolbar Pause Selected"
72#define TOOLBAR_RESUME_SELECTED         @"Toolbar Resume Selected"
73#define TOOLBAR_PAUSE_RESUME_SELECTED   @"Toolbar Pause / Resume Selected"
74#define TOOLBAR_FILTER                  @"Toolbar Toggle Filter"
75#define TOOLBAR_QUICKLOOK               @"Toolbar QuickLook"
76
77typedef enum
78{
79    TOOLBAR_PAUSE_TAG = 0,
80    TOOLBAR_RESUME_TAG = 1
81} toolbarGroupTag;
82
83#define SORT_DATE       @"Date"
84#define SORT_NAME       @"Name"
85#define SORT_STATE      @"State"
86#define SORT_PROGRESS   @"Progress"
87#define SORT_TRACKER    @"Tracker"
88#define SORT_ORDER      @"Order"
89#define SORT_ACTIVITY   @"Activity"
90
91typedef enum
92{
93    SORT_ORDER_TAG = 0,
94    SORT_DATE_TAG = 1,
95    SORT_NAME_TAG = 2,
96    SORT_PROGRESS_TAG = 3,
97    SORT_STATE_TAG = 4,
98    SORT_TRACKER_TAG = 5,
99    SORT_ACTIVITY_TAG = 6
100} sortTag;
101
102#define FILTER_NONE     @"None"
103#define FILTER_ACTIVE   @"Active"
104#define FILTER_DOWNLOAD @"Download"
105#define FILTER_SEED     @"Seed"
106#define FILTER_PAUSE    @"Pause"
107
108#define FILTER_TYPE_NAME    @"Name"
109#define FILTER_TYPE_TRACKER @"Tracker"
110
111#define FILTER_TYPE_TAG_NAME    401
112#define FILTER_TYPE_TAG_TRACKER 402
113
114#define GROUP_FILTER_ALL_TAG    -2
115
116#define STATUS_RATIO_TOTAL      @"RatioTotal"
117#define STATUS_RATIO_SESSION    @"RatioSession"
118#define STATUS_TRANSFER_TOTAL   @"TransferTotal"
119#define STATUS_TRANSFER_SESSION @"TransferSession"
120
121typedef enum
122{
123    STATUS_RATIO_TOTAL_TAG = 0,
124    STATUS_RATIO_SESSION_TAG = 1,
125    STATUS_TRANSFER_TOTAL_TAG = 2,
126    STATUS_TRANSFER_SESSION_TAG = 3
127} statusTag;
128
129#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
130#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
131#define GROWL_AUTO_ADD          @"Torrent Auto Added"
132#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
133
134#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
135
136#define ROW_HEIGHT_REGULAR      62.0
137#define ROW_HEIGHT_SMALL        22.0
138#define WINDOW_REGULAR_WIDTH    468.0
139
140#define SEARCH_FILTER_MIN_WIDTH 48.0
141#define SEARCH_FILTER_MAX_WIDTH 95.0
142
143#define UPDATE_UI_SECONDS   1.0
144
145#define DOCK_SEEDING_TAG        101
146#define DOCK_DOWNLOADING_TAG    102
147
148#define TRANSFER_PLIST  @"/Library/Application Support/Transmission/Transfers.plist"
149
150#define WEBSITE_URL @"http://www.transmissionbt.com/"
151#define FORUM_URL   @"http://forum.transmissionbt.com/"
152#define TRAC_URL    @"http://trac.transmissionbt.com/"
153#define DONATE_URL  @"http://www.transmissionbt.com/donate.php"
154
155#define DONATE_NAG_TIME (60 * 60 * 24 * 7)
156
157static void altSpeedToggledCallback(tr_session * handle UNUSED, tr_bool active, tr_bool byUser, void * controller)
158{
159    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: [[NSNumber alloc] initWithBool: active], @"Active",
160                                [[NSNumber alloc] initWithBool: byUser], @"ByUser", nil];
161    [(Controller *)controller performSelectorOnMainThread: @selector(altSpeedToggledCallbackIsLimited:)
162        withObject: dict waitUntilDone: NO];
163}
164
165static tr_rpc_callback_status rpcCallback(tr_session * handle UNUSED, tr_rpc_callback_type type, struct tr_torrent * torrentStruct,
166                                            void * controller)
167{
168    [(Controller *)controller rpcCallback: type forTorrentStruct: torrentStruct];
169    return TR_RPC_NOREMOVE; //we'll do the remove manually
170}
171
172static void sleepCallback(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
173{
174    [(Controller *)controller sleepCallback: messageType argument: messageArgument];
175}
176
177@implementation Controller
178
179+ (void) initialize
180{
181    //make sure another Transmission.app isn't running already
182    BOOL othersRunning = NO;
183   
184    if ([NSApp isOnSnowLeopardOrBetter])
185    {
186        NSArray * apps = [NSRunningApplicationSL runningApplicationsWithBundleIdentifier: [[NSBundle mainBundle] bundleIdentifier]];
187        othersRunning = [apps count] > 1;
188    }
189    else
190    {
191        NSString * bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
192        const int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
193
194        for (NSDictionary * dic in [[NSWorkspace sharedWorkspace] launchedApplications])
195        {
196            if ([[dic objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]
197                    && [[dic objectForKey: @"NSApplicationProcessIdentifier"] intValue] != processIdentifier)
198                othersRunning = YES;
199        }
200    }
201   
202    if (othersRunning)
203    {
204        NSAlert * alert = [[NSAlert alloc] init];
205        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Transmission already running alert -> button")];
206        [alert setMessageText: NSLocalizedString(@"Transmission is already running.",
207                                                "Transmission already running alert -> title")];
208        [alert setInformativeText: NSLocalizedString(@"There is already a copy of Transmission running. "
209            "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message")];
210        [alert setAlertStyle: NSCriticalAlertStyle];
211       
212        [alert runModal];
213        [alert release];
214       
215        //kill ourselves right away
216        exit(0);
217    }
218   
219    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
220        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
221   
222    //set custom value transformers
223    ExpandedPathToPathTransformer * pathTransformer = [[[ExpandedPathToPathTransformer alloc] init] autorelease];
224    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
225   
226    ExpandedPathToIconTransformer * iconTransformer = [[[ExpandedPathToIconTransformer alloc] init] autorelease];
227    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
228   
229    //cover our asses
230    if ([[NSUserDefaults standardUserDefaults] boolForKey: @"WarningLegal"])
231    {
232        NSAlert * alert = [[NSAlert alloc] init];
233        [alert addButtonWithTitle: NSLocalizedString(@"I Accept", "Legal alert -> button")];
234        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Legal alert -> button")];
235        [alert setMessageText: NSLocalizedString(@"Welcome to Transmission", "Legal alert -> title")];
236        [alert setInformativeText: NSLocalizedString(@"Transmission is a file-sharing program."
237            " When you run a torrent, its data will be made available to others by means of upload."
238            " You and you alone are fully responsible for exercising proper judgement and abiding by your local laws.",
239            "Legal alert -> message")];
240        [alert setAlertStyle: NSInformationalAlertStyle];
241       
242        if ([alert runModal] == NSAlertSecondButtonReturn)
243            exit(0);
244        [alert release];
245       
246        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningLegal"];
247    }
248}
249
250- (id) init
251{
252    if ((self = [super init]))
253    {
254        fDefaults = [NSUserDefaults standardUserDefaults];
255       
256        //checks for old version speeds of -1
257        if ([fDefaults integerForKey: @"UploadLimit"] < 0)
258        {
259            [fDefaults removeObjectForKey: @"UploadLimit"];
260            [fDefaults setBool: NO forKey: @"CheckUpload"];
261        }
262        if ([fDefaults integerForKey: @"DownloadLimit"] < 0)
263        {
264            [fDefaults removeObjectForKey: @"DownloadLimit"];
265            [fDefaults setBool: NO forKey: @"CheckDownload"];
266        }
267       
268        tr_benc settings;
269        tr_bencInitDict(&settings, 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    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1915   
1916    Torrent * torrent = [notification object];
1917   
1918    if ([[[notification userInfo] objectForKey: @"WasRunning"] boolValue])
1919    {
1920        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1921        {
1922            NSSound * sound;
1923            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1924            {
1925                [sound setDelegate: self];
1926                fSoundPlaying = YES;
1927                [sound play];
1928            }
1929        }
1930       
1931        NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_DOWNLOAD_COMPLETE forKey: @"Type"];
1932       
1933        NSString * location = [torrent dataLocation];
1934        if (location)
1935            [clickContext setObject: location forKey: @"Location"];
1936       
1937        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1938                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1939                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1940       
1941        if (![fWindow isMainWindow])
1942            [fBadger incrementCompleted];
1943       
1944        //bounce download stack
1945        [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"com.apple.DownloadFileFinished"
1946            object: [torrent dataLocation]];
1947       
1948        if ([torrent isActive] && [fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] == 0)
1949        {
1950            [torrent stopTransfer];
1951            [torrent setWaitToStart: YES];
1952        }
1953    }
1954   
1955    [self updateTorrentsInQueue];
1956   
1957    [pool drain];
1958}
1959
1960- (void) torrentRestartedDownloading: (NSNotification *) notification
1961{
1962    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1963   
1964    Torrent * torrent = [notification object];
1965    if ([torrent isActive] && [fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] == 0)
1966    {
1967        [torrent stopTransfer];
1968        [torrent setWaitToStart: YES];
1969    }
1970   
1971    [self updateTorrentsInQueue];
1972   
1973    [pool drain];
1974}
1975
1976- (void) torrentFinishedSeeding: (NSNotification *) notification
1977{
1978    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1979   
1980    Torrent * torrent = [notification object];
1981   
1982    [self updateTorrentsInQueue];
1983   
1984    if ([[fTableView selectedTorrents] containsObject: torrent])
1985    {
1986        [fInfoController updateInfoStats];
1987        [fInfoController updateOptions];
1988    }
1989   
1990    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1991    {
1992        NSSound * sound;
1993        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1994        {
1995            [sound setDelegate: self];
1996            fSoundPlaying = YES;
1997            [sound play];
1998        }
1999    }
2000   
2001    NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_SEEDING_COMPLETE forKey: @"Type"];
2002   
2003    NSString * location = [torrent dataLocation];
2004    if (location)
2005        [clickContext setObject: location forKey: @"Location"];
2006   
2007    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
2008                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2009                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2010   
2011    [pool drain];
2012}
2013
2014- (void) updateTorrentHistory
2015{
2016    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2017   
2018    for (Torrent * torrent in fTorrents)
2019        [history addObject: [torrent history]];
2020   
2021    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST] atomically: YES];
2022}
2023
2024- (void) setSort: (id) sender
2025{
2026    NSString * sortType;
2027    switch ([sender tag])
2028    {
2029        case SORT_ORDER_TAG:
2030            sortType = SORT_ORDER;
2031            [fDefaults setBool: NO forKey: @"SortReverse"];
2032            break;
2033        case SORT_DATE_TAG:
2034            sortType = SORT_DATE;
2035            break;
2036        case SORT_NAME_TAG:
2037            sortType = SORT_NAME;
2038            break;
2039        case SORT_PROGRESS_TAG:
2040            sortType = SORT_PROGRESS;
2041            break;
2042        case SORT_STATE_TAG:
2043            sortType = SORT_STATE;
2044            break;
2045        case SORT_TRACKER_TAG:
2046            sortType = SORT_TRACKER;
2047            break;
2048        case SORT_ACTIVITY_TAG:
2049            sortType = SORT_ACTIVITY;
2050            break;
2051        default:
2052            NSAssert1(NO, @"Unknown sort tag received: %d", [sender tag]);
2053            return;
2054    }
2055   
2056    [fDefaults setObject: sortType forKey: @"Sort"];
2057    [self applyFilter: nil]; //better than calling sortTorrents because it will even apply to queue order
2058}
2059
2060- (void) setSortByGroup: (id) sender
2061{
2062    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
2063    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
2064   
2065    //expand all groups
2066    if (sortByGroup)
2067        [fTableView removeAllCollapsedGroups];
2068   
2069    [self applyFilter: nil];
2070}
2071
2072- (void) setSortReverse: (id) sender
2073{
2074    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
2075    [self sortTorrents];
2076}
2077
2078- (void) sortTorrents
2079{
2080    NSArray * selectedValues = [fTableView selectedValues];
2081   
2082    [self sortTorrentsIgnoreSelected]; //actually sort
2083   
2084    [fTableView selectValues: selectedValues];
2085}
2086
2087- (void) sortTorrentsIgnoreSelected
2088{
2089    NSString * sortType = [fDefaults stringForKey: @"Sort"];
2090   
2091    if (![sortType isEqualToString: SORT_ORDER])
2092    {
2093        const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
2094       
2095        NSArray * descriptors;
2096        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
2097                                                selector: @selector(compareFinder:)] autorelease];
2098       
2099        if ([sortType isEqualToString: SORT_STATE])
2100        {
2101            NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
2102                            * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
2103                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
2104           
2105            descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
2106                                                                nameDescriptor, nil];
2107        }
2108        else if ([sortType isEqualToString: SORT_PROGRESS])
2109        {
2110            NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
2111                            * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
2112                                                            ascending: asc] autorelease],
2113                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
2114           
2115            descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
2116                                                                nameDescriptor, nil];
2117        }
2118        else if ([sortType isEqualToString: SORT_TRACKER])
2119        {
2120            NSSortDescriptor * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerSortKey" ascending: asc
2121                                                    selector: @selector(localizedCaseInsensitiveCompare:)] autorelease];
2122           
2123            descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, nil];
2124        }
2125        else if ([sortType isEqualToString: SORT_ACTIVITY])
2126        {
2127            NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
2128            NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
2129                                                        autorelease];
2130           
2131            descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
2132        }
2133        else if ([sortType isEqualToString: SORT_DATE])
2134        {
2135            NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
2136           
2137            descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
2138        }
2139        else
2140            descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, nil];
2141       
2142        //actually sort
2143        if ([fDefaults boolForKey: @"SortByGroup"])
2144        {
2145            for (TorrentGroup * group in fDisplayedTorrents)
2146                [[group torrents] sortUsingDescriptors: descriptors];
2147        }
2148        else
2149            [fDisplayedTorrents sortUsingDescriptors: descriptors];
2150       
2151        [descriptors release];
2152    }
2153   
2154    [fTableView reloadData];
2155}
2156
2157- (void) applyFilter: (id) sender
2158{
2159    //get all the torrents in the table
2160    NSMutableArray * previousTorrents;
2161    if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2162    {
2163        previousTorrents = [NSMutableArray array];
2164       
2165        for (TorrentGroup * group in fDisplayedTorrents)
2166            [previousTorrents addObjectsFromArray: [group torrents]];
2167    }
2168    else
2169        previousTorrents = fDisplayedTorrents;
2170   
2171    NSArray * selectedValues = [fTableView selectedValues];
2172   
2173    NSUInteger active = 0, downloading = 0, seeding = 0, paused = 0;
2174    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2175    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
2176    if ([filterType isEqualToString: FILTER_ACTIVE])
2177        filterActive = YES;
2178    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2179        filterDownload = YES;
2180    else if ([filterType isEqualToString: FILTER_SEED])
2181        filterSeed = YES;
2182    else if ([filterType isEqualToString: FILTER_PAUSE])
2183        filterPause = YES;
2184    else
2185        filterStatus = NO;
2186   
2187    const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
2188    const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
2189   
2190    NSString * searchString = [fSearchFilterField stringValue];
2191    const BOOL filterText = [searchString length] > 0,
2192            filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
2193   
2194    NSMutableArray * allTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2195   
2196    //get count of each type
2197    for (Torrent * torrent in fTorrents)
2198    {
2199        //check status
2200        if ([torrent isActive] && ![torrent isCheckingWaiting])
2201        {
2202            const BOOL isActive = ![torrent isStalled];
2203            if (isActive)
2204                active++;
2205           
2206            if ([torrent isSeeding])
2207            {
2208                seeding++;
2209                if (filterStatus && !((filterActive && isActive) || filterSeed))
2210                    continue;
2211            }
2212            else
2213            {
2214                downloading++;
2215                if (filterStatus && !((filterActive && isActive) || filterDownload))
2216                    continue;
2217            }
2218        }
2219        else
2220        {
2221            paused++;
2222            if (filterStatus && !filterPause)
2223                continue;
2224        }
2225       
2226        //checkGroup
2227        if (filterGroup)
2228            if ([torrent groupValue] != groupFilterValue)
2229                continue;
2230       
2231        //check text field
2232        if (filterText)
2233        {
2234            if (filterTracker)
2235            {
2236                BOOL removeTextField = YES;
2237                for (NSString * tracker in [torrent allTrackersFlat])
2238                {
2239                    if ([tracker rangeOfString: searchString options:
2240                            (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound)
2241                    {
2242                        removeTextField = NO;
2243                        break;
2244                    }
2245                }
2246               
2247                if (removeTextField)
2248                    continue;
2249            }
2250            else
2251            {
2252                if ([[torrent name] rangeOfString: searchString options:
2253                        (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound)
2254                    continue;
2255            }
2256        }
2257       
2258        [allTorrents addObject: torrent];
2259    }
2260   
2261    //set button tooltips
2262    [fNoFilterButton setCount: [fTorrents count]];
2263    [fActiveFilterButton setCount: active];
2264    [fDownloadFilterButton setCount: downloading];
2265    [fSeedFilterButton setCount: seeding];
2266    [fPauseFilterButton setCount: paused];
2267   
2268    //clear display cache for not-shown torrents
2269    [previousTorrents removeObjectsInArray: allTorrents];
2270    for (Torrent * torrent in previousTorrents)
2271        [torrent setPreviousFinishedPieces: nil];
2272   
2273    //place torrents into groups
2274    const BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"];
2275    if (groupRows)
2276    {
2277        NSMutableArray * oldTorrentGroups = [NSMutableArray array];
2278        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2279            [oldTorrentGroups addObjectsFromArray: fDisplayedTorrents];
2280       
2281        [fDisplayedTorrents removeAllObjects];
2282       
2283        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2284        [allTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2285       
2286        TorrentGroup * group = nil;
2287        NSInteger lastGroupValue = -2, currentOldGroupIndex = 0;
2288        for (Torrent * torrent in allTorrents)
2289        {
2290            const NSInteger groupValue = [torrent groupValue];
2291            if (groupValue != lastGroupValue)
2292            {
2293                lastGroupValue = groupValue;
2294               
2295                group = nil;
2296               
2297                //try to see if the group already exists
2298                for (; currentOldGroupIndex < [oldTorrentGroups count]; currentOldGroupIndex++)
2299                {
2300                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
2301                    const NSInteger currentGroupValue = [currentGroup groupIndex];
2302                    if (currentGroupValue == groupValue)
2303                    {
2304                        group = currentGroup;
2305                        [[currentGroup torrents] removeAllObjects];
2306                       
2307                        currentOldGroupIndex++;
2308                    }
2309                   
2310                    if (currentGroupValue >= groupValue)
2311                        break;
2312                }
2313               
2314                if (!group)
2315                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2316                [fDisplayedTorrents addObject: group];
2317            }
2318           
2319            NSAssert(group != nil, @"No group object to add torrents to");
2320            [[group torrents] addObject: torrent];
2321        }
2322    }
2323    else
2324        [fDisplayedTorrents setArray: allTorrents];
2325   
2326    //actually sort
2327    [self sortTorrentsIgnoreSelected];
2328   
2329    //reset expanded/collapsed rows
2330    if (groupRows)
2331    {
2332        for (TorrentGroup * group in fDisplayedTorrents)
2333        {
2334            if ([fTableView isGroupCollapsed: [group groupIndex]])
2335                [fTableView collapseItem: group];
2336            else
2337                [fTableView expandItem: group];
2338        }
2339    }
2340   
2341    [fTableView selectValues: selectedValues];
2342    [self resetInfo]; //if group is already selected, but the torrents in it change
2343   
2344    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2345   
2346    [self setWindowSizeToFit];
2347}
2348
2349//resets filter and sorts torrents
2350- (void) setFilter: (id) sender
2351{
2352    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2353   
2354    NSButton * prevFilterButton;
2355    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2356        prevFilterButton = fPauseFilterButton;
2357    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2358        prevFilterButton = fActiveFilterButton;
2359    else if ([oldFilterType isEqualToString: FILTER_SEED])
2360        prevFilterButton = fSeedFilterButton;
2361    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2362        prevFilterButton = fDownloadFilterButton;
2363    else
2364        prevFilterButton = fNoFilterButton;
2365   
2366    if (sender != prevFilterButton)
2367    {
2368        [prevFilterButton setState: NSOffState];
2369        [sender setState: NSOnState];
2370
2371        NSString * filterType;
2372        if (sender == fActiveFilterButton)
2373            filterType = FILTER_ACTIVE;
2374        else if (sender == fDownloadFilterButton)
2375            filterType = FILTER_DOWNLOAD;
2376        else if (sender == fPauseFilterButton)
2377            filterType = FILTER_PAUSE;
2378        else if (sender == fSeedFilterButton)
2379            filterType = FILTER_SEED;
2380        else
2381            filterType = FILTER_NONE;
2382
2383        [fDefaults setObject: filterType forKey: @"Filter"];
2384    }
2385    else
2386        [sender setState: NSOnState];
2387
2388    [self applyFilter: nil];
2389}
2390
2391- (void) setFilterSearchType: (id) sender
2392{
2393    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2394   
2395    NSInteger prevTag, currentTag = [sender tag];
2396    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2397        prevTag = FILTER_TYPE_TAG_TRACKER;
2398    else
2399        prevTag = FILTER_TYPE_TAG_NAME;
2400   
2401    if (currentTag != prevTag)
2402    {
2403        NSString * filterType;
2404        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2405            filterType = FILTER_TYPE_TRACKER;
2406        else
2407            filterType = FILTER_TYPE_NAME;
2408       
2409        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2410       
2411        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2412    }
2413   
2414    [self applyFilter: nil];
2415}
2416
2417- (void) switchFilter: (id) sender
2418{
2419    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2420   
2421    NSButton * button;
2422    if ([filterType isEqualToString: FILTER_NONE])
2423        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2424    else if ([filterType isEqualToString: FILTER_ACTIVE])
2425        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2426    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2427        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2428    else if ([filterType isEqualToString: FILTER_SEED])
2429        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2430    else if ([filterType isEqualToString: FILTER_PAUSE])
2431        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2432    else
2433        button = fNoFilterButton;
2434   
2435    [self setFilter: button];
2436}
2437
2438- (void) setStatusLabel: (id) sender
2439{
2440    NSString * statusLabel;
2441    switch ([sender tag])
2442    {
2443        case STATUS_RATIO_TOTAL_TAG:
2444            statusLabel = STATUS_RATIO_TOTAL;
2445            break;
2446        case STATUS_RATIO_SESSION_TAG:
2447            statusLabel = STATUS_RATIO_SESSION;
2448            break;
2449        case STATUS_TRANSFER_TOTAL_TAG:
2450            statusLabel = STATUS_TRANSFER_TOTAL;
2451            break;
2452        case STATUS_TRANSFER_SESSION_TAG:
2453            statusLabel = STATUS_TRANSFER_SESSION;
2454            break;
2455        default:
2456            NSAssert1(NO, @"Unknown status label tag received: %d", [sender tag]);
2457            return;
2458    }
2459   
2460    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2461    [self updateUI];
2462}
2463
2464- (void) menuNeedsUpdate: (NSMenu *) menu
2465{
2466    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu || menu == fGroupFilterMenu)
2467    {
2468        const BOOL filter = menu == fGroupFilterMenu;
2469       
2470        const NSInteger remaining = filter ? 3 : 0;
2471        for (NSInteger i = [menu numberOfItems]-1; i >= remaining; i--)
2472            [menu removeItemAtIndex: i];
2473       
2474        NSMenu * groupMenu;
2475        if (!filter)
2476            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2477        else
2478            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:) isSmall: YES];
2479       
2480        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2481        for (NSInteger i = 0; i < groupMenuCount; i++)
2482        {
2483            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2484            [groupMenu removeItemAtIndex: 0];
2485            [menu addItem: item];
2486            [item release];
2487        }
2488    }
2489    else if (menu == fUploadMenu || menu == fDownloadMenu)
2490    {
2491        if ([menu numberOfItems] > 3)
2492            return;
2493       
2494        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2495       
2496        NSMenuItem * item;
2497        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2498        {
2499            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2500                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2501                    keyEquivalent: @""];
2502            [item setTarget: self];
2503            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2504            [menu addItem: item];
2505            [item release];
2506        }
2507    }
2508    else if (menu == fRatioStopMenu)
2509    {
2510        if ([menu numberOfItems] > 3)
2511            return;
2512       
2513        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2514       
2515        NSMenuItem * item;
2516        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2517        {
2518            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2519                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2520            [item setTarget: self];
2521            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2522            [menu addItem: item];
2523            [item release];
2524        }
2525    }
2526    else;
2527}
2528
2529- (void) setGroup: (id) sender
2530{
2531    for (Torrent * torrent in [fTableView selectedTorrents])
2532    {
2533        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2534       
2535        [torrent setGroupValue: [sender tag]];
2536    }
2537   
2538    [self applyFilter: nil];
2539    [self updateUI];
2540    [self updateTorrentHistory];
2541}
2542
2543- (void) setGroupFilter: (id) sender
2544{
2545    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2546    [self updateGroupsFilterButton];
2547    [self applyFilter: nil];
2548}
2549
2550- (void) updateGroupsFilterButton
2551{
2552    NSInteger groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2553   
2554    NSImage * icon;
2555    NSString * toolTip;
2556    if (groupIndex == GROUP_FILTER_ALL_TAG)
2557    {
2558        icon = [NSImage imageNamed: @"PinTemplate.png"];
2559        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2560    }
2561    else
2562    {
2563        icon = [[GroupsController groups] imageForIndex: groupIndex];
2564        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2565                                                : NSLocalizedString(@"None", "Groups -> Button");
2566        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2567    }
2568   
2569    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2570    [fGroupsButton setToolTip: toolTip];
2571}
2572
2573- (void) updateGroupsFilters: (NSNotification *) notification
2574{
2575    [self updateGroupsFilterButton];
2576    [self applyFilter: nil];
2577}
2578
2579- (void) toggleSpeedLimit: (id) sender
2580{
2581    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2582    [self speedLimitChanged: sender];
2583}
2584
2585- (void) speedLimitChanged: (id) sender
2586{
2587    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2588    [self updateSpeedFieldsToolTips];
2589}
2590
2591//dict has been retained
2592- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2593{
2594    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2595
2596    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2597    [self updateSpeedFieldsToolTips];
2598   
2599    if (![[dict objectForKey: @"ByUser"] boolValue])
2600        [GrowlApplicationBridge notifyWithTitle: isLimited
2601                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2602                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2603            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2604            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2605   
2606    [dict release];
2607}
2608
2609- (void) setLimitGlobalEnabled: (id) sender
2610{
2611    BOOL upload = [sender menu] == fUploadMenu;
2612    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2613   
2614    [fPrefsController applySpeedSettings: nil];
2615}
2616
2617- (void) setQuickLimitGlobal: (id) sender
2618{
2619    BOOL upload = [sender menu] == fUploadMenu;
2620    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2621    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2622   
2623    [fPrefsController updateLimitFields];
2624    [fPrefsController applySpeedSettings: nil];
2625}
2626
2627- (void) setRatioGlobalEnabled: (id) sender
2628{
2629    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2630   
2631    [fPrefsController applyRatioSetting: nil];
2632}
2633
2634- (void) setQuickRatioGlobal: (id) sender
2635{
2636    [fDefaults setBool: YES forKey: @"RatioCheck"];
2637    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2638   
2639    [fPrefsController updateRatioStopField];
2640}
2641
2642- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2643{
2644    fSoundPlaying = NO;
2645}
2646
2647- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2648{
2649    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2650    {
2651        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2652            return;
2653       
2654        if (fAutoImportTimer)
2655        {
2656            if ([fAutoImportTimer isValid])
2657                [fAutoImportTimer invalidate];
2658            [fAutoImportTimer release];
2659            fAutoImportTimer = nil;
2660        }
2661       
2662        //check again in 10 seconds in case torrent file wasn't complete
2663        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2664            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2665       
2666        [self checkAutoImportDirectory];
2667    }
2668}
2669
2670- (void) changeAutoImport
2671{
2672    if (fAutoImportTimer)
2673    {
2674        if ([fAutoImportTimer isValid])
2675            [fAutoImportTimer invalidate];
2676        [fAutoImportTimer release];
2677        fAutoImportTimer = nil;
2678    }
2679   
2680    if (fAutoImportedNames)
2681    {
2682        [fAutoImportedNames release];
2683        fAutoImportedNames = nil;
2684    }
2685   
2686    [self checkAutoImportDirectory];
2687}
2688
2689- (void) checkAutoImportDirectory
2690{
2691    NSString * path;
2692    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2693        return;
2694   
2695    path = [path stringByExpandingTildeInPath];
2696   
2697    NSArray * importedNames;
2698    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2699        return;
2700   
2701    //only check files that have not been checked yet
2702    NSMutableArray * newNames = [importedNames mutableCopy];
2703   
2704    if (fAutoImportedNames)
2705        [newNames removeObjectsInArray: fAutoImportedNames];
2706    else
2707        fAutoImportedNames = [[NSMutableArray alloc] init];
2708    [fAutoImportedNames setArray: importedNames];
2709   
2710    for (NSString * file in newNames)
2711    {
2712        if ([file hasPrefix: @"."])
2713            continue;
2714       
2715        NSString * fullFile = [path stringByAppendingPathComponent: file];
2716       
2717        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2718                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2719            continue;
2720       
2721        tr_ctor * ctor = tr_ctorNew(fLib);
2722        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2723       
2724        switch (tr_torrentParse(ctor, NULL))
2725        {
2726            case TR_PARSE_OK:
2727                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2728               
2729                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2730                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2731                    clickContext: nil];
2732                break;
2733           
2734            case TR_PARSE_ERR:
2735                [fAutoImportedNames removeObject: file];
2736        }
2737       
2738        tr_ctorFree(ctor);
2739    }
2740   
2741    [newNames release];
2742}
2743
2744- (void) beginCreateFile: (NSNotification *) notification
2745{
2746    if (![fDefaults boolForKey: @"AutoImport"])
2747        return;
2748   
2749    NSString * location = [notification object],
2750            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2751   
2752    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2753                                    isEqualToString: [path stringByExpandingTildeInPath]])
2754        [fAutoImportedNames addObject: [location lastPathComponent]];
2755}
2756
2757- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2758{
2759    if (item)
2760        return [[item torrents] count];
2761    else
2762        return [fDisplayedTorrents count];
2763}
2764
2765- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2766{
2767    if (item)
2768        return [[item torrents] objectAtIndex: index];
2769    else
2770        return [fDisplayedTorrents objectAtIndex: index];
2771}
2772
2773- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2774{
2775    return ![item isKindOfClass: [Torrent class]];
2776}
2777
2778- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2779{
2780    if ([item isKindOfClass: [Torrent class]])
2781        return [item hashString];
2782    else
2783    {
2784        NSString * ident = [tableColumn identifier];
2785        if ([ident isEqualToString: @"Group"])
2786        {
2787            NSInteger group = [item groupIndex];
2788            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2789                                : NSLocalizedString(@"No Group", "Group table row");
2790        }
2791        else if ([ident isEqualToString: @"Color"])
2792        {
2793            NSInteger group = [item groupIndex];
2794            return [[GroupsController groups] imageForIndex: group];
2795        }
2796        else if ([ident isEqualToString: @"DL Image"])
2797            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2798        else if ([ident isEqualToString: @"UL Image"])
2799            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2800                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2801        else
2802        {
2803            TorrentGroup * group = (TorrentGroup *)item;
2804           
2805            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2806                return [NSString stringForRatio: [group ratio]];
2807            else
2808            {
2809                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2810                return [NSString stringForSpeed: rate];
2811            }
2812        }
2813    }
2814}
2815
2816- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2817{
2818    //only allow reordering of rows if sorting by order
2819    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2820    {
2821        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2822        for (id torrent in items)
2823        {
2824            if (![torrent isKindOfClass: [Torrent class]])
2825                return NO;
2826           
2827            [indexSet addIndex: [fTableView rowForItem: torrent]];
2828        }
2829       
2830        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2831        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2832        return YES;
2833    }
2834    return NO;
2835}
2836
2837- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2838    proposedChildIndex: (NSInteger) index
2839{
2840    NSPasteboard * pasteboard = [info draggingPasteboard];
2841    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2842    {
2843        if ([fDefaults boolForKey: @"SortByGroup"])
2844        {
2845            if (!item)
2846                return NSDragOperationNone;
2847           
2848            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2849            {
2850                if ([item isKindOfClass: [Torrent class]])
2851                {
2852                    TorrentGroup * group = [fTableView parentForItem: item];
2853                    index = [[group torrents] indexOfObject: item] + 1;
2854                    item = group;
2855                }
2856            }
2857            else
2858            {
2859                if ([item isKindOfClass: [Torrent class]])
2860                    item = [fTableView parentForItem: item];
2861                index = NSOutlineViewDropOnItemIndex;
2862            }
2863        }
2864        else
2865        {
2866            if (item)
2867            {
2868                index = [fTableView rowForItem: item] + 1;
2869                item = nil;
2870            }
2871        }
2872       
2873        [fTableView setDropItem: item dropChildIndex: index];
2874        return NSDragOperationGeneric;
2875    }
2876   
2877    return NSDragOperationNone;
2878}
2879
2880- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2881    childIndex: (NSInteger) newRow
2882{
2883    NSPasteboard * pasteboard = [info draggingPasteboard];
2884    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2885    {
2886        //remember selected rows
2887        NSArray * selectedValues = [fTableView selectedValues];
2888   
2889        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2890       
2891        //get the torrents to move
2892        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2893        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2894            [movingTorrents addObject: [fTableView itemAtRow: i]];
2895       
2896        //reset groups
2897        if (item)
2898        {
2899            //change groups
2900            NSInteger groupValue = [item groupIndex];
2901            for (Torrent * torrent in movingTorrents)
2902            {
2903                //have to reset objects here to avoid weird crash
2904                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2905                [[item torrents] addObject: torrent];
2906               
2907                [torrent setGroupValue: groupValue];
2908            }
2909            //part 2 of avoiding weird crash
2910            [fTableView reloadItem: nil reloadChildren: YES];
2911        }
2912       
2913        //reorder queue order
2914        if (newRow != NSOutlineViewDropOnItemIndex)
2915        {
2916            //find torrent to place under
2917            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2918            Torrent * topTorrent = nil;
2919            for (NSInteger i = newRow-1; i >= 0; i--)
2920            {
2921                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2922                if (![movingTorrents containsObject: tempTorrent])
2923                {
2924                    topTorrent = tempTorrent;
2925                    break;
2926                }
2927            }
2928           
2929            //remove objects to reinsert
2930            [fTorrents removeObjectsInArray: movingTorrents];
2931           
2932            //insert objects at new location
2933            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2934            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2935            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2936        }
2937       
2938        [self applyFilter: nil];
2939        [fTableView selectValues: selectedValues];
2940    }
2941   
2942    return YES;
2943}
2944
2945- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2946{
2947    [self resetInfo];
2948    [[fWindow toolbar] validateVisibleItems];
2949}
2950
2951- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2952{
2953    NSPasteboard * pasteboard = [info draggingPasteboard];
2954    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2955    {
2956        //check if any torrent files can be added
2957        BOOL torrent = NO;
2958        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2959        for (NSString * file in files)
2960        {
2961            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2962                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2963            {
2964                torrent = YES;
2965                tr_ctor * ctor = tr_ctorNew(fLib);
2966                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2967                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2968                {
2969                    if (!fOverlayWindow)
2970                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2971                    [fOverlayWindow setTorrents: files];
2972                   
2973                    return NSDragOperationCopy;
2974                }
2975                tr_ctorFree(ctor);
2976            }
2977        }
2978       
2979        //create a torrent file if a single file
2980        if (!torrent && [files count] == 1)
2981        {
2982            if (!fOverlayWindow)
2983                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2984            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2985           
2986            return NSDragOperationCopy;
2987        }
2988    }
2989    else if ([[pasteboard types] containsObject: NSURLPboardType])
2990    {
2991        if (!fOverlayWindow)
2992            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2993        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2994       
2995        return NSDragOperationCopy;
2996    }
2997    else;
2998   
2999    return NSDragOperationNone;
3000}
3001
3002- (void) draggingExited: (id <NSDraggingInfo>) info
3003{
3004    if (fOverlayWindow)
3005        [fOverlayWindow fadeOut];
3006}
3007
3008- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
3009{
3010    if (fOverlayWindow)
3011        [fOverlayWindow fadeOut];
3012   
3013    NSPasteboard * pasteboard = [info draggingPasteboard];
3014    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
3015    {
3016        BOOL torrent = NO, accept = YES;
3017       
3018        //create an array of files that can be opened
3019        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
3020        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
3021        for (NSString * file in files)
3022        {
3023            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
3024                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
3025            {
3026                torrent = YES;
3027                tr_ctor * ctor = tr_ctorNew(fLib);
3028                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
3029                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
3030                    [filesToOpen addObject: file];
3031                tr_ctorFree(ctor);
3032            }
3033        }
3034       
3035        if ([filesToOpen count] > 0)
3036            [self application: NSApp openFiles: filesToOpen];
3037        else
3038        {
3039            if (!torrent && [files count] == 1)
3040                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
3041            else
3042                accept = NO;
3043        }
3044       
3045        return accept;
3046    }
3047    else if ([[pasteboard types] containsObject: NSURLPboardType])
3048    {
3049        NSURL * url;
3050        if ((url = [NSURL URLFromPasteboard: pasteboard]))
3051        {
3052            [self openURL: [url absoluteString]];
3053            return YES;
3054        }
3055    }
3056    else;
3057   
3058    return NO;
3059}
3060
3061- (void) toggleSmallView: (id) sender
3062{
3063    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
3064    [fDefaults setBool: makeSmall forKey: @"SmallView"];
3065   
3066    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
3067   
3068    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
3069   
3070    //window min height
3071    NSSize contentMinSize = [fWindow contentMinSize],
3072            contentSize = [[fWindow contentView] frame].size;
3073    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
3074                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
3075    [fWindow setContentMinSize: contentMinSize];
3076   
3077    //resize for larger min height if not set to auto size
3078    if (![fDefaults boolForKey: @"AutoSize"])
3079    {
3080        if (!makeSmall && contentSize.height < contentMinSize.height)
3081        {
3082            NSRect frame = [fWindow frame];
3083            CGFloat heightChange = contentMinSize.height - contentSize.height;
3084            frame.size.height += heightChange;
3085            frame.origin.y -= heightChange;
3086           
3087            [fWindow setFrame: frame display: YES];
3088        }
3089    }
3090    else
3091        [self setWindowSizeToFit];
3092}
3093
3094- (void) togglePiecesBar: (id) sender
3095{
3096    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
3097    [fTableView togglePiecesBar];
3098}
3099
3100- (void) toggleAvailabilityBar: (id) sender
3101{
3102    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
3103    [fTableView display];
3104}
3105
3106- (void) toggleStatusString: (id) sender
3107{
3108    if ([fDefaults boolForKey: @"SmallView"])
3109        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
3110    else
3111        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
3112   
3113    [fTableView reloadData];
3114}
3115
3116- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
3117{
3118    NSScrollView * scrollView = [fTableView enclosingScrollView];
3119   
3120    //convert pixels to points
3121    NSRect windowFrame = [fWindow frame];
3122    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
3123    windowSize.height += height;
3124   
3125    if (check)
3126    {
3127        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
3128       
3129        if (windowSize.height < minSize.height)
3130            windowSize.height = minSize.height;
3131        else
3132        {
3133            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
3134            if ([fStatusBar isHidden])
3135                maxSize.height -= [fStatusBar frame].size.height;
3136            if ([fFilterBar isHidden])
3137                maxSize.height -= [fFilterBar frame].size.height;
3138            if (windowSize.height > maxSize.height)
3139                windowSize.height = maxSize.height;
3140        }
3141    }
3142
3143    //convert points to pixels
3144    windowSize = [scrollView convertSize: windowSize toView: nil];
3145
3146    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
3147    windowFrame.size.height = windowSize.height;
3148    return windowFrame;
3149}
3150
3151- (void) toggleStatusBar: (id) sender
3152{
3153    [self showStatusBar: [fStatusBar isHidden] animate: YES];
3154    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
3155}
3156
3157//doesn't save shown state
3158- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
3159{
3160    if (show != [fStatusBar isHidden])
3161        return;
3162
3163    if (show)
3164        [fStatusBar setHidden: NO];
3165
3166    NSRect frame;
3167    CGFloat heightChange = [fStatusBar frame].size.height;
3168    if (!show)
3169        heightChange *= -1;
3170   
3171    //allow bar to show even if not enough room
3172    if (show && ![fDefaults boolForKey: @"AutoSize"])
3173    {
3174        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3175        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3176        if (change < 0.0)
3177        {
3178            frame = [fWindow frame];
3179            frame.size.height += change;
3180            frame.origin.y -= change;
3181            [fWindow setFrame: frame display: NO animate: NO];
3182        }
3183    }
3184
3185    [self updateUI];
3186   
3187    NSScrollView * scrollView = [fTableView enclosingScrollView];
3188   
3189    //set views to not autoresize
3190    NSUInteger statsMask = [fStatusBar autoresizingMask];
3191    NSUInteger filterMask = [fFilterBar autoresizingMask];
3192    NSUInteger scrollMask = [scrollView autoresizingMask];
3193    [fStatusBar setAutoresizingMask: NSViewNotSizable];
3194    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3195    [scrollView setAutoresizingMask: NSViewNotSizable];
3196   
3197    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3198    [fWindow setFrame: frame display: YES animate: animate];
3199   
3200    //re-enable autoresize
3201    [fStatusBar setAutoresizingMask: statsMask];
3202    [fFilterBar setAutoresizingMask: filterMask];
3203    [scrollView setAutoresizingMask: scrollMask];
3204   
3205    //change min size
3206    NSSize minSize = [fWindow contentMinSize];
3207    minSize.height += heightChange;
3208    [fWindow setContentMinSize: minSize];
3209   
3210    if (!show)
3211        [fStatusBar setHidden: YES];
3212}
3213
3214- (void) toggleFilterBar: (id) sender
3215{
3216    //disable filtering when hiding
3217    if (![fFilterBar isHidden])
3218    {
3219        [fSearchFilterField setStringValue: @""];
3220        [self setFilter: fNoFilterButton];
3221        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3222    }
3223
3224    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3225    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3226    [[fWindow toolbar] validateVisibleItems];
3227}
3228
3229//doesn't save shown state
3230- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3231{
3232    if (show != [fFilterBar isHidden])
3233        return;
3234
3235    if (show)
3236        [fFilterBar setHidden: NO];
3237
3238    NSRect frame;
3239    CGFloat heightChange = [fFilterBar frame].size.height;
3240    if (!show)
3241        heightChange *= -1;
3242   
3243    //allow bar to show even if not enough room
3244    if (show && ![fDefaults boolForKey: @"AutoSize"])
3245    {
3246        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3247        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3248        if (change < 0.0)
3249        {
3250            frame = [fWindow frame];
3251            frame.size.height += change;
3252            frame.origin.y -= change;
3253            [fWindow setFrame: frame display: NO animate: NO];
3254        }
3255    }
3256   
3257    NSScrollView * scrollView = [fTableView enclosingScrollView];
3258
3259    //set views to not autoresize
3260    NSUInteger filterMask = [fFilterBar autoresizingMask];
3261    NSUInteger scrollMask = [scrollView autoresizingMask];
3262    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3263    [scrollView setAutoresizingMask: NSViewNotSizable];
3264   
3265    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3266    [fWindow setFrame: frame display: YES animate: animate];
3267   
3268    //re-enable autoresize
3269    [fFilterBar setAutoresizingMask: filterMask];
3270    [scrollView setAutoresizingMask: scrollMask];
3271   
3272    //change min size
3273    NSSize minSize = [fWindow contentMinSize];
3274    minSize.height += heightChange;
3275    [fWindow setContentMinSize: minSize];
3276   
3277    if (!show)
3278    {
3279        [fFilterBar setHidden: YES];
3280        [fWindow makeFirstResponder: fTableView];
3281    }
3282}
3283
3284- (void) focusFilterField
3285{
3286    [fWindow makeFirstResponder: fSearchFilterField];
3287    if ([fFilterBar isHidden])
3288        [self toggleFilterBar: self];
3289}
3290
3291#warning change from id to QLPreviewPanel
3292- (BOOL) acceptsPreviewPanelControl: (id) panel
3293{
3294    return !fQuitting;
3295}
3296
3297- (void) beginPreviewPanelControl: (id) panel
3298{
3299    fPreviewPanel = [panel retain];
3300    [fPreviewPanel setDelegate: self];
3301    [fPreviewPanel setDataSource: self];
3302}
3303
3304- (void) endPreviewPanelControl: (id) panel
3305{
3306    [fPreviewPanel release];
3307    fPreviewPanel = nil;
3308}
3309
3310- (NSArray *) quickLookableTorrents
3311{
3312    NSArray * selectedTorrents = [fTableView selectedTorrents];
3313    NSMutableArray * qlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
3314   
3315    for (Torrent * torrent in selectedTorrents)
3316        if (([torrent isFolder] || [torrent isComplete]) && [torrent dataLocation])
3317            [qlArray addObject: torrent];
3318   
3319    return qlArray;
3320}
3321
3322- (NSInteger) numberOfPreviewItemsInPreviewPanel: (id) panel
3323{
3324    if ([fInfoController canQuickLook])
3325        return [[fInfoController quickLookURLs] count];
3326    else
3327        return [[self quickLookableTorrents] count];
3328}
3329
3330- (id /*<QLPreviewItem>*/) previewPanel: (id) panel previewItemAtIndex: (NSInteger) index
3331{
3332    if ([fInfoController canQuickLook])
3333        return [[fInfoController quickLookURLs] objectAtIndex: index];
3334    else
3335        return [[self quickLookableTorrents] objectAtIndex: index];
3336}
3337
3338- (BOOL) previewPanel: (id) panel handleEvent: (NSEvent *) event
3339{
3340    /*if ([event type] == NSKeyDown)
3341    {
3342        [super keyDown: event];
3343        return YES;
3344    }*/
3345   
3346    return NO;
3347}
3348
3349- (NSRect) previewPanel: (id) panel sourceFrameOnScreenForPreviewItem: (id /*<QLPreviewItem>*/) item
3350{
3351    if ([fInfoController canQuickLook])
3352        return [fInfoController quickLookSourceFrameForPreviewItem: item];
3353    else
3354    {
3355        if (![fWindow isVisible])
3356            return NSZeroRect;
3357       
3358        const NSInteger row = [fTableView rowForItem: item];
3359        if (row == -1)
3360            return NSZeroRect;
3361       
3362        NSRect frame = [fTableView iconRectForRow: row];
3363       
3364        if (!NSIntersectsRect([fTableView visibleRect], frame))
3365            return NSZeroRect;
3366       
3367        frame.origin = [fTableView convertPoint: frame.origin toView: nil];
3368        frame.origin = [fWindow convertBaseToScreen: frame.origin];
3369        frame.origin.y -= frame.size.height;
3370        return frame;
3371    }
3372}
3373
3374- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3375{
3376    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3377   
3378    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3379    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3380    [button setStringValue: @""];
3381   
3382    [item setView: button];
3383    [button release];
3384   
3385    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3386    [item setMinSize: buttonSize];
3387    [item setMaxSize: buttonSize];
3388   
3389    return [item autorelease];
3390}
3391
3392- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3393{
3394    if ([ident isEqualToString: TOOLBAR_CREATE])
3395    {
3396        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3397       
3398        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3399        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3400        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3401        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3402        [item setTarget: self];
3403        [item setAction: @selector(createFile:)];
3404        [item setAutovalidates: NO];
3405       
3406        return item;
3407    }
3408    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3409    {
3410        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3411       
3412        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3413        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3414        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3415        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3416        [item setTarget: self];
3417        [item setAction: @selector(openShowSheet:)];
3418        [item setAutovalidates: NO];
3419       
3420        return item;
3421    }
3422    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3423    {
3424        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3425       
3426        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3427        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3428        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3429        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3430        [item setTarget: self];
3431        [item setAction: @selector(openURLShowSheet:)];
3432        [item setAutovalidates: NO];
3433       
3434        return item;
3435    }
3436    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3437    {
3438        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3439       
3440        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3441        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3442        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3443        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3444        [item setTarget: self];
3445        [item setAction: @selector(removeNoDelete:)];
3446       
3447        return item;
3448    }
3449    else if ([ident isEqualToString: TOOLBAR_INFO])
3450    {
3451        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3452        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3453       
3454        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3455        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3456        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3457        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3458        [item setTarget: self];
3459        [item setAction: @selector(showInfo:)];
3460       
3461        return item;
3462    }
3463    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3464    {
3465        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3466       
3467        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3468        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3469        [groupItem setView: segmentedControl];
3470        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3471       
3472        [segmentedControl setSegmentCount: 2];
3473        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3474       
3475        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3476        [groupItem setMinSize: groupSize];
3477        [groupItem setMaxSize: groupSize];
3478       
3479        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3480        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3481        [groupItem setTarget: self];
3482        [groupItem setAction: @selector(allToolbarClicked:)];
3483       
3484        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3485       
3486        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3487        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3488        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3489                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3490       
3491        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3492        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3493        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3494                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3495       
3496        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3497                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3498       
3499        [segmentedControl release];
3500        return [groupItem autorelease];
3501    }
3502    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3503    {
3504        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3505       
3506        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3507        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3508        [groupItem setView: segmentedControl];
3509        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3510       
3511        [segmentedControl setSegmentCount: 2];
3512        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3513       
3514        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3515        [groupItem setMinSize: groupSize];
3516        [groupItem setMaxSize: groupSize];
3517       
3518        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3519        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3520        [groupItem setTarget: self];
3521        [groupItem setAction: @selector(selectedToolbarClicked:)];
3522       
3523        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3524       
3525        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3526        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3527        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3528                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3529       
3530        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3531        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3532        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3533                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3534       
3535        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3536                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3537       
3538        [segmentedControl release];
3539        return [groupItem autorelease];
3540    }
3541    else if ([ident isEqualToString: TOOLBAR_FILTER])
3542    {
3543        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3544        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3545       
3546        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3547        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3548        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3549        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3550        [item setTarget: self];
3551        [item setAction: @selector(toggleFilterBar:)];
3552       
3553        return item;
3554    }
3555    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3556    {
3557        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3558        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3559       
3560        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3561        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3562        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3563        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3564        [item setTarget: self];
3565        [item setAction: @selector(toggleQuickLook:)];
3566       
3567        return item;
3568    }
3569    else
3570        return nil;
3571}
3572
3573- (void) allToolbarClicked: (id) sender
3574{
3575    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3576                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3577    switch (tagValue)
3578    {
3579        case TOOLBAR_PAUSE_TAG:
3580            [self stopAllTorrents: sender];
3581            break;
3582        case TOOLBAR_RESUME_TAG:
3583            [self resumeAllTorrents: sender];
3584            break;
3585    }
3586}
3587
3588- (void) selectedToolbarClicked: (id) sender
3589{
3590    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3591                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3592    switch (tagValue)
3593    {
3594        case TOOLBAR_PAUSE_TAG:
3595            [self stopSelectedTorrents: sender];
3596            break;
3597        case TOOLBAR_RESUME_TAG:
3598            [self resumeSelectedTorrents: sender];
3599            break;
3600    }
3601}
3602
3603- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3604{
3605    return [NSArray arrayWithObjects:
3606            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3607            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3608            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3609            NSToolbarSeparatorItemIdentifier,
3610            NSToolbarSpaceItemIdentifier,
3611            NSToolbarFlexibleSpaceItemIdentifier,
3612            NSToolbarCustomizeToolbarItemIdentifier, nil];
3613}
3614
3615- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3616{
3617    return [NSArray arrayWithObjects:
3618            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSeparatorItemIdentifier,
3619            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3620            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3621}
3622
3623- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3624{
3625    NSString * ident = [toolbarItem itemIdentifier];
3626   
3627    //enable remove item
3628    if ([ident isEqualToString: TOOLBAR_REMOVE])
3629        return [fTableView numberOfSelectedRows] > 0;
3630
3631    //enable pause all item
3632    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3633    {
3634        for (Torrent * torrent in fTorrents)
3635            if ([torrent isActive] || [torrent waitingToStart])
3636                return YES;
3637        return NO;
3638    }
3639
3640    //enable resume all item
3641    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3642    {
3643        for (Torrent * torrent in fTorrents)
3644            if (![torrent isActive] && ![torrent waitingToStart])
3645                return YES;
3646        return NO;
3647    }
3648
3649    //enable pause item
3650    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3651    {
3652        for (Torrent * torrent in [fTableView selectedTorrents])
3653            if ([torrent isActive] || [torrent waitingToStart])
3654                return YES;
3655        return NO;
3656    }
3657   
3658    //enable resume item
3659    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3660    {
3661        for (Torrent * torrent in [fTableView selectedTorrents])
3662            if (![torrent isActive] && ![torrent waitingToStart])
3663                return YES;
3664        return NO;
3665    }
3666   
3667    //set info image
3668    if ([ident isEqualToString: TOOLBAR_INFO])
3669    {
3670        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3671        return YES;
3672    }
3673   
3674    //set filter image
3675    if ([ident isEqualToString: TOOLBAR_FILTER])
3676    {
3677        [(NSButton *)[toolbarItem view] setState: ![fFilterBar isHidden]];
3678        return YES;
3679    }
3680   
3681    //set quick look image
3682    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3683    {
3684        [(NSButton *)[toolbarItem view] setState: [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
3685                                                    && [[QLPreviewPanelSL sharedPreviewPanel] isVisible]];
3686        return [NSApp isOnSnowLeopardOrBetter];
3687    }
3688
3689    return YES;
3690}
3691
3692- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3693{
3694    SEL action = [menuItem action];
3695   
3696    if (action == @selector(toggleSpeedLimit:))
3697    {
3698        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3699        return YES;
3700    }
3701   
3702    //only enable some items if it is in a context menu or the window is useable
3703    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3704
3705    //enable open items
3706    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3707        return [fWindow attachedSheet] == nil;
3708   
3709    //enable sort options
3710    if (action == @selector(setSort:))
3711    {
3712        NSString * sortType;
3713        switch ([menuItem tag])
3714        {
3715            case SORT_ORDER_TAG:
3716                sortType = SORT_ORDER;
3717                break;
3718            case SORT_DATE_TAG:
3719                sortType = SORT_DATE;
3720                break;
3721            case SORT_NAME_TAG:
3722                sortType = SORT_NAME;
3723                break;
3724            case SORT_PROGRESS_TAG:
3725                sortType = SORT_PROGRESS;
3726                break;
3727            case SORT_STATE_TAG:
3728                sortType = SORT_STATE;
3729                break;
3730            case SORT_TRACKER_TAG:
3731                sortType = SORT_TRACKER;
3732                break;
3733            case SORT_ACTIVITY_TAG:
3734                sortType = SORT_ACTIVITY;
3735                break;
3736            default:
3737                NSAssert1(NO, @"Unknown sort tag received: %d", [menuItem tag]);
3738        }
3739       
3740        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3741        return [fWindow isVisible];
3742    }
3743   
3744    //enable sort options
3745    if (action == @selector(setStatusLabel:))
3746    {
3747        NSString * statusLabel;
3748        switch ([menuItem tag])
3749        {
3750            case STATUS_RATIO_TOTAL_TAG:
3751                statusLabel = STATUS_RATIO_TOTAL;
3752                break;
3753            case STATUS_RATIO_SESSION_TAG:
3754                statusLabel = STATUS_RATIO_SESSION;
3755                break;
3756            case STATUS_TRANSFER_TOTAL_TAG:
3757                statusLabel = STATUS_TRANSFER_TOTAL;
3758                break;
3759            case STATUS_TRANSFER_SESSION_TAG:
3760                statusLabel = STATUS_TRANSFER_SESSION;
3761                break;
3762            default:
3763                NSAssert1(NO, @"Unknown status label tag received: %d", [menuItem tag]);
3764        }
3765       
3766        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3767        return YES;
3768    }
3769   
3770    if (action == @selector(setGroup:))
3771    {
3772        BOOL checked = NO;
3773       
3774        NSInteger index = [menuItem tag];
3775        for (Torrent * torrent in [fTableView selectedTorrents])
3776            if (index == [torrent groupValue])
3777            {
3778                checked = YES;
3779                break;
3780            }
3781       
3782        [menuItem setState: checked ? NSOnState : NSOffState];
3783        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3784    }
3785   
3786    if (action == @selector(setGroupFilter:))
3787    {
3788        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3789        return YES;
3790    }
3791   
3792    if (action == @selector(toggleSmallView:))
3793    {
3794        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3795        return [fWindow isVisible];
3796    }
3797   
3798    if (action == @selector(togglePiecesBar:))
3799    {
3800        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3801        return [fWindow isVisible];
3802    }
3803   
3804    if (action == @selector(toggleStatusString:))
3805    {
3806        if ([fDefaults boolForKey: @"SmallView"])
3807        {
3808            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3809            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3810        }
3811        else
3812        {
3813            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3814            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3815        }
3816       
3817        return [fWindow isVisible];
3818    }
3819   
3820    if (action == @selector(toggleAvailabilityBar:))
3821    {
3822        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3823        return [fWindow isVisible];
3824    }
3825   
3826    if (action == @selector(setLimitGlobalEnabled:))
3827    {
3828        BOOL upload = [menuItem menu] == fUploadMenu;
3829        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3830        if (limit)
3831            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3832                                    "Action menu -> upload/download limit"),
3833                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3834       
3835        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3836        return YES;
3837    }
3838   
3839    if (action == @selector(setRatioGlobalEnabled:))
3840    {
3841        BOOL check = menuItem == fCheckRatioItem;
3842        if (check)
3843            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3844                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3845       
3846        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3847        return YES;
3848    }
3849
3850    //enable show info
3851    if (action == @selector(showInfo:))
3852    {
3853        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3854                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3855        [menuItem setTitle: title];
3856
3857        return YES;
3858    }
3859   
3860    //enable prev/next inspector tab
3861    if (action == @selector(setInfoTab:))
3862        return [[fInfoController window] isVisible];
3863   
3864    //enable toggle status bar
3865    if (action == @selector(toggleStatusBar:))
3866    {
3867        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3868                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3869        [menuItem setTitle: title];
3870
3871        return [fWindow isVisible];
3872    }
3873   
3874    //enable toggle filter bar
3875    if (action == @selector(toggleFilterBar:))
3876    {
3877        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3878                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3879        [menuItem setTitle: title];
3880
3881        return [fWindow isVisible];
3882    }
3883   
3884    //enable prev/next filter button
3885    if (action == @selector(switchFilter:))
3886        return [fWindow isVisible] && ![fFilterBar isHidden];
3887   
3888    //enable reveal in finder
3889    if (action == @selector(revealFile:))
3890        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3891
3892    //enable remove items
3893    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
3894    {
3895        BOOL warning = NO;
3896       
3897        for (Torrent * torrent in [fTableView selectedTorrents])
3898        {
3899            if ([torrent isActive])
3900            {
3901                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
3902                {
3903                    warning = YES;
3904                    break;
3905                }
3906            }
3907        }
3908   
3909        //append or remove ellipsis when needed
3910        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3911        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3912        {
3913            if (![title hasSuffix: ellipsis])
3914                [menuItem setTitle: [title stringByAppendingEllipsis]];
3915        }
3916        else
3917        {
3918            if ([title hasSuffix: ellipsis])
3919                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3920        }
3921       
3922        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3923    }
3924
3925    //enable pause all item
3926    if (action == @selector(stopAllTorrents:))
3927    {
3928        for (Torrent * torrent in fTorrents)
3929            if ([torrent isActive] || [torrent waitingToStart])
3930                return YES;
3931        return NO;
3932    }
3933   
3934    //enable resume all item
3935    if (action == @selector(resumeAllTorrents:))
3936    {
3937        for (Torrent * torrent in fTorrents)
3938            if (![torrent isActive] && ![torrent waitingToStart] && ![torrent isFinishedSeeding])
3939                return YES;
3940        return NO;
3941    }
3942   
3943    //enable resume all waiting item
3944    if (action == @selector(resumeWaitingTorrents:))
3945    {
3946        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3947            return NO;
3948   
3949        for (Torrent * torrent in fTorrents)
3950            if (![torrent isActive] && [torrent waitingToStart])
3951                return YES;
3952        return NO;
3953    }
3954   
3955    //enable resume selected waiting item
3956    if (action == @selector(resumeSelectedTorrentsNoWait:))
3957    {
3958        if (!canUseTable)
3959            return NO;
3960       
3961        for (Torrent * torrent in [fTableView selectedTorrents])
3962            if (![torrent isActive])
3963                return YES;
3964        return NO;
3965    }
3966
3967    //enable pause item
3968    if (action == @selector(stopSelectedTorrents:))
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 resume item
3980    if (action == @selector(resumeSelectedTorrents:))
3981    {
3982        if (!canUseTable)
3983            return NO;
3984   
3985        for (Torrent * torrent in [fTableView selectedTorrents])
3986            if (![torrent isActive] && ![torrent waitingToStart])
3987                return YES;
3988        return NO;
3989    }
3990   
3991    //enable manual announce item
3992    if (action == @selector(announceSelectedTorrents:))
3993    {
3994        if (!canUseTable)
3995            return NO;
3996       
3997        for (Torrent * torrent in [fTableView selectedTorrents])
3998            if ([torrent canManualAnnounce])
3999                return YES;
4000        return NO;
4001    }
4002   
4003    //enable reset cache item
4004    if (action == @selector(verifySelectedTorrents:))
4005    {
4006        if (!canUseTable)
4007            return NO;
4008           
4009        for (Torrent * torrent in [fTableView selectedTorrents])
4010            if (![torrent isMagnet])
4011                return YES;
4012        return NO;
4013    }
4014   
4015    //enable move torrent file item
4016    if (action == @selector(moveDataFilesSelected:))
4017        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4018   
4019    //enable copy torrent file item
4020    if (action == @selector(copyTorrentFiles:))
4021    {
4022        if (!canUseTable)
4023            return NO;
4024       
4025        for (Torrent * torrent in [fTableView selectedTorrents])
4026            if (![torrent isMagnet])
4027                return YES;
4028        return NO;
4029    }
4030   
4031    //enable copy torrent file item
4032    if (action == @selector(copyMagnetLinks:))
4033        return canUseTable && [fTableView numberOfSelectedRows] > 0;
4034   
4035    //enable reverse sort item
4036    if (action == @selector(setSortReverse:))
4037    {
4038        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
4039        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
4040    }
4041   
4042    //enable group sort item
4043    if (action == @selector(setSortByGroup:))
4044    {
4045        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
4046        return YES;
4047    }
4048   
4049    //check proper filter search item
4050    if (action == @selector(setFilterSearchType:))
4051    {
4052        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
4053       
4054        BOOL state;
4055        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
4056            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
4057        else
4058            state = [filterType isEqualToString: FILTER_TYPE_NAME];
4059       
4060        [menuItem setState: state ? NSOnState : NSOffState];
4061        return YES;
4062    }
4063   
4064    if (action == @selector(toggleQuickLook:))
4065    {
4066        const BOOL visible = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
4067                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
4068        //text consistent with Finder
4069        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
4070                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
4071        [menuItem setTitle: title];
4072       
4073        return [NSApp isOnSnowLeopardOrBetter];
4074    }
4075   
4076    return YES;
4077}
4078
4079- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
4080{
4081    switch (messageType)
4082    {
4083        case kIOMessageSystemWillSleep:
4084            //if there are any running transfers, wait 15 seconds for them to stop
4085            for (Torrent * torrent in fTorrents)
4086                if ([torrent isActive])
4087                {
4088                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
4089                    for (Torrent * torrent in fTorrents)
4090                        [torrent sleep];
4091                    sleep(15);
4092                    break;
4093                }
4094
4095            IOAllowPowerChange(fRootPort, (long) messageArgument);
4096            break;
4097
4098        case kIOMessageCanSystemSleep:
4099            if ([fDefaults boolForKey: @"SleepPrevent"])
4100            {
4101                //prevent idle sleep unless no torrents are active
4102                for (Torrent * torrent in fTorrents)
4103                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
4104                    {
4105                        IOCancelPowerChange(fRootPort, (long) messageArgument);
4106                        return;
4107                    }
4108            }
4109           
4110            IOAllowPowerChange(fRootPort, (long) messageArgument);
4111            break;
4112
4113        case kIOMessageSystemHasPoweredOn:
4114            //resume sleeping transfers after we wake up
4115            for (Torrent * torrent in fTorrents)
4116                [torrent wakeUp];
4117            break;
4118    }
4119}
4120
4121- (NSMenu *) applicationDockMenu: (NSApplication *) sender
4122{
4123    NSInteger seeding = 0, downloading = 0;
4124    for (Torrent * torrent in fTorrents)
4125    {
4126        if ([torrent isSeeding])
4127            seeding++;
4128        else if ([torrent isActive])
4129            downloading++;
4130        else;
4131    }
4132   
4133    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
4134            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
4135   
4136    BOOL hasSeparator = seedingItem || downloadingItem;
4137   
4138    if (seeding > 0)
4139    {
4140        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
4141        if (!seedingItem)
4142        {
4143            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
4144            [seedingItem setTag: DOCK_SEEDING_TAG];
4145            [fDockMenu insertItem: seedingItem atIndex: 0];
4146        }
4147        else
4148            [seedingItem setTitle: title];
4149    }
4150    else
4151    {
4152        if (seedingItem)
4153            [fDockMenu removeItem: seedingItem];
4154    }
4155   
4156    if (downloading > 0)
4157    {
4158        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
4159        if (!downloadingItem)
4160        {
4161            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
4162            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
4163            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
4164        }
4165        else
4166            [downloadingItem setTitle: title];
4167    }
4168    else
4169    {
4170        if (downloadingItem)
4171            [fDockMenu removeItem: downloadingItem];
4172    }
4173   
4174    if (seeding > 0 || downloading > 0)
4175    {
4176        if (!hasSeparator)
4177            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: (seeding > 0 && downloading > 0) ? 2 : 1];
4178    }
4179    else
4180    {
4181        if (hasSeparator)
4182            [fDockMenu removeItemAtIndex: 0];
4183    }
4184   
4185    return fDockMenu;
4186}
4187
4188- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
4189{
4190    //if auto size is enabled, the current frame shouldn't need to change
4191    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
4192   
4193    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
4194    return frame;
4195}
4196
4197- (void) setWindowSizeToFit
4198{
4199    if ([fDefaults boolForKey: @"AutoSize"])
4200    {
4201        NSScrollView * scrollView = [fTableView enclosingScrollView];
4202       
4203        [scrollView setHasVerticalScroller: NO];
4204        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
4205        [scrollView setHasVerticalScroller: YES];
4206       
4207        //hack to ensure scrollbars don't disappear after resizing
4208        if (![NSApp isOnSnowLeopardOrBetter])
4209        {
4210            [scrollView setAutohidesScrollers: NO];
4211            [scrollView setAutohidesScrollers: YES];
4212        }
4213    }
4214}
4215
4216- (NSRect) sizedWindowFrame
4217{
4218    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
4219                    ? [fDisplayedTorrents count] : 0;
4220   
4221    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4222                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4223                        - [[fTableView enclosingScrollView] frame].size.height;
4224   
4225    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4226}
4227
4228- (void) resizeFilterBar
4229{
4230    //replace all buttons
4231    [fNoFilterButton sizeToFit];
4232    [fActiveFilterButton sizeToFit];
4233    [fDownloadFilterButton sizeToFit];
4234    [fSeedFilterButton sizeToFit];
4235    [fPauseFilterButton sizeToFit];
4236   
4237    NSRect allRect = [fNoFilterButton frame];
4238    NSRect activeRect = [fActiveFilterButton frame];
4239    NSRect downloadRect = [fDownloadFilterButton frame];
4240    NSRect seedRect = [fSeedFilterButton frame];
4241    NSRect pauseRect = [fPauseFilterButton frame];
4242   
4243    //size search filter to not overlap buttons
4244    NSRect searchFrame = [fSearchFilterField frame];
4245    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
4246    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
4247   
4248    //make sure it is not too long
4249    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
4250    {
4251        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
4252        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
4253    }
4254    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
4255    {
4256        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
4257        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
4258       
4259        //calculate width the buttons can take up
4260        const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x;
4261        const CGFloat currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect)
4262                                        + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons
4263        const CGFloat ratio = allowedWidth / currentWidth;
4264       
4265        //decrease button widths proportionally
4266        allRect.size.width  = NSWidth(allRect) * ratio;
4267        activeRect.size.width = NSWidth(activeRect) * ratio;
4268        downloadRect.size.width = NSWidth(downloadRect) * ratio;
4269        seedRect.size.width = NSWidth(seedRect) * ratio;
4270        pauseRect.size.width = NSWidth(pauseRect) * ratio;
4271    }
4272    else;
4273   
4274    activeRect.origin.x = NSMaxX(allRect) + 1.0;
4275    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
4276    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4277    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4278   
4279    [fNoFilterButton setFrame: allRect];
4280    [fActiveFilterButton setFrame: activeRect];
4281    [fDownloadFilterButton setFrame: downloadRect];
4282    [fSeedFilterButton setFrame: seedRect];
4283    [fPauseFilterButton setFrame: pauseRect];
4284   
4285    [fSearchFilterField setFrame: searchFrame];
4286}
4287
4288- (void) updateForExpandCollape
4289{
4290    [self setWindowSizeToFit];
4291    [self setBottomCountText: YES];
4292}
4293
4294- (void) showMainWindow: (id) sender
4295{
4296    [fWindow makeKeyAndOrderFront: nil];
4297}
4298
4299- (void) windowDidBecomeMain: (NSNotification *) notification
4300{
4301    [fBadger clearCompleted];
4302    [self updateUI];
4303}
4304
4305- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
4306{
4307    //only resize horizontally if autosize is enabled
4308    if ([fDefaults boolForKey: @"AutoSize"])
4309        proposedFrameSize.height = [fWindow frame].size.height;
4310    return proposedFrameSize;
4311}
4312
4313- (void) windowDidResize: (NSNotification *) notification
4314{
4315    if (![fStatusBar isHidden])
4316        [self resizeStatusButton];
4317   
4318    if ([fFilterBar isHidden])
4319        return;
4320
4321    [self resizeFilterBar];
4322}
4323
4324- (void) applicationWillUnhide: (NSNotification *) notification
4325{
4326    [self updateUI];
4327}
4328
4329- (void) toggleQuickLook: (id) sender
4330{
4331    if (![NSApp isOnSnowLeopardOrBetter])
4332        return;
4333   
4334    if ([[QLPreviewPanelSL sharedPreviewPanel] isVisible])
4335        [[QLPreviewPanelSL sharedPreviewPanel] orderOut: nil];
4336    else
4337        [[QLPreviewPanelSL sharedPreviewPanel] makeKeyAndOrderFront: nil];
4338}
4339
4340- (void) linkHomepage: (id) sender
4341{
4342    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4343}
4344
4345- (void) linkForums: (id) sender
4346{
4347    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4348}
4349
4350- (void) linkTrac: (id) sender
4351{
4352    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4353}
4354
4355- (void) linkDonate: (id) sender
4356{
4357    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4358}
4359
4360- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4361{
4362    fUpdateInProgress = YES;
4363}
4364
4365- (NSDictionary *) registrationDictionaryForGrowl
4366{
4367    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4368                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4369    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4370                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4371}
4372
4373- (void) growlNotificationWasClicked: (id) clickContext
4374{
4375    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4376        return;
4377   
4378    NSString * type = [clickContext objectForKey: @"Type"], * location;
4379    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4380            && (location = [clickContext objectForKey: @"Location"]))
4381    {
4382        if ([NSApp isOnSnowLeopardOrBetter])
4383        {
4384            NSURL * file = [NSURL fileURLWithPath: location];
4385            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4386        }
4387        else
4388            [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4389    }
4390}
4391
4392- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4393{
4394    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4395   
4396    //get the torrent
4397    Torrent * torrent = nil;
4398    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4399    {
4400        for (torrent in fTorrents)
4401            if (torrentStruct == [torrent torrentStruct])
4402            {
4403                [torrent retain];
4404                break;
4405            }
4406       
4407        if (!torrent)
4408        {
4409            [pool drain];
4410           
4411            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4412            return;
4413        }
4414    }
4415   
4416    switch (type)
4417    {
4418        case TR_RPC_TORRENT_ADDED:
4419            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4420                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4421            break;
4422       
4423        case TR_RPC_TORRENT_STARTED:
4424        case TR_RPC_TORRENT_STOPPED:
4425            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4426            break;
4427       
4428        case TR_RPC_TORRENT_REMOVING:
4429            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4430            break;
4431       
4432        case TR_RPC_TORRENT_CHANGED:
4433            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4434            break;
4435       
4436        case TR_RPC_TORRENT_MOVED:
4437            [self performSelectorOnMainThread: @selector(rpcMovedTorrent:) withObject: torrent waitUntilDone: NO];
4438            break;
4439       
4440        case TR_RPC_SESSION_CHANGED:
4441            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4442            break;
4443       
4444        default:
4445            NSAssert1(NO, @"Unknown RPC command received: %d", type);
4446            [torrent release];
4447    }
4448   
4449    [pool drain];
4450}
4451
4452- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4453{
4454    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4455    [torrentStructPtr release];
4456   
4457    NSString * location = nil;
4458    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4459        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4460   
4461    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4462   
4463    [torrent update];
4464    [fTorrents addObject: torrent];
4465    [torrent release];
4466   
4467    [self updateTorrentsInQueue];
4468}
4469
4470- (void) rpcRemoveTorrent: (Torrent *) torrent
4471{
4472    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4473    [torrent release];
4474}
4475
4476- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4477{
4478    [torrent update];
4479    [torrent release];
4480   
4481    [self updateUI];
4482    [self applyFilter: nil];
4483    [self updateTorrentHistory];
4484}
4485
4486- (void) rpcChangedTorrent: (Torrent *) torrent
4487{
4488    [torrent update];
4489   
4490    if ([[fTableView selectedTorrents] containsObject: torrent])
4491    {
4492        [fInfoController updateInfoStats]; //this will reload the file table
4493        [fInfoController updateOptions];
4494    }
4495   
4496    [torrent release];
4497}
4498
4499- (void) rpcMovedTorrent: (Torrent *) torrent
4500{
4501    [torrent update];
4502    [torrent updateTimeMachineExclude];
4503   
4504    if ([[fTableView selectedTorrents] containsObject: torrent])
4505        [fInfoController updateInfoStats];
4506   
4507    [torrent release];
4508}
4509
4510@end
Note: See TracBrowser for help on using the repository browser.