source: trunk/macosx/Controller.m @ 11621

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

separate the code for the filter and status bars

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