source: trunk/macosx/Controller.m @ 11433

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

#3613 run a script when download completes - patch by Alexander Courtis

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