source: trunk/macosx/Controller.m @ 11640

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

replace the "Reverse Sort Order" menu item with "Ascending" and "Descending" menu items

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