source: trunk/macosx/Controller.m @ 11453

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

experiment for #3788 Adjust the status and filter bars' colors; make main window draggable

  • Property svn:keywords set to Date Rev Author Id
File size: 166.6 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 11453 2010-12-04 03:55:36Z livings124 $
3 *
4 * Copyright (c) 2005-2010 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import <IOKit/IOMessage.h>
26#import <IOKit/pwr_mgt/IOPMLib.h>
27#import <Carbon/Carbon.h>
28
29#import "Controller.h"
30#import "Torrent.h"
31#import "TorrentGroup.h"
32#import "TorrentTableView.h"
33#import "CreatorWindowController.h"
34#import "StatsWindowController.h"
35#import "InfoWindowController.h"
36#import "PrefsController.h"
37#import "GroupsController.h"
38#import "AboutWindowController.h"
39#import "AddWindowController.h"
40#import "AddMagnetWindowController.h"
41#import "MessageWindowController.h"
42#import "ButtonToolbarItem.h"
43#import "GroupToolbarItem.h"
44#import "ToolbarSegmentedCell.h"
45#import "BlocklistDownloader.h"
46#import "StatusBarView.h"
47#import "FilterButton.h"
48#import "BonjourController.h"
49#import "Badger.h"
50#import "DragOverlayWindow.h"
51#import "NSApplicationAdditions.h"
52#import "NSStringAdditions.h"
53#import "ExpandedPathToPathTransformer.h"
54#import "ExpandedPathToIconTransformer.h"
55
56#import "transmission.h"
57#import "bencode.h"
58#import "utils.h"
59
60#import "UKKQueue.h"
61#import <Sparkle/Sparkle.h>
62
63#define TOOLBAR_CREATE                  @"Toolbar Create"
64#define TOOLBAR_OPEN_FILE               @"Toolbar Open"
65#define TOOLBAR_OPEN_WEB                @"Toolbar Open Web"
66#define TOOLBAR_REMOVE                  @"Toolbar Remove"
67#define TOOLBAR_INFO                    @"Toolbar Info"
68#define TOOLBAR_PAUSE_ALL               @"Toolbar Pause All"
69#define TOOLBAR_RESUME_ALL              @"Toolbar Resume All"
70#define TOOLBAR_PAUSE_RESUME_ALL        @"Toolbar Pause / Resume All"
71#define TOOLBAR_PAUSE_SELECTED          @"Toolbar Pause Selected"
72#define TOOLBAR_RESUME_SELECTED         @"Toolbar Resume Selected"
73#define TOOLBAR_PAUSE_RESUME_SELECTED   @"Toolbar Pause / Resume Selected"
74#define TOOLBAR_FILTER                  @"Toolbar Toggle Filter"
75#define TOOLBAR_QUICKLOOK               @"Toolbar QuickLook"
76
77typedef enum
78{
79    TOOLBAR_PAUSE_TAG = 0,
80    TOOLBAR_RESUME_TAG = 1
81} toolbarGroupTag;
82
83#define SORT_DATE       @"Date"
84#define SORT_NAME       @"Name"
85#define SORT_STATE      @"State"
86#define SORT_PROGRESS   @"Progress"
87#define SORT_TRACKER    @"Tracker"
88#define SORT_ORDER      @"Order"
89#define SORT_ACTIVITY   @"Activity"
90
91typedef enum
92{
93    SORT_ORDER_TAG = 0,
94    SORT_DATE_TAG = 1,
95    SORT_NAME_TAG = 2,
96    SORT_PROGRESS_TAG = 3,
97    SORT_STATE_TAG = 4,
98    SORT_TRACKER_TAG = 5,
99    SORT_ACTIVITY_TAG = 6
100} sortTag;
101
102#define FILTER_NONE     @"None"
103#define FILTER_ACTIVE   @"Active"
104#define FILTER_DOWNLOAD @"Download"
105#define FILTER_SEED     @"Seed"
106#define FILTER_PAUSE    @"Pause"
107
108#define FILTER_TYPE_NAME    @"Name"
109#define FILTER_TYPE_TRACKER @"Tracker"
110
111#define FILTER_TYPE_TAG_NAME    401
112#define FILTER_TYPE_TAG_TRACKER 402
113
114#define GROUP_FILTER_ALL_TAG    -2
115
116#define STATUS_RATIO_TOTAL      @"RatioTotal"
117#define STATUS_RATIO_SESSION    @"RatioSession"
118#define STATUS_TRANSFER_TOTAL   @"TransferTotal"
119#define STATUS_TRANSFER_SESSION @"TransferSession"
120
121typedef enum
122{
123    STATUS_RATIO_TOTAL_TAG = 0,
124    STATUS_RATIO_SESSION_TAG = 1,
125    STATUS_TRANSFER_TOTAL_TAG = 2,
126    STATUS_TRANSFER_SESSION_TAG = 3
127} statusTag;
128
129#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
130#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
131#define GROWL_AUTO_ADD          @"Torrent Auto Added"
132#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
133
134#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
135
136#define ROW_HEIGHT_REGULAR      62.0
137#define ROW_HEIGHT_SMALL        22.0
138#define WINDOW_REGULAR_WIDTH    468.0
139
140#define SEARCH_FILTER_MIN_WIDTH 48.0
141#define SEARCH_FILTER_MAX_WIDTH 95.0
142
143#define UPDATE_UI_SECONDS   1.0
144
145#define DOCK_SEEDING_TAG        101
146#define DOCK_DOWNLOADING_TAG    102
147
148#define TRANSFER_PLIST  @"/Library/Application Support/Transmission/Transfers.plist"
149
150#define WEBSITE_URL @"http://www.transmissionbt.com/"
151#define FORUM_URL   @"http://forum.transmissionbt.com/"
152#define TRAC_URL   @"http://trac.transmissionbt.com/"
153#define DONATE_URL  @"http://www.transmissionbt.com/donate.php"
154
155#define DONATE_NAG_TIME (60 * 60 * 24 * 7)
156
157static void altSpeedToggledCallback(tr_session * handle UNUSED, tr_bool active, tr_bool byUser, void * controller)
158{
159    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: [[NSNumber alloc] initWithBool: active], @"Active",
160                                [[NSNumber alloc] initWithBool: byUser], @"ByUser", nil];
161    [(Controller *)controller performSelectorOnMainThread: @selector(altSpeedToggledCallbackIsLimited:)
162        withObject: dict waitUntilDone: NO];
163}
164
165static tr_rpc_callback_status rpcCallback(tr_session * handle UNUSED, tr_rpc_callback_type type, struct tr_torrent * torrentStruct,
166                                            void * controller)
167{
168    [(Controller *)controller rpcCallback: type forTorrentStruct: torrentStruct];
169    return TR_RPC_NOREMOVE; //we'll do the remove manually
170}
171
172static void sleepCallback(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
173{
174    [(Controller *)controller sleepCallback: messageType argument: messageArgument];
175}
176
177@implementation Controller
178
179+ (void) initialize
180{
181    //make sure another Transmission.app isn't running already
182    BOOL othersRunning = NO;
183   
184    if ([NSApp isOnSnowLeopardOrBetter])
185    {
186        NSArray * apps = [NSRunningApplicationSL runningApplicationsWithBundleIdentifier: [[NSBundle mainBundle] bundleIdentifier]];
187        othersRunning = [apps count] > 1;
188    }
189    else
190    {
191        NSString * bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
192        const int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
193
194        for (NSDictionary * dic in [[NSWorkspace sharedWorkspace] launchedApplications])
195        {
196            if ([[dic objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]
197                    && [[dic objectForKey: @"NSApplicationProcessIdentifier"] intValue] != processIdentifier)
198                othersRunning = YES;
199        }
200    }
201   
202    if (othersRunning)
203    {
204        NSAlert * alert = [[NSAlert alloc] init];
205        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Transmission already running alert -> button")];
206        [alert setMessageText: NSLocalizedString(@"Transmission is already running.",
207                                                "Transmission already running alert -> title")];
208        [alert setInformativeText: NSLocalizedString(@"There is already a copy of Transmission running. "
209            "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message")];
210        [alert setAlertStyle: NSCriticalAlertStyle];
211       
212        [alert runModal];
213        [alert release];
214       
215        //kill ourselves right away
216        exit(0);
217    }
218   
219    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
220        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
221   
222    //set custom value transformers
223    ExpandedPathToPathTransformer * pathTransformer = [[[ExpandedPathToPathTransformer alloc] init] autorelease];
224    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
225   
226    ExpandedPathToIconTransformer * iconTransformer = [[[ExpandedPathToIconTransformer alloc] init] autorelease];
227    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
228   
229    //cover our asses
230    if ([[NSUserDefaults standardUserDefaults] boolForKey: @"WarningLegal"])
231    {
232        NSAlert * alert = [[NSAlert alloc] init];
233        [alert addButtonWithTitle: NSLocalizedString(@"I Accept", "Legal alert -> button")];
234        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Legal alert -> button")];
235        [alert setMessageText: NSLocalizedString(@"Welcome to Transmission", "Legal alert -> title")];
236        [alert setInformativeText: NSLocalizedString(@"Transmission is a file-sharing program."
237            " When you run a torrent, its data will be made available to others by means of upload."
238            " You and you alone are fully responsible for exercising proper judgement and abiding by your local laws.",
239            "Legal alert -> message")];
240        [alert setAlertStyle: NSInformationalAlertStyle];
241       
242        if ([alert runModal] == NSAlertSecondButtonReturn)
243            exit(0);
244        [alert release];
245       
246        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningLegal"];
247    }
248}
249
250- (id) init
251{
252    if ((self = [super init]))
253    {
254        fDefaults = [NSUserDefaults standardUserDefaults];
255       
256        //checks for old version speeds of -1
257        if ([fDefaults integerForKey: @"UploadLimit"] < 0)
258        {
259            [fDefaults removeObjectForKey: @"UploadLimit"];
260            [fDefaults setBool: NO forKey: @"CheckUpload"];
261        }
262        if ([fDefaults integerForKey: @"DownloadLimit"] < 0)
263        {
264            [fDefaults removeObjectForKey: @"DownloadLimit"];
265            [fDefaults setBool: NO forKey: @"CheckDownload"];
266        }
267       
268        tr_benc settings;
269        tr_bencInitDict(&settings, 41);
270        const char * configDir = tr_getDefaultConfigDir("Transmission");
271        tr_sessionGetDefaultSettings(configDir, &settings);
272       
273        const BOOL usesSpeedLimitSched = [fDefaults boolForKey: @"SpeedLimitAuto"];
274        if (!usesSpeedLimitSched)
275            tr_bencDictAddBool(&settings, TR_PREFS_KEY_ALT_SPEED_ENABLED, [fDefaults boolForKey: @"SpeedLimit"]);
276       
277        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_UP_KBps, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]);
278        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_DOWN_KBps, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]);
279       
280        tr_bencDictAddBool(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED, [fDefaults boolForKey: @"SpeedLimitAuto"]);
281        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN, [PrefsController dateToTimeSum:
282                                                                            [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]]);
283        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_END, [PrefsController dateToTimeSum:
284                                                                            [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]]);
285        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_DAY, [fDefaults integerForKey: @"SpeedLimitAutoDay"]);
286       
287        tr_bencDictAddInt(&settings, TR_PREFS_KEY_DSPEED_KBps, [fDefaults integerForKey: @"DownloadLimit"]);
288        tr_bencDictAddBool(&settings, TR_PREFS_KEY_DSPEED_ENABLED, [fDefaults boolForKey: @"CheckDownload"]);
289        tr_bencDictAddInt(&settings, TR_PREFS_KEY_USPEED_KBps, [fDefaults integerForKey: @"UploadLimit"]);
290        tr_bencDictAddBool(&settings, TR_PREFS_KEY_USPEED_ENABLED, [fDefaults boolForKey: @"CheckUpload"]);
291       
292        //hidden prefs
293        if ([fDefaults objectForKey: @"BindAddressIPv4"])
294            tr_bencDictAddStr(&settings, TR_PREFS_KEY_BIND_ADDRESS_IPV4, [[fDefaults stringForKey: @"BindAddressIPv4"] UTF8String]);
295        if ([fDefaults objectForKey: @"BindAddressIPv6"])
296            tr_bencDictAddStr(&settings, TR_PREFS_KEY_BIND_ADDRESS_IPV6, [[fDefaults stringForKey: @"BindAddressIPv6"] UTF8String]);
297       
298        tr_bencDictAddBool(&settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, [fDefaults boolForKey: @"BlocklistNew"]);
299        if ([fDefaults objectForKey: @"BlocklistURL"])
300            tr_bencDictAddStr(&settings, TR_PREFS_KEY_BLOCKLIST_URL, [[fDefaults stringForKey: @"BlocklistURL"] UTF8String]);
301        tr_bencDictAddBool(&settings, TR_PREFS_KEY_DHT_ENABLED, [fDefaults boolForKey: @"DHTGlobal"]);
302        tr_bencDictAddStr(&settings, TR_PREFS_KEY_DOWNLOAD_DIR, [[[fDefaults stringForKey: @"DownloadFolder"]
303                                                                    stringByExpandingTildeInPath] UTF8String]);
304        tr_bencDictAddInt(&settings, TR_PREFS_KEY_IDLE_LIMIT, [fDefaults integerForKey: @"IdleLimitMinutes"]);
305        tr_bencDictAddBool(&settings, TR_PREFS_KEY_IDLE_LIMIT_ENABLED, [fDefaults boolForKey: @"IdleLimitCheck"]);
306        tr_bencDictAddStr(&settings, TR_PREFS_KEY_INCOMPLETE_DIR, [[[fDefaults stringForKey: @"IncompleteDownloadFolder"]
307                                                                    stringByExpandingTildeInPath] UTF8String]);
308        tr_bencDictAddBool(&settings, TR_PREFS_KEY_INCOMPLETE_DIR_ENABLED, [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]);
309        tr_bencDictAddBool(&settings, TR_PREFS_KEY_LPD_ENABLED, [fDefaults boolForKey: @"LocalPeerDiscoveryGlobal"]);
310        tr_bencDictAddInt(&settings, TR_PREFS_KEY_MSGLEVEL, TR_MSG_DBG);
311        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, [fDefaults integerForKey: @"PeersTotal"]);
312        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_TORRENT, [fDefaults integerForKey: @"PeersTorrent"]);
313       
314        const BOOL randomPort = [fDefaults boolForKey: @"RandomPort"];
315        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, randomPort);
316        if (!randomPort)
317            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_PORT, [fDefaults integerForKey: @"BindPort"]);
318       
319        //hidden pref
320        if ([fDefaults objectForKey: @"PeerSocketTOS"])
321            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_SOCKET_TOS, [fDefaults integerForKey: @"PeerSocketTOS"]);
322       
323        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PEX_ENABLED, [fDefaults boolForKey: @"PEXGlobal"]);
324        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PORT_FORWARDING, [fDefaults boolForKey: @"NatTraversal"]);
325        tr_bencDictAddReal(&settings, TR_PREFS_KEY_RATIO, [fDefaults floatForKey: @"RatioLimit"]);
326        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RATIO_ENABLED, [fDefaults boolForKey: @"RatioCheck"]);
327        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RENAME_PARTIAL_FILES, [fDefaults boolForKey: @"RenamePartialFiles"]);
328        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED,  [fDefaults boolForKey: @"RPCAuthorize"]);
329        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_ENABLED,  [fDefaults boolForKey: @"RPC"]);
330        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_PORT, [fDefaults integerForKey: @"RPCPort"]);
331        tr_bencDictAddStr(&settings, TR_PREFS_KEY_RPC_USERNAME,  [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
332        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_WHITELIST_ENABLED,  [fDefaults boolForKey: @"RPCUseWhitelist"]);
333        tr_bencDictAddBool(&settings, TR_PREFS_KEY_START, [fDefaults boolForKey: @"AutoStartDownload"]);
334        tr_bencDictAddBool(&settings, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_ENABLED, [fDefaults boolForKey: @"DoneScriptEnabled"]);
335        tr_bencDictAddStr(&settings, TR_PREFS_KEY_SCRIPT_TORRENT_DONE_FILENAME, [[fDefaults stringForKey: @"DoneScriptPath"] UTF8String]);
336       
337        tr_formatter_size_init([NSApp isOnSnowLeopardOrBetter] ? 1000 : 1024,
338                                    [NSLocalizedString(@"KB", "File size - kilobytes") UTF8String],
339                                    [NSLocalizedString(@"MB", "File size - megabytes") UTF8String],
340                                    [NSLocalizedString(@"GB", "File size - gigabytes") UTF8String],
341                                    [NSLocalizedString(@"TB", "File size - terabytes") UTF8String]);
342
343        tr_formatter_speed_init([NSApp isOnSnowLeopardOrBetter] ? 1000 : 1024,
344                                    [NSLocalizedString(@"KB/s", "Transfer speed (kilobytes per second)") UTF8String],
345                                    [NSLocalizedString(@"MB/s", "Transfer speed (megabytes per second)") UTF8String],
346                                    [NSLocalizedString(@"GB/s", "Transfer speed (gigabytes per second)") UTF8String],
347                                    [NSLocalizedString(@"TB/s", "Transfer speed (terabytes per second)") UTF8String]); //why not?
348
349        tr_formatter_mem_init(1024, [NSLocalizedString(@"KB", "Memory size - kilobytes") UTF8String],
350                                    [NSLocalizedString(@"MB", "Memory size - megabytes") UTF8String],
351                                    [NSLocalizedString(@"GB", "Memory size - gigabytes") UTF8String],
352                                    [NSLocalizedString(@"TB", "Memory size - terabytes") UTF8String]);
353       
354        fLib = tr_sessionInit("macosx", configDir, YES, &settings);
355        tr_bencFree(&settings);
356       
357        [NSApp setDelegate: self];
358       
359        //register for magnet URLs (has to be in init)
360        [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:)
361            forEventClass: kInternetEventClass andEventID: kAEGetURL];
362       
363        fTorrents = [[NSMutableArray alloc] init];
364        fDisplayedTorrents = [[NSMutableArray alloc] init];
365       
366        fInfoController = [[InfoWindowController alloc] init];
367       
368        [PrefsController setHandle: fLib];
369        fPrefsController = [[PrefsController alloc] init];
370       
371        fQuitting = NO;
372        fSoundPlaying = NO;
373       
374        tr_sessionSetAltSpeedFunc(fLib, altSpeedToggledCallback, self);
375        if (usesSpeedLimitSched)
376            [fDefaults setBool: tr_sessionUsesAltSpeed(fLib) forKey: @"SpeedLimit"];
377       
378        tr_sessionSetRPCCallback(fLib, rpcCallback, self);
379       
380        [GrowlApplicationBridge setGrowlDelegate: self];
381       
382        [[UKKQueue sharedFileWatcher] setDelegate: self];
383       
384        [[SUUpdater sharedUpdater] setDelegate: self];
385        fUpdateInProgress = NO;
386       
387        fPauseOnLaunch = (GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0;
388    }
389    return self;
390}
391
392- (void) awakeFromNib
393{
394    [fFilterBar setIsFilter: YES];
395   
396    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"TRMainToolbar"];
397    [toolbar setDelegate: self];
398    [toolbar setAllowsUserCustomization: YES];
399    [toolbar setAutosavesConfiguration: YES];
400    [toolbar setDisplayMode: NSToolbarDisplayModeIconOnly];
401    [fWindow setToolbar: toolbar];
402    [toolbar release];
403   
404    [fWindow setDelegate: self]; //do manually to avoid placement issue
405   
406    [fWindow makeFirstResponder: fTableView];
407    [fWindow setExcludedFromWindowsMenu: YES];
408   
409    //set table size
410    if ([fDefaults boolForKey: @"SmallView"])
411        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
412   
413    #warning remove once localizations are updated for 2.2
414    [fActionButton setBordered: NO];
415    [fActionButton setFrame: NSMakeRect(6.0, 2.0, 36.0, 18.0)];
416    [fSpeedLimitButton setBordered: NO];
417    [fSpeedLimitButton setFrame: NSMakeRect(45.0, 2.0, 36.0, 18.0)];
418   
419    //window min height
420    NSSize contentMinSize = [fWindow contentMinSize];
421    contentMinSize.height = [[fWindow contentView] frame].size.height - [[fTableView enclosingScrollView] frame].size.height
422                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
423    [fWindow setContentMinSize: contentMinSize];
424    [fWindow setContentBorderThickness: NSMinY([[fTableView enclosingScrollView] frame]) forEdge: NSMinYEdge];
425    [fWindow setMovableByWindowBackground: YES];
426   
427    [[fTotalDLField cell] setBackgroundStyle: NSBackgroundStyleRaised];
428    [[fTotalULField cell] setBackgroundStyle: NSBackgroundStyleRaised];
429    [[fTotalTorrentsField cell] setBackgroundStyle: NSBackgroundStyleRaised];
430   
431    [self updateGroupsFilterButton];
432   
433    //set up filter bar
434    NSView * contentView = [fWindow contentView];
435    NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
436    [fFilterBar setHidden: YES];
437   
438    NSRect filterBarFrame = [fFilterBar frame];
439    filterBarFrame.size.width = windowSize.width;
440    [fFilterBar setFrame: filterBarFrame];
441   
442    [contentView addSubview: fFilterBar];
443    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
444
445    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
446   
447    //set up status bar
448    [fStatusBar setHidden: YES];
449   
450    [self updateSpeedFieldsToolTips];
451   
452    NSRect statusBarFrame = [fStatusBar frame];
453    statusBarFrame.size.width = windowSize.width;
454    [fStatusBar setFrame: statusBarFrame];
455   
456    [contentView addSubview: fStatusBar];
457    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
458    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
459   
460    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
461                                "Main window -> 1st bottom left button (action) tooltip")];
462    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
463                                "Main window -> 2nd bottom left button (turtle) tooltip")];
464   
465    [fTableView registerForDraggedTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE]];
466    [fWindow registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType, NSURLPboardType, nil]];
467
468    //register for sleep notifications
469    IONotificationPortRef notify;
470    io_object_t iterator;
471    if ((fRootPort = IORegisterForSystemPower(self, & notify, sleepCallback, &iterator)))
472        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
473    else
474        NSLog(@"Could not IORegisterForSystemPower");
475   
476    //load previous transfers
477    NSArray * history = [NSArray arrayWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST]];
478   
479    if (!history)
480    {
481        //old version saved transfer info in prefs file
482        if ((history = [fDefaults arrayForKey: @"History"]))
483            [fDefaults removeObjectForKey: @"History"];
484    }
485   
486    if (history)
487    {
488        for (NSDictionary * historyItem in history)
489        {
490            Torrent * torrent;
491            if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib forcePause: fPauseOnLaunch]))
492            {
493                [fTorrents addObject: torrent];
494                [torrent release];
495            }
496        }
497    }
498   
499    //set filter
500    NSString * filterType = [fDefaults stringForKey: @"Filter"];
501   
502    NSButton * currentFilterButton;
503    if ([filterType isEqualToString: FILTER_ACTIVE])
504        currentFilterButton = fActiveFilterButton;
505    else if ([filterType isEqualToString: FILTER_PAUSE])
506        currentFilterButton = fPauseFilterButton;
507    else if ([filterType isEqualToString: FILTER_SEED])
508        currentFilterButton = fSeedFilterButton;
509    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
510        currentFilterButton = fDownloadFilterButton;
511    else
512    {
513        //safety
514        if (![filterType isEqualToString: FILTER_NONE])
515            [fDefaults setObject: FILTER_NONE forKey: @"Filter"];
516        currentFilterButton = fNoFilterButton;
517    }
518    [currentFilterButton setState: NSOnState];
519   
520    //set filter search type
521    NSString * filterSearchType = [fDefaults stringForKey: @"FilterSearchType"];
522   
523    NSMenu * filterSearchMenu = [[fSearchFilterField cell] searchMenuTemplate];
524    NSString * filterSearchTypeTitle;
525    if ([filterSearchType isEqualToString: FILTER_TYPE_TRACKER])
526        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_TRACKER] title];
527    else
528    {
529        //safety
530        if (![filterType isEqualToString: FILTER_TYPE_NAME])
531            [fDefaults setObject: FILTER_TYPE_NAME forKey: @"FilterSearchType"];
532        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_NAME] title];
533    }
534    [[fSearchFilterField cell] setPlaceholderString: filterSearchTypeTitle];
535   
536    fBadger = [[Badger alloc] initWithLib: fLib];
537   
538    //observe notifications
539    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
540   
541    [nc addObserver: self selector: @selector(updateUI)
542                    name: @"UpdateUI" object: nil];
543   
544    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
545                    name: @"TorrentFinishedDownloading" object: nil];
546   
547    [nc addObserver: self selector: @selector(torrentRestartedDownloading:)
548                    name: @"TorrentRestartedDownloading" object: nil];
549   
550    [nc addObserver: self selector: @selector(torrentFinishedSeeding:)
551                    name: @"TorrentFinishedSeeding" object: nil];
552   
553    //avoids need of setting delegate
554    [nc addObserver: self selector: @selector(torrentTableViewSelectionDidChange:)
555                    name: NSOutlineViewSelectionDidChangeNotification object: fTableView];
556   
557    [nc addObserver: self selector: @selector(changeAutoImport)
558                    name: @"AutoImportSettingChange" object: nil];
559   
560    [nc addObserver: self selector: @selector(setWindowSizeToFit)
561                    name: @"AutoSizeSettingChange" object: nil];
562   
563    [nc addObserver: self selector: @selector(updateForExpandCollape)
564                    name: @"OutlineExpandCollapse" object: nil];
565   
566    [nc addObserver: fWindow selector: @selector(makeKeyWindow)
567                    name: @"MakeWindowKey" object: nil];
568   
569    [nc addObserver: self selector: @selector(updateTorrentsInQueue)
570                    name: @"UpdateQueue" object: nil];
571   
572    //open newly created torrent file
573    [nc addObserver: self selector: @selector(beginCreateFile:)
574                    name: @"BeginCreateTorrentFile" object: nil];
575   
576    //open newly created torrent file
577    [nc addObserver: self selector: @selector(openCreatedFile:)
578                    name: @"OpenCreatedTorrentFile" object: nil];
579   
580    //update when groups change
581    [nc addObserver: self selector: @selector(updateGroupsFilters:)
582                    name: @"UpdateGroups" object: nil];
583   
584    //update when speed limits are changed
585    [nc addObserver: self selector: @selector(updateSpeedFieldsToolTips)
586                    name: @"SpeedLimitUpdate" object: nil];
587
588    //timer to update the interface every second
589    [self updateUI];
590    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
591                selector: @selector(updateUI) userInfo: nil repeats: YES];
592    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
593    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
594   
595    [self applyFilter: nil];
596   
597    [fWindow makeKeyAndOrderFront: nil];
598   
599    //can't be done earlier
600    if (![fFilterBar isHidden])
601        [self resizeFilterBar];
602   
603    if ([fDefaults boolForKey: @"InfoVisible"])
604        [self showInfo: nil];
605}
606
607- (void) applicationDidFinishLaunching: (NSNotification *) notification
608{
609    [NSApp setServicesProvider: self];
610   
611    //register for dock icon drags (has to be in applicationDidFinishLaunching: to work)
612    [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:)
613        forEventClass: kCoreEventClass andEventID: kAEOpenContents];
614   
615    //auto importing
616    [self checkAutoImportDirectory];
617   
618    //registering the Web UI to Bonjour
619    if ([fDefaults boolForKey: @"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"])
620        [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]];
621   
622    //shamelessly ask for donations
623    if ([fDefaults boolForKey: @"WarningDonate"])
624    {
625        tr_session_stats stats;
626        tr_sessionGetCumulativeStats(fLib, &stats);
627        const BOOL firstLaunch = stats.sessionCount <= 1;
628       
629        NSDate * lastDonateDate = [fDefaults objectForKey: @"DonateAskDate"];
630        const BOOL timePassed = !lastDonateDate || (-1 * [lastDonateDate timeIntervalSinceNow]) >= DONATE_NAG_TIME;
631       
632        if (!firstLaunch && timePassed)
633        {
634            [fDefaults setObject: [NSDate date] forKey: @"DonateAskDate"];
635           
636            NSAlert * alert = [[NSAlert alloc] init];
637            [alert setMessageText: NSLocalizedString(@"Support open-source indie software", "Donation beg -> title")];
638           
639            NSString * donateMessage = [NSString stringWithFormat: @"%@\n\n%@",
640                NSLocalizedString(@"Transmission is a full-featured torrent application."
641                    " A lot of time and effort have gone into development, coding, and refinement."
642                    " If you enjoy using it, please consider showing your love with a donation.", "Donation beg -> message"),
643                NSLocalizedString(@"Donate or not, there will be no difference to your torrenting experience.", "Donation beg -> message")];
644           
645            [alert setInformativeText: donateMessage];
646            [alert setAlertStyle: NSInformationalAlertStyle];
647           
648            [alert addButtonWithTitle: [NSLocalizedString(@"Donate", "Donation beg -> button") stringByAppendingEllipsis]];
649            NSButton * noDonateButton = [alert addButtonWithTitle: NSLocalizedString(@"Nope", "Donation beg -> button")];
650            [noDonateButton setKeyEquivalent: @"\e"]; //escape key
651           
652            const BOOL allowNeverAgain = lastDonateDate != nil; //hide the "don't show again" check the first time - give them time to try the app
653            [alert setShowsSuppressionButton: allowNeverAgain];
654            if (allowNeverAgain)
655                [[alert suppressionButton] setTitle: NSLocalizedString(@"Don't bug me about this ever again.", "Donation beg -> button")];
656           
657            const NSInteger donateResult = [alert runModal];
658            if (donateResult == NSAlertFirstButtonReturn)
659                [self linkDonate: self];
660           
661            if (allowNeverAgain)
662                [fDefaults setBool: ([[alert suppressionButton] state] != NSOnState) forKey: @"WarningDonate"];
663           
664            [alert release];
665        }
666    }
667}
668
669- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
670{
671    NSWindow * mainWindow = [NSApp mainWindow];
672    if (!mainWindow || ![mainWindow isVisible])
673        [fWindow makeKeyAndOrderFront: nil];
674   
675    return NO;
676}
677
678- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
679{
680    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
681    {
682        NSInteger active = 0, downloading = 0;
683        for (Torrent * torrent  in fTorrents)
684            if ([torrent isActive] && ![torrent isStalled])
685            {
686                active++;
687                if (![torrent allDownloaded])
688                    downloading++;
689            }
690       
691        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
692        {
693            NSString * message = active == 1
694                ? NSLocalizedString(@"There is an active transfer that will be paused on quit."
695                    " The transfer will automatically resume on the next launch.", "Confirm Quit panel -> message")
696                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers that will be paused on quit."
697                    " The transfers will automatically resume on the next launch.", "Confirm Quit panel -> message"), active];
698
699            NSBeginAlertSheet(NSLocalizedString(@"Are you sure you want to quit?", "Confirm Quit panel -> title"),
700                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
701                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
702                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
703            return NSTerminateLater;
704        }
705    }
706   
707    return NSTerminateNow;
708}
709
710- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
711{
712    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
713}
714
715- (void) applicationWillTerminate: (NSNotification *) notification
716{
717    fQuitting = YES;
718   
719    //stop the Bonjour service
720    [[BonjourController defaultController] stop];
721
722    //stop blocklist download
723    if ([BlocklistDownloader isRunning])
724        [[BlocklistDownloader downloader] cancelDownload];
725   
726    //stop timers and notification checking
727    [[NSNotificationCenter defaultCenter] removeObserver: self];
728   
729    [fTimer invalidate];
730   
731    if (fAutoImportTimer)
732    {   
733        if ([fAutoImportTimer isValid])
734            [fAutoImportTimer invalidate];
735        [fAutoImportTimer release];
736    }
737   
738    [fBadger setQuitting];
739   
740    //remove all torrent downloads
741    if (fPendingTorrentDownloads)
742    {
743        for (NSDictionary * downloadDict in fPendingTorrentDownloads)
744        {
745            NSURLDownload * download = [downloadDict objectForKey: @"Download"];
746            [download cancel];
747            [download release];
748        }
749        [fPendingTorrentDownloads release];
750    }
751   
752    //remember window states and close all windows
753    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
754   
755    const BOOL quickLookOpen = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
756                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
757    if (quickLookOpen)
758        [[QLPreviewPanelSL sharedPreviewPanel] updateController];
759   
760    for (NSWindow * window in [NSApp windows])
761        [window close];
762   
763    [self showStatusBar: NO animate: NO];
764    [self showFilterBar: NO animate: NO];
765   
766    //save history
767    [self updateTorrentHistory];
768    [fTableView saveCollapsedGroups];
769   
770    //remaining calls the same as dealloc
771    [fInfoController release];
772    [fMessageController release];
773    [fPrefsController release];
774   
775    [fTorrents release];
776    [fDisplayedTorrents release];
777   
778    [fOverlayWindow release];
779    [fBadger release];
780   
781    [fAutoImportedNames release];
782   
783    [fPreviewPanel release];
784   
785    //complete cleanup
786    tr_sessionClose(fLib);
787}
788
789- (void) handleOpenContentsEvent: (NSAppleEventDescriptor *) event replyEvent: (NSAppleEventDescriptor *) replyEvent
790{
791    NSString * urlString = nil;
792
793    NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject];
794    if ([directObject descriptorType] == typeAEList)
795    {
796        for (NSInteger i = 1; i <= [directObject numberOfItems]; i++)
797            if ((urlString = [[directObject descriptorAtIndex: i] stringValue]))
798                break;
799    }
800    else
801        urlString = [directObject stringValue];
802   
803    if (urlString)
804        [self openURL: urlString];
805}
806
807- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) suggestedName
808{
809    if ([[suggestedName pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
810    {
811        [download cancel];
812       
813        NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title"),
814            [NSString stringWithFormat: NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.",
815            "Download not a torrent -> message"), suggestedName,
816            [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]],
817            NSLocalizedString(@"OK", "Download not a torrent -> button"), nil, nil);
818       
819        [download release];
820    }
821    else
822        [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: [suggestedName lastPathComponent]]
823                    allowOverwrite: NO];
824}
825
826-(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path
827{
828    if (!fPendingTorrentDownloads)
829        fPendingTorrentDownloads = [[NSMutableDictionary alloc] init];
830   
831    [fPendingTorrentDownloads setObject: [NSDictionary dictionaryWithObjectsAndKeys:
832                    path, @"Path", download, @"Download", nil] forKey: [[download request] URL]];
833}
834
835- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error
836{
837    NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Torrent download error -> title"),
838        [NSString stringWithFormat: NSLocalizedString(@"The torrent could not be downloaded from %@: %@.",
839        "Torrent download failed -> message"),
840        [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
841        [error localizedDescription]], NSLocalizedString(@"OK", "Torrent download failed -> button"), nil, nil);
842   
843    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
844    if ([fPendingTorrentDownloads count] == 0)
845    {
846        [fPendingTorrentDownloads release];
847        fPendingTorrentDownloads = nil;
848    }
849   
850    [download release];
851}
852
853- (void) downloadDidFinish: (NSURLDownload *) download
854{
855    NSString * path = [[fPendingTorrentDownloads objectForKey: [[download request] URL]] objectForKey: @"Path"];
856   
857    [self openFiles: [NSArray arrayWithObject: path] addType: ADD_URL forcePath: nil];
858   
859    //delete the torrent file after opening
860    [[NSFileManager defaultManager] removeItemAtPath: path error: NULL];
861   
862    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
863    if ([fPendingTorrentDownloads count] == 0)
864    {
865        [fPendingTorrentDownloads release];
866        fPendingTorrentDownloads = nil;
867    }
868   
869    [download release];
870}
871
872- (void) application: (NSApplication *) app openFiles: (NSArray *) filenames
873{
874    [self openFiles: filenames addType: ADD_MANUAL forcePath: nil];
875}
876
877- (void) openFiles: (NSArray *) filenames addType: (addType) type forcePath: (NSString *) path
878{
879    BOOL deleteTorrentFile, canToggleDelete = NO;
880    switch (type)
881    {
882        case ADD_CREATED:
883            deleteTorrentFile = NO;
884            break;
885        case ADD_URL:
886            deleteTorrentFile = YES;
887            break;
888        default:
889            deleteTorrentFile = [fDefaults boolForKey: @"DeleteOriginalTorrent"];
890            canToggleDelete = YES;
891    }
892   
893    for (NSString * torrentPath in filenames)
894    {
895        //ensure torrent doesn't already exist
896        tr_ctor * ctor = tr_ctorNew(fLib);
897        tr_ctorSetMetainfoFromFile(ctor, [torrentPath UTF8String]);
898       
899        tr_info info;
900        const tr_parse_result result = tr_torrentParse(ctor, &info);
901        tr_ctorFree(ctor);
902       
903        if (result != TR_PARSE_OK)
904        {
905            if (result == TR_PARSE_DUPLICATE)
906                [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
907            else if (result == TR_PARSE_ERR)
908            {
909                if (type != ADD_AUTO)
910                    [self invalidOpenAlert: [torrentPath lastPathComponent]];
911            }
912            else
913                NSAssert2(NO, @"Unknown error code (%d) when attempting to open \"%@\"", result, torrentPath);
914           
915            tr_metainfoFree(&info);
916            continue;
917        }
918       
919        //determine download location
920        NSString * location;
921        BOOL lockDestination = NO; //don't override the location with a group location if it has a hardcoded path
922        if (path)
923        {
924            location = [path stringByExpandingTildeInPath];
925            lockDestination = YES;
926        }
927        else if ([fDefaults boolForKey: @"DownloadLocationConstant"])
928            location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
929        else if (type != ADD_URL)
930            location = [torrentPath stringByDeletingLastPathComponent];
931        else
932            location = nil;
933       
934        //determine to show the options window
935        const BOOL showWindow = type == ADD_SHOW_OPTIONS || ([fDefaults boolForKey: @"DownloadAsk"]
936                                    && (info.isMultifile || ![fDefaults boolForKey: @"DownloadAskMulti"])
937                                    && (type != ADD_AUTO || ![fDefaults boolForKey: @"DownloadAskManual"]));
938        tr_metainfoFree(&info);
939       
940        Torrent * torrent;
941        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath location: location
942                            deleteTorrentFile: showWindow ? NO : deleteTorrentFile lib: fLib]))
943            continue;
944       
945        //change the location if the group calls for it (this has to wait until after the torrent is created)
946        if (!lockDestination && [[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
947        {
948            location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
949            [torrent changeDownloadFolderBeforeUsing: location];
950        }
951       
952        //verify the data right away if it was newly created
953        if (type == ADD_CREATED)
954            [torrent resetCache];
955       
956        //add it to the "File -> Open Recent" menu
957        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
958       
959        //show the add window or add directly
960        if (showWindow || !location)
961        {
962            AddWindowController * addController = [[AddWindowController alloc] initWithTorrent: torrent destination: location
963                                                    lockDestination: lockDestination controller: self torrentFile: torrentPath
964                                                    deleteTorrent: deleteTorrentFile canToggleDelete: canToggleDelete];
965            [addController showWindow: self];
966        }
967        else
968        {
969            [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
970           
971            [torrent update];
972            [fTorrents addObject: torrent];
973            [torrent release];
974        }
975    }
976
977    [self updateTorrentsInQueue];
978}
979
980- (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add
981{
982    Torrent * torrent = [addController torrent];
983    [addController release];
984   
985    if (add)
986    {
987        [torrent update];
988        [fTorrents addObject: torrent];
989        [torrent release];
990       
991        [self updateTorrentsInQueue];
992    }
993    else
994    {
995        [torrent closeRemoveTorrent];
996        [torrent release];
997    }
998}
999
1000- (void) openMagnet: (NSString *) address
1001{
1002    tr_torrent * duplicateTorrent;
1003    if ((duplicateTorrent = tr_torrentFindFromMagnetLink(fLib, [address UTF8String])))
1004    {
1005        const tr_info * info = tr_torrentInfo(duplicateTorrent);
1006        NSString * name = (info != NULL && info->name != NULL) ? [NSString stringWithUTF8String: info->name] : nil;
1007        [self duplicateOpenMagnetAlert: address transferName: name];
1008        return;
1009    }
1010   
1011    //determine download location
1012    NSString * location = nil;
1013    if ([fDefaults boolForKey: @"DownloadLocationConstant"])
1014        location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
1015   
1016    Torrent * torrent;
1017    if (!(torrent = [[Torrent alloc] initWithMagnetAddress: address location: location lib: fLib]))
1018    {
1019        [self invalidOpenMagnetAlert: address];
1020        return;
1021    }
1022   
1023    //change the location if the group calls for it (this has to wait until after the torrent is created)
1024    if ([[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
1025    {
1026        location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
1027        [torrent changeDownloadFolderBeforeUsing: location];
1028    }
1029   
1030    if ([fDefaults boolForKey: @"MagnetOpenAsk"] || !location)
1031    {
1032        AddMagnetWindowController * addController = [[AddMagnetWindowController alloc] initWithTorrent: torrent destination: location
1033                                                        controller: self];
1034        [addController showWindow: self];
1035    }
1036    else
1037    {
1038        [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
1039       
1040        [torrent update];
1041        [fTorrents addObject: torrent];
1042        [torrent release];
1043    }
1044
1045    [self updateTorrentsInQueue];
1046}
1047
1048- (void) askOpenMagnetConfirmed: (AddMagnetWindowController *) addController add: (BOOL) add
1049{
1050    Torrent * torrent = [addController torrent];
1051    [addController release];
1052   
1053    if (add)
1054    {
1055        [torrent update];
1056        [fTorrents addObject: torrent];
1057        [torrent release];
1058       
1059        [self updateTorrentsInQueue];
1060    }
1061    else
1062    {
1063        [torrent closeRemoveTorrent];
1064        [torrent release];
1065    }
1066}
1067
1068- (void) openCreatedFile: (NSNotification *) notification
1069{
1070    NSDictionary * dict = [notification userInfo];
1071    [self openFiles: [NSArray arrayWithObject: [dict objectForKey: @"File"]] addType: ADD_CREATED
1072                        forcePath: [dict objectForKey: @"Path"]];
1073    [dict release];
1074}
1075
1076- (void) openFilesWithDict: (NSDictionary *) dictionary
1077{
1078    [self openFiles: [dictionary objectForKey: @"Filenames"] addType: [[dictionary objectForKey: @"AddType"] intValue] forcePath: nil];
1079   
1080    [dictionary release];
1081}
1082
1083//called on by applescript
1084- (void) open: (NSArray *) files
1085{
1086    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: files, @"Filenames",
1087                                [NSNumber numberWithInt: ADD_MANUAL], @"AddType", nil];
1088    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dict waitUntilDone: NO];
1089}
1090
1091- (void) openShowSheet: (id) sender
1092{
1093    NSOpenPanel * panel = [NSOpenPanel openPanel];
1094
1095    [panel setAllowsMultipleSelection: YES];
1096    [panel setCanChooseFiles: YES];
1097    [panel setCanChooseDirectories: NO];
1098
1099    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]
1100        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
1101        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
1102}
1103
1104- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSNumber *) useOptions
1105{
1106    if (code == NSOKButton)
1107    {
1108        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: [panel filenames], @"Filenames",
1109            [NSNumber numberWithInt: [useOptions boolValue] ? ADD_SHOW_OPTIONS : ADD_MANUAL], @"AddType", nil];
1110        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
1111    }
1112}
1113
1114- (void) invalidOpenAlert: (NSString *) filename
1115{
1116    if (![fDefaults boolForKey: @"WarningInvalidOpen"])
1117        return;
1118   
1119    NSAlert * alert = [[NSAlert alloc] init];
1120    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"\"%@\" is not a valid torrent file.",
1121                            "Open invalid alert -> title"), filename]];
1122    [alert setInformativeText:
1123            NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.",
1124                            "Open invalid alert -> message")];
1125    [alert setAlertStyle: NSWarningAlertStyle];
1126    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open invalid alert -> button")];
1127   
1128    [alert runModal];
1129    if ([[alert suppressionButton] state] == NSOnState)
1130        [fDefaults setBool: NO forKey: @"WarningInvalidOpen"];
1131    [alert release];
1132}
1133
1134- (void) invalidOpenMagnetAlert: (NSString *) address
1135{
1136    if (![fDefaults boolForKey: @"WarningInvalidOpen"])
1137        return;
1138   
1139    NSAlert * alert = [[NSAlert alloc] init];
1140    [alert setMessageText: NSLocalizedString(@"Adding magnetized transfer failed.", "Magnet link failed -> title")];
1141    [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"There was an error when adding the magnet link \"%@\"."
1142                                " The transfer will not occur.", "Magnet link failed -> message"), address]];
1143    [alert setAlertStyle: NSWarningAlertStyle];
1144    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Magnet link failed -> button")];
1145   
1146    [alert runModal];
1147    if ([[alert suppressionButton] state] == NSOnState)
1148        [fDefaults setBool: NO forKey: @"WarningInvalidOpen"];
1149    [alert release];
1150}
1151
1152- (void) duplicateOpenAlert: (NSString *) name
1153{
1154    if (![fDefaults boolForKey: @"WarningDuplicate"])
1155        return;
1156   
1157    NSAlert * alert = [[NSAlert alloc] init];
1158    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.",
1159                            "Open duplicate alert -> title"), name]];
1160    [alert setInformativeText:
1161            NSLocalizedString(@"The transfer cannot be added because it is a duplicate of an already existing transfer.",
1162                            "Open duplicate alert -> message")];
1163    [alert setAlertStyle: NSWarningAlertStyle];
1164    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate alert -> button")];
1165    [alert setShowsSuppressionButton: YES];
1166   
1167    [alert runModal];
1168    if ([[alert suppressionButton] state])
1169        [fDefaults setBool: NO forKey: @"WarningDuplicate"];
1170    [alert release];
1171}
1172
1173- (void) duplicateOpenMagnetAlert: (NSString *) address transferName: (NSString *) name
1174{
1175    if (![fDefaults boolForKey: @"WarningDuplicate"])
1176        return;
1177   
1178    NSAlert * alert = [[NSAlert alloc] init];
1179    if (name)
1180        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.",
1181                                "Open duplicate magnet alert -> title"), name]];
1182    else
1183        [alert setMessageText: NSLocalizedString(@"Magnet link is a duplicate of an existing transfer.",
1184                                "Open duplicate magnet alert -> title")];
1185    [alert setInformativeText: [NSString stringWithFormat:
1186            NSLocalizedString(@"The magnet link  \"%@\" cannot be added because it is a duplicate of an already existing transfer.",
1187                            "Open duplicate magnet alert -> message"), address]];
1188    [alert setAlertStyle: NSWarningAlertStyle];
1189    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate magnet alert -> button")];
1190    [alert setShowsSuppressionButton: YES];
1191   
1192    [alert runModal];
1193    if ([[alert suppressionButton] state])
1194        [fDefaults setBool: NO forKey: @"WarningDuplicate"];
1195    [alert release];
1196}
1197
1198- (void) openURL: (NSString *) urlString
1199{
1200    if ([urlString rangeOfString: @"magnet:" options: (NSAnchoredSearch | NSCaseInsensitiveSearch)].location != NSNotFound)
1201        [self openMagnet: urlString];
1202    else
1203    {
1204        if ([urlString rangeOfString: @"://"].location == NSNotFound)
1205        {
1206            if ([urlString rangeOfString: @"."].location == NSNotFound)
1207            {
1208                NSInteger beforeCom;
1209                if ((beforeCom = [urlString rangeOfString: @"/"].location) != NSNotFound)
1210                    urlString = [NSString stringWithFormat: @"http://www.%@.com/%@",
1211                                    [urlString substringToIndex: beforeCom],
1212                                    [urlString substringFromIndex: beforeCom + 1]];
1213                else
1214                    urlString = [NSString stringWithFormat: @"http://www.%@.com/", urlString];
1215            }
1216            else
1217                urlString = [@"http://" stringByAppendingString: urlString];
1218        }
1219       
1220        NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: urlString]
1221                                    cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval: 60];
1222        [[NSURLDownload alloc] initWithRequest: request delegate: self];
1223    }
1224}
1225
1226- (void) openURLShowSheet: (id) sender
1227{
1228    [NSApp beginSheet: fURLSheetWindow modalForWindow: fWindow modalDelegate: self
1229            didEndSelector: @selector(urlSheetDidEnd:returnCode:contextInfo:) contextInfo: nil];
1230}
1231
1232- (void) openURLEndSheet: (id) sender
1233{
1234    [fURLSheetWindow orderOut: sender];
1235    [NSApp endSheet: fURLSheetWindow returnCode: 1];
1236}
1237
1238- (void) openURLCancelEndSheet: (id) sender
1239{
1240    [fURLSheetWindow orderOut: sender];
1241    [NSApp endSheet: fURLSheetWindow returnCode: 0];
1242}
1243
1244- (void) controlTextDidChange: (NSNotification *) notification
1245{
1246    if ([notification object] != fURLSheetTextField)
1247        return;
1248   
1249    NSString * string = [fURLSheetTextField stringValue];
1250    BOOL enable = YES;
1251    if ([string isEqualToString: @""])
1252        enable = NO;
1253    else
1254    {
1255        NSRange prefixRange = [string rangeOfString: @"://"];
1256        if (prefixRange.location != NSNotFound && [string length] == NSMaxRange(prefixRange))
1257            enable = NO;
1258    }
1259   
1260    [fURLSheetOpenButton setEnabled: enable];
1261}
1262
1263- (void) urlSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
1264{
1265    [fURLSheetTextField selectText: self];
1266    if (returnCode != 1)
1267        return;
1268   
1269    NSString * urlString = [fURLSheetTextField stringValue];
1270    [self performSelectorOnMainThread: @selector(openURL:) withObject: urlString waitUntilDone: NO];
1271}
1272
1273- (void) createFile: (id) sender
1274{
1275    [CreatorWindowController createTorrentFile: fLib];
1276}
1277
1278- (void) resumeSelectedTorrents: (id) sender
1279{
1280    [self resumeTorrents: [fTableView selectedTorrents]];
1281}
1282
1283- (void) resumeAllTorrents: (id) sender
1284{
1285    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1286   
1287    for (Torrent * torrent in fTorrents)
1288        if (![torrent isFinishedSeeding])
1289            [torrents addObject: torrent];
1290   
1291    [self resumeTorrents: torrents];
1292}
1293
1294- (void) resumeTorrents: (NSArray *) torrents
1295{
1296    for (Torrent * torrent in torrents)
1297        [torrent setWaitToStart: YES];
1298   
1299    [self updateTorrentsInQueue];
1300}
1301
1302- (void) resumeSelectedTorrentsNoWait:  (id) sender
1303{
1304    [self resumeTorrentsNoWait: [fTableView selectedTorrents]];
1305}
1306
1307- (void) resumeWaitingTorrents: (id) sender
1308{
1309    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1310   
1311    for (Torrent * torrent in fTorrents)
1312        if (![torrent isActive] && [torrent waitingToStart])
1313            [torrents addObject: torrent];
1314   
1315    [self resumeTorrentsNoWait: torrents];
1316}
1317
1318- (void) resumeTorrentsNoWait: (NSArray *) torrents
1319{
1320    //iterate through instead of all at once to ensure no conflicts
1321    for (Torrent * torrent in torrents)
1322    {
1323        tr_inf( "restarting a torrent in resumeTorrentsNoWait" );
1324        [torrent startTransfer];
1325    }
1326   
1327    [self updateUI];
1328    [self applyFilter: nil];
1329    [[fWindow toolbar] validateVisibleItems];
1330    [self updateTorrentHistory];
1331}
1332
1333- (void) stopSelectedTorrents: (id) sender
1334{
1335    [self stopTorrents: [fTableView selectedTorrents]];
1336}
1337
1338- (void) stopAllTorrents: (id) sender
1339{
1340    [self stopTorrents: fTorrents];
1341}
1342
1343- (void) stopTorrents: (NSArray *) torrents
1344{
1345    //don't want any of these starting then stopping
1346    for (Torrent * torrent in torrents)
1347        [torrent setWaitToStart: NO];
1348
1349    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
1350   
1351    [self updateUI];
1352    [self applyFilter: nil];
1353    [[fWindow toolbar] validateVisibleItems];
1354    [self updateTorrentHistory];
1355}
1356
1357- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1358{
1359    [torrents retain];
1360    NSInteger active = 0, downloading = 0;
1361
1362    if ([fDefaults boolForKey: @"CheckRemove"])
1363    {
1364        for (Torrent * torrent in torrents)
1365            if ([torrent isActive])
1366            {
1367                active++;
1368                if (![torrent isSeeding])
1369                    downloading++;
1370            }
1371
1372        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
1373        {
1374            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
1375                                    torrents, @"Torrents",
1376                                    [NSNumber numberWithBool: deleteData], @"DeleteData", nil];
1377           
1378            NSString * title, * message;
1379           
1380            const NSInteger selected = [torrents count];
1381            if (selected == 1)
1382            {
1383                NSString * torrentName = [[torrents objectAtIndex: 0] name];
1384               
1385                if (deleteData)
1386                    title = [NSString stringWithFormat:
1387                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1388                                " and trash the data file?", "Removal confirm panel -> title"), torrentName];
1389                else
1390                    title = [NSString stringWithFormat:
1391                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1392                                "Removal confirm panel -> title"), torrentName];
1393               
1394                message = NSLocalizedString(@"This transfer is active."
1395                            " Once removed, continuing the transfer will require the torrent file or magnet link.",
1396                            "Removal confirm panel -> message");
1397            }
1398            else
1399            {
1400                if (deleteData)
1401                    title = [NSString stringWithFormat:
1402                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1403                                " and trash the data files?", "Removal confirm panel -> title"), selected];
1404                else
1405                    title = [NSString stringWithFormat:
1406                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list?",
1407                                "Removal confirm panel -> title"), selected];
1408               
1409                if (selected == active)
1410                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
1411                                "Removal confirm panel -> message part 1"), active];
1412                else
1413                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
1414                                "Removal confirm panel -> message part 1"), selected, active];
1415                message = [message stringByAppendingFormat: @" %@",
1416                            NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files or magnet links.",
1417                            "Removal confirm panel -> message part 2")];
1418            }
1419           
1420            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
1421                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
1422                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
1423            return;
1424        }
1425    }
1426   
1427    [self confirmRemoveTorrents: torrents deleteData: deleteData];
1428}
1429
1430- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (NSDictionary *) dict
1431{
1432    NSArray * torrents = [dict objectForKey: @"Torrents"];
1433    if (returnCode == NSAlertDefaultReturn)
1434        [self confirmRemoveTorrents: torrents deleteData: [[dict objectForKey: @"DeleteData"] boolValue]];
1435    else
1436        [torrents release];
1437   
1438    [dict release];
1439}
1440
1441- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1442{
1443    //don't want any of these starting then stopping
1444    for (Torrent * torrent in torrents)
1445        [torrent setWaitToStart: NO];
1446   
1447    [fTorrents removeObjectsInArray: torrents];
1448   
1449    //if not removed from displayed torrents, updateTorrentsInQueue might cause a crash
1450    if ([fDisplayedTorrents count] > 0)
1451    {
1452        if ([[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1453        {
1454            for (TorrentGroup * group in fDisplayedTorrents)
1455                [[group torrents] removeObjectsInArray: torrents];
1456        }
1457        else
1458            [fDisplayedTorrents removeObjectsInArray: torrents];
1459    }
1460   
1461    for (Torrent * torrent in torrents)
1462    {
1463        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1464        [fTableView removeCollapsedGroup: [torrent groupValue]];
1465       
1466        if (deleteData)
1467            [torrent trashData];
1468       
1469        [torrent closeRemoveTorrent];
1470    }
1471   
1472    [torrents release];
1473   
1474    [fTableView deselectAll: nil];
1475   
1476    [self updateTorrentsInQueue];
1477}
1478
1479- (void) removeNoDelete: (id) sender
1480{
1481    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO];
1482}
1483
1484- (void) removeDeleteData: (id) sender
1485{
1486    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES];
1487}
1488
1489- (void) moveDataFilesSelected: (id) sender
1490{
1491    [self moveDataFiles: [fTableView selectedTorrents]];
1492}
1493
1494- (void) moveDataFiles: (NSArray *) torrents
1495{
1496    NSOpenPanel * panel = [NSOpenPanel openPanel];
1497    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1498    [panel setAllowsMultipleSelection: NO];
1499    [panel setCanChooseFiles: NO];
1500    [panel setCanChooseDirectories: YES];
1501    [panel setCanCreateDirectories: YES];
1502   
1503    torrents = [torrents retain];
1504    NSInteger count = [torrents count];
1505    if (count == 1)
1506        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1507                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1508    else
1509        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1510                            "Move torrent -> select destination folder"), count]];
1511       
1512    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1513        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1514}
1515
1516- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) torrents
1517{
1518    if (code == NSOKButton)
1519    {
1520        for (Torrent * torrent in torrents)
1521            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1522    }
1523   
1524    [torrents release];
1525}
1526
1527- (void) copyTorrentFiles: (id) sender
1528{
1529    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1530}
1531
1532- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1533{
1534    if ([torrents count] == 0)
1535    {
1536        [torrents release];
1537        return;
1538    }
1539   
1540    Torrent * torrent = [torrents objectAtIndex: 0];
1541   
1542    if (![torrent isMagnet] && [[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1543    {
1544        NSSavePanel * panel = [NSSavePanel savePanel];
1545        [panel setAllowedFileTypes: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]];
1546        [panel setExtensionHidden: NO];
1547       
1548        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1549            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1550    }
1551    else
1552    {
1553        if (![torrent isMagnet])
1554        {
1555            NSAlert * alert = [[NSAlert alloc] init];
1556            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1557            [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1558                                    "Torrent file copy alert -> title"), [torrent name]]];
1559            [alert setInformativeText: [NSString stringWithFormat:
1560                    NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1561                                        [torrent torrentLocation]]];
1562            [alert setAlertStyle: NSWarningAlertStyle];
1563           
1564            [alert runModal];
1565            [alert release];
1566        }
1567       
1568        [torrents removeObjectAtIndex: 0];
1569        [self copyTorrentFileForTorrents: torrents];
1570    }
1571}
1572
1573- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSMutableArray *) torrents
1574{
1575    //copy torrent to new location with name of data file
1576    if (code == NSOKButton)
1577        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1578   
1579    [torrents removeObjectAtIndex: 0];
1580    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1581}
1582
1583- (void) copyMagnetLinks: (id) sender
1584{
1585    NSArray * torrents = [fTableView selectedTorrents];
1586   
1587    if ([torrents count] <= 0)
1588        return;
1589   
1590    NSMutableArray * links = [NSMutableArray arrayWithCapacity: [torrents count]];
1591    for (Torrent * torrent in torrents)
1592        [links addObject: [torrent magnetLink]];
1593   
1594    NSString * text = [links componentsJoinedByString: @"\n"];
1595   
1596    NSPasteboard * pb = [NSPasteboard generalPasteboard];
1597    if ([NSApp isOnSnowLeopardOrBetter])
1598    {
1599        [pb clearContents];
1600        [pb writeObjects: [NSArray arrayWithObject: text]];
1601    }
1602    else
1603    {
1604        [pb declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner: nil];
1605        [pb setString: text forType: NSStringPboardType];
1606    }
1607}
1608
1609- (void) revealFile: (id) sender
1610{
1611    NSArray * selected = [fTableView selectedTorrents];
1612    if ([NSApp isOnSnowLeopardOrBetter])
1613    {
1614        NSMutableArray * paths = [NSMutableArray arrayWithCapacity: [selected count]];
1615        for (Torrent * torrent in selected)
1616        {
1617            NSString * location = [torrent dataLocation];
1618            if (location)
1619                [paths addObject: [NSURL fileURLWithPath: location]];
1620        }
1621       
1622        if ([paths count] > 0)
1623            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: paths];
1624    }
1625    else
1626    {
1627        for (Torrent * torrent in selected)
1628        {
1629            NSString * location = [torrent dataLocation];
1630            if (location)
1631                [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
1632        }
1633    }
1634}
1635
1636- (void) announceSelectedTorrents: (id) sender
1637{
1638    for (Torrent * torrent in [fTableView selectedTorrents])
1639    {
1640        if ([torrent canManualAnnounce])
1641            [torrent manualAnnounce];
1642    }
1643}
1644
1645- (void) verifySelectedTorrents: (id) sender
1646{
1647    [self verifyTorrents: [fTableView selectedTorrents]];
1648}
1649
1650- (void) verifyTorrents: (NSArray *) torrents
1651{
1652    for (Torrent * torrent in torrents)
1653        [torrent resetCache];
1654   
1655    [self applyFilter: nil];
1656}
1657
1658- (void) showPreferenceWindow: (id) sender
1659{
1660    NSWindow * window = [fPrefsController window];
1661    if (![window isVisible])
1662        [window center];
1663
1664    [window makeKeyAndOrderFront: nil];
1665}
1666
1667- (void) showAboutWindow: (id) sender
1668{
1669    [[AboutWindowController aboutController] showWindow: nil];
1670}
1671
1672- (void) showInfo: (id) sender
1673{
1674    if ([[fInfoController window] isVisible])
1675        [fInfoController close];
1676    else
1677    {
1678        [fInfoController updateInfoStats];
1679        [[fInfoController window] orderFront: nil];
1680       
1681        if ([fInfoController canQuickLook]
1682            && [QLPreviewPanelSL sharedPreviewPanelExists] && [[QLPreviewPanelSL sharedPreviewPanel] isVisible])
1683            [[QLPreviewPanelSL sharedPreviewPanel] reloadData];
1684       
1685    }
1686   
1687    [[fWindow toolbar] validateVisibleItems];
1688}
1689
1690- (void) resetInfo
1691{
1692    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1693   
1694    if ([NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
1695        && [[QLPreviewPanelSL sharedPreviewPanel] isVisible])
1696        [[QLPreviewPanelSL sharedPreviewPanel] reloadData];
1697}
1698
1699- (void) setInfoTab: (id) sender
1700{
1701    if (sender == fNextInfoTabItem)
1702        [fInfoController setNextTab];
1703    else
1704        [fInfoController setPreviousTab];
1705}
1706
1707- (void) showMessageWindow: (id) sender
1708{
1709    if (!fMessageController)
1710        fMessageController = [[MessageWindowController alloc] init];
1711    [fMessageController showWindow: nil];
1712}
1713
1714- (void) showStatsWindow: (id) sender
1715{
1716    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1717}
1718
1719- (void) updateUI
1720{
1721    [fTorrents makeObjectsPerformSelector: @selector(update)];
1722   
1723    if (![NSApp isHidden])
1724    {
1725        if ([fWindow isVisible])
1726        {
1727            [self sortTorrents];
1728           
1729            //update status bar
1730            if (![fStatusBar isHidden])
1731            {
1732                //set rates
1733                [fTotalDLField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed_KBps(fLib, TR_DOWN)]];
1734                [fTotalULField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed_KBps(fLib, TR_UP)]];
1735               
1736                //set status button text
1737                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1738                BOOL total;
1739                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1740                {
1741                    tr_session_stats stats;
1742                    if (total)
1743                        tr_sessionGetCumulativeStats(fLib, &stats);
1744                    else
1745                        tr_sessionGetStats(fLib, &stats);
1746                   
1747                    statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") stringByAppendingFormat: @": %@",
1748                                    [NSString stringForRatio: stats.ratio]];
1749                }
1750                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1751                {
1752                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1753                   
1754                    tr_session_stats stats;
1755                    if (total)
1756                        tr_sessionGetCumulativeStats(fLib, &stats);
1757                    else
1758                        tr_sessionGetStats(fLib, &stats);
1759                   
1760                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1761                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1762                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1763                }
1764               
1765                [fStatusButton setTitle: statusString];
1766                [self resizeStatusButton];
1767            }
1768        }
1769
1770        //update non-constant parts of info window
1771        if ([[fInfoController window] isVisible])
1772            [fInfoController updateInfoStats];
1773    }
1774   
1775    //badge dock
1776    [fBadger updateBadge];
1777}
1778
1779- (void) resizeStatusButton
1780{
1781    [fStatusButton sizeToFit];
1782   
1783    //width ends up being too long
1784    NSRect statusFrame = [fStatusButton frame];
1785    statusFrame.size.width -= 25.0;
1786   
1787    CGFloat difference = NSMaxX(statusFrame) + 5.0 - [fTotalDLImageView frame].origin.x;
1788    if (difference > 0)
1789        statusFrame.size.width -= difference;
1790   
1791    [fStatusButton setFrame: statusFrame];
1792}
1793
1794- (void) setBottomCountText: (BOOL) filtering
1795{
1796    NSString * totalTorrentsString;
1797    NSUInteger totalCount = [fTorrents count];
1798    if (totalCount != 1)
1799        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ transfers", "Status bar transfer count"),
1800                                [NSString formattedUInteger: totalCount]];
1801    else
1802        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1803   
1804    if (filtering)
1805    {
1806        NSUInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1807        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1808            count -= [fDisplayedTorrents count];
1809       
1810        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Status bar transfer count"),
1811                                [NSString formattedUInteger: count], totalTorrentsString];
1812    }
1813   
1814    [fTotalTorrentsField setStringValue: totalTorrentsString];
1815}
1816
1817- (void) updateSpeedFieldsToolTips
1818{
1819    NSString * uploadText, * downloadText;
1820   
1821    if ([fDefaults boolForKey: @"SpeedLimit"])
1822    {
1823        NSString * speedString = [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1824                                    NSLocalizedString(@"Speed Limit", "Status Bar -> speed tooltip")];
1825       
1826        uploadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]];
1827        downloadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]];
1828    }
1829    else
1830    {
1831        if ([fDefaults boolForKey: @"CheckUpload"])
1832            uploadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1833                            [fDefaults integerForKey: @"UploadLimit"]];
1834        else
1835            uploadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1836       
1837        if ([fDefaults boolForKey: @"CheckDownload"])
1838            downloadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1839                            [fDefaults integerForKey: @"DownloadLimit"]];
1840        else
1841            downloadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1842    }
1843   
1844    uploadText = [NSLocalizedString(@"Global upload limit", "Status Bar -> speed tooltip")
1845                    stringByAppendingFormat: @": %@", uploadText];
1846    downloadText = [NSLocalizedString(@"Global download limit", "Status Bar -> speed tooltip")
1847                    stringByAppendingFormat: @": %@", downloadText];
1848   
1849    [fTotalULField setToolTip: uploadText];
1850    [fTotalDLField setToolTip: downloadText];
1851}
1852
1853- (void) updateTorrentsInQueue
1854{
1855    NSUInteger desiredDownloadActive = [fDefaults boolForKey: @"Queue"] ? [self numToStartFromQueue: YES] : NSUIntegerMax,
1856                desiredSeedActive = [fDefaults boolForKey: @"QueueSeed"] ? [self numToStartFromQueue: NO] : NSUIntegerMax;
1857   
1858    for (Torrent * torrent in fTorrents)
1859    {
1860        if (desiredDownloadActive == 0 && desiredSeedActive == 0)
1861            break;
1862       
1863        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1864        {
1865            if (![torrent allDownloaded])
1866            {
1867                if (desiredDownloadActive > 0)
1868                {
1869                    tr_inf( "restarting download torrent in mac queue" );
1870                    [torrent startTransfer];
1871                    if ([torrent isActive])
1872                        --desiredDownloadActive;
1873                    [torrent update];
1874                }
1875            }
1876            else
1877            {
1878                if (desiredSeedActive > 0)
1879                {
1880                    tr_inf( "restarting seed torrent in mac queue" );
1881                    [torrent startTransfer];
1882                    if ([torrent isActive])
1883                        --desiredSeedActive;
1884                    [torrent update];
1885                }
1886            }
1887        }
1888    }
1889   
1890    [self updateUI];
1891    [self applyFilter: nil];
1892    [[fWindow toolbar] validateVisibleItems];
1893    [self updateTorrentHistory];
1894}
1895
1896- (NSUInteger) numToStartFromQueue: (BOOL) downloadQueue
1897{
1898    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1899        return 0;
1900   
1901    NSUInteger desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1902       
1903    for (Torrent * torrent in fTorrents)
1904    {
1905        if (desired == 0)
1906            break;
1907       
1908        if ([torrent isChecking])
1909            --desired;
1910        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1911        {
1912            if ([torrent allDownloaded] != downloadQueue)
1913                --desired;
1914        }
1915        else;
1916    }
1917   
1918    return desired;
1919}
1920
1921- (void) torrentFinishedDownloading: (NSNotification *) notification
1922{
1923    Torrent * torrent = [notification object];
1924   
1925    if ([[[notification userInfo] objectForKey: @"WasRunning"] boolValue])
1926    {
1927        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1928        {
1929            NSSound * sound;
1930            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1931            {
1932                [sound setDelegate: self];
1933                fSoundPlaying = YES;
1934                [sound play];
1935            }
1936        }
1937       
1938        NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_DOWNLOAD_COMPLETE forKey: @"Type"];
1939       
1940        NSString * location = [torrent dataLocation];
1941        if (location)
1942            [clickContext setObject: location forKey: @"Location"];
1943       
1944        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1945                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1946                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1947       
1948        if (![fWindow isMainWindow])
1949            [fBadger incrementCompleted];
1950       
1951        //bounce download stack
1952        [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"com.apple.DownloadFileFinished"
1953            object: [torrent dataLocation]];
1954       
1955        if ([torrent isActive] && [fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] == 0)
1956        {
1957            [torrent stopTransfer];
1958            [torrent setWaitToStart: YES];
1959        }
1960    }
1961   
1962    [self updateTorrentsInQueue];
1963}
1964
1965- (void) torrentRestartedDownloading: (NSNotification *) notification
1966{
1967    Torrent * torrent = [notification object];
1968    if ([torrent isActive] && [fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] == 0)
1969    {
1970        [torrent stopTransfer];
1971        [torrent setWaitToStart: YES];
1972    }
1973   
1974    [self updateTorrentsInQueue];
1975}
1976
1977- (void) torrentFinishedSeeding: (NSNotification *) notification
1978{
1979    Torrent * torrent = [notification object];
1980   
1981    [self updateTorrentsInQueue];
1982   
1983    if ([[fTableView selectedTorrents] containsObject: torrent])
1984    {
1985        [fInfoController updateInfoStats];
1986        [fInfoController updateOptions];
1987    }
1988   
1989    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1990    {
1991        NSSound * sound;
1992        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1993        {
1994            [sound setDelegate: self];
1995            fSoundPlaying = YES;
1996            [sound play];
1997        }
1998    }
1999   
2000    NSMutableDictionary * clickContext = [NSMutableDictionary dictionaryWithObject: GROWL_SEEDING_COMPLETE forKey: @"Type"];
2001   
2002    NSString * location = [torrent dataLocation];
2003    if (location)
2004        [clickContext setObject: location forKey: @"Location"];
2005   
2006    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
2007                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2008                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2009}
2010
2011- (void) updateTorrentHistory
2012{
2013    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2014   
2015    for (Torrent * torrent in fTorrents)
2016        [history addObject: [torrent history]];
2017   
2018    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST] atomically: YES];
2019}
2020
2021- (void) setSort: (id) sender
2022{
2023    NSString * sortType;
2024    switch ([sender tag])
2025    {
2026        case SORT_ORDER_TAG:
2027            sortType = SORT_ORDER;
2028            [fDefaults setBool: NO forKey: @"SortReverse"];
2029            break;
2030        case SORT_DATE_TAG:
2031            sortType = SORT_DATE;
2032            break;
2033        case SORT_NAME_TAG:
2034            sortType = SORT_NAME;
2035            break;
2036        case SORT_PROGRESS_TAG:
2037            sortType = SORT_PROGRESS;
2038            break;
2039        case SORT_STATE_TAG:
2040            sortType = SORT_STATE;
2041            break;
2042        case SORT_TRACKER_TAG:
2043            sortType = SORT_TRACKER;
2044            break;
2045        case SORT_ACTIVITY_TAG:
2046            sortType = SORT_ACTIVITY;
2047            break;
2048        default:
2049            NSAssert1(NO, @"Unknown sort tag received: %d", [sender tag]);
2050            return;
2051    }
2052   
2053    [fDefaults setObject: sortType forKey: @"Sort"];
2054    [self applyFilter: nil]; //better than calling sortTorrents because it will even apply to queue order
2055}
2056
2057- (void) setSortByGroup: (id) sender
2058{
2059    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
2060    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
2061   
2062    //expand all groups
2063    if (sortByGroup)
2064        [fTableView removeAllCollapsedGroups];
2065   
2066    [self applyFilter: nil];
2067}
2068
2069- (void) setSortReverse: (id) sender
2070{
2071    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
2072    [self sortTorrents];
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        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
4036        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
4037    }
4038   
4039    //enable group sort item
4040    if (action == @selector(setSortByGroup:))
4041    {
4042        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
4043        return YES;
4044    }
4045   
4046    //check proper filter search item
4047    if (action == @selector(setFilterSearchType:))
4048    {
4049        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
4050       
4051        BOOL state;
4052        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
4053            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
4054        else
4055            state = [filterType isEqualToString: FILTER_TYPE_NAME];
4056       
4057        [menuItem setState: state ? NSOnState : NSOffState];
4058        return YES;
4059    }
4060   
4061    if (action == @selector(toggleQuickLook:))
4062    {
4063        const BOOL visible = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
4064                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
4065        //text consistent with Finder
4066        NSString * title = !visible ? NSLocalizedString(@"Quick Look", "View menu -> Quick Look")
4067                                    : NSLocalizedString(@"Close Quick Look", "View menu -> Quick Look");
4068        [menuItem setTitle: title];
4069       
4070        return [NSApp isOnSnowLeopardOrBetter];
4071    }
4072   
4073    return YES;
4074}
4075
4076- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
4077{
4078    switch (messageType)
4079    {
4080        case kIOMessageSystemWillSleep:
4081            //if there are any running transfers, wait 15 seconds for them to stop
4082            for (Torrent * torrent in fTorrents)
4083                if ([torrent isActive])
4084                {
4085                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
4086                    for (Torrent * torrent in fTorrents)
4087                        [torrent sleep];
4088                    sleep(15);
4089                    break;
4090                }
4091
4092            IOAllowPowerChange(fRootPort, (long) messageArgument);
4093            break;
4094
4095        case kIOMessageCanSystemSleep:
4096            if ([fDefaults boolForKey: @"SleepPrevent"])
4097            {
4098                //prevent idle sleep unless no torrents are active
4099                for (Torrent * torrent in fTorrents)
4100                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
4101                    {
4102                        IOCancelPowerChange(fRootPort, (long) messageArgument);
4103                        return;
4104                    }
4105            }
4106           
4107            IOAllowPowerChange(fRootPort, (long) messageArgument);
4108            break;
4109
4110        case kIOMessageSystemHasPoweredOn:
4111            //resume sleeping transfers after we wake up
4112            for (Torrent * torrent in fTorrents)
4113                [torrent wakeUp];
4114            break;
4115    }
4116}
4117
4118- (NSMenu *) applicationDockMenu: (NSApplication *) sender
4119{
4120    NSInteger seeding = 0, downloading = 0;
4121    for (Torrent * torrent in fTorrents)
4122    {
4123        if ([torrent isSeeding])
4124            seeding++;
4125        else if ([torrent isActive])
4126            downloading++;
4127        else;
4128    }
4129   
4130    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
4131            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
4132   
4133    BOOL hasSeparator = seedingItem || downloadingItem;
4134   
4135    if (seeding > 0)
4136    {
4137        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
4138        if (!seedingItem)
4139        {
4140            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
4141            [seedingItem setTag: DOCK_SEEDING_TAG];
4142            [fDockMenu insertItem: seedingItem atIndex: 0];
4143        }
4144        else
4145            [seedingItem setTitle: title];
4146    }
4147    else
4148    {
4149        if (seedingItem)
4150            [fDockMenu removeItem: seedingItem];
4151    }
4152   
4153    if (downloading > 0)
4154    {
4155        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
4156        if (!downloadingItem)
4157        {
4158            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
4159            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
4160            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
4161        }
4162        else
4163            [downloadingItem setTitle: title];
4164    }
4165    else
4166    {
4167        if (downloadingItem)
4168            [fDockMenu removeItem: downloadingItem];
4169    }
4170   
4171    if (seeding > 0 || downloading > 0)
4172    {
4173        if (!hasSeparator)
4174            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: (seeding > 0 && downloading > 0) ? 2 : 1];
4175    }
4176    else
4177    {
4178        if (hasSeparator)
4179            [fDockMenu removeItemAtIndex: 0];
4180    }
4181   
4182    return fDockMenu;
4183}
4184
4185- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
4186{
4187    //if auto size is enabled, the current frame shouldn't need to change
4188    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
4189   
4190    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
4191    return frame;
4192}
4193
4194- (void) setWindowSizeToFit
4195{
4196    if ([fDefaults boolForKey: @"AutoSize"])
4197    {
4198        NSScrollView * scrollView = [fTableView enclosingScrollView];
4199       
4200        [scrollView setHasVerticalScroller: NO];
4201        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
4202        [scrollView setHasVerticalScroller: YES];
4203       
4204        //hack to ensure scrollbars don't disappear after resizing
4205        if (![NSApp isOnSnowLeopardOrBetter])
4206        {
4207            [scrollView setAutohidesScrollers: NO];
4208            [scrollView setAutohidesScrollers: YES];
4209        }
4210    }
4211}
4212
4213- (NSRect) sizedWindowFrame
4214{
4215    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
4216                    ? [fDisplayedTorrents count] : 0;
4217   
4218    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4219                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4220                        - [[fTableView enclosingScrollView] frame].size.height;
4221   
4222    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4223}
4224
4225- (void) resizeFilterBar
4226{
4227    //replace all buttons
4228    [fNoFilterButton sizeToFit];
4229    [fActiveFilterButton sizeToFit];
4230    [fDownloadFilterButton sizeToFit];
4231    [fSeedFilterButton sizeToFit];
4232    [fPauseFilterButton sizeToFit];
4233   
4234    NSRect allRect = [fNoFilterButton frame];
4235    NSRect activeRect = [fActiveFilterButton frame];
4236    NSRect downloadRect = [fDownloadFilterButton frame];
4237    NSRect seedRect = [fSeedFilterButton frame];
4238    NSRect pauseRect = [fPauseFilterButton frame];
4239   
4240    //size search filter to not overlap buttons
4241    NSRect searchFrame = [fSearchFilterField frame];
4242    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
4243    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
4244   
4245    //make sure it is not too long
4246    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
4247    {
4248        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
4249        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
4250    }
4251    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
4252    {
4253        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
4254        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
4255       
4256        //calculate width the buttons can take up
4257        const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x;
4258        const CGFloat currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect)
4259                                        + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons
4260        const CGFloat ratio = allowedWidth / currentWidth;
4261       
4262        //decrease button widths proportionally
4263        allRect.size.width  = NSWidth(allRect) * ratio;
4264        activeRect.size.width = NSWidth(activeRect) * ratio;
4265        downloadRect.size.width = NSWidth(downloadRect) * ratio;
4266        seedRect.size.width = NSWidth(seedRect) * ratio;
4267        pauseRect.size.width = NSWidth(pauseRect) * ratio;
4268    }
4269    else;
4270   
4271    activeRect.origin.x = NSMaxX(allRect) + 1.0;
4272    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
4273    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4274    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4275   
4276    [fNoFilterButton setFrame: allRect];
4277    [fActiveFilterButton setFrame: activeRect];
4278    [fDownloadFilterButton setFrame: downloadRect];
4279    [fSeedFilterButton setFrame: seedRect];
4280    [fPauseFilterButton setFrame: pauseRect];
4281   
4282    [fSearchFilterField setFrame: searchFrame];
4283}
4284
4285- (void) updateForExpandCollape
4286{
4287    [self setWindowSizeToFit];
4288    [self setBottomCountText: YES];
4289}
4290
4291- (void) showMainWindow: (id) sender
4292{
4293    [fWindow makeKeyAndOrderFront: nil];
4294}
4295
4296- (void) windowDidBecomeMain: (NSNotification *) notification
4297{
4298    [fBadger clearCompleted];
4299    [self updateUI];
4300}
4301
4302- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
4303{
4304    //only resize horizontally if autosize is enabled
4305    if ([fDefaults boolForKey: @"AutoSize"])
4306        proposedFrameSize.height = [fWindow frame].size.height;
4307    return proposedFrameSize;
4308}
4309
4310- (void) windowDidResize: (NSNotification *) notification
4311{
4312    if (![fStatusBar isHidden])
4313        [self resizeStatusButton];
4314   
4315    if ([fFilterBar isHidden])
4316        return;
4317
4318    [self resizeFilterBar];
4319}
4320
4321- (void) applicationWillUnhide: (NSNotification *) notification
4322{
4323    [self updateUI];
4324}
4325
4326- (void) toggleQuickLook: (id) sender
4327{
4328    if (![NSApp isOnSnowLeopardOrBetter])
4329        return;
4330   
4331    if ([[QLPreviewPanelSL sharedPreviewPanel] isVisible])
4332        [[QLPreviewPanelSL sharedPreviewPanel] orderOut: nil];
4333    else
4334        [[QLPreviewPanelSL sharedPreviewPanel] makeKeyAndOrderFront: nil];
4335}
4336
4337- (void) linkHomepage: (id) sender
4338{
4339    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4340}
4341
4342- (void) linkForums: (id) sender
4343{
4344    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4345}
4346
4347- (void) linkTrac: (id) sender
4348{
4349    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4350}
4351
4352- (void) linkDonate: (id) sender
4353{
4354    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4355}
4356
4357- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4358{
4359    fUpdateInProgress = YES;
4360}
4361
4362- (NSDictionary *) registrationDictionaryForGrowl
4363{
4364    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4365                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4366    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4367                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4368}
4369
4370- (void) growlNotificationWasClicked: (id) clickContext
4371{
4372    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4373        return;
4374   
4375    NSString * type = [clickContext objectForKey: @"Type"], * location;
4376    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4377            && (location = [clickContext objectForKey: @"Location"]))
4378    {
4379        if ([NSApp isOnSnowLeopardOrBetter])
4380        {
4381            NSURL * file = [NSURL fileURLWithPath: location];
4382            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4383        }
4384        else
4385            [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4386    }
4387}
4388
4389- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4390{
4391    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4392   
4393    //get the torrent
4394    Torrent * torrent = nil;
4395    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4396    {
4397        for (torrent in fTorrents)
4398            if (torrentStruct == [torrent torrentStruct])
4399            {
4400                [torrent retain];
4401                break;
4402            }
4403       
4404        if (!torrent)
4405        {
4406            [pool drain];
4407           
4408            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4409            return;
4410        }
4411    }
4412   
4413    switch (type)
4414    {
4415        case TR_RPC_TORRENT_ADDED:
4416            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4417                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4418            break;
4419       
4420        case TR_RPC_TORRENT_STARTED:
4421        case TR_RPC_TORRENT_STOPPED:
4422            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4423            break;
4424       
4425        case TR_RPC_TORRENT_REMOVING:
4426            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4427            break;
4428       
4429        case TR_RPC_TORRENT_CHANGED:
4430            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4431            break;
4432       
4433        case TR_RPC_TORRENT_MOVED:
4434            [self performSelectorOnMainThread: @selector(rpcMovedTorrent:) withObject: torrent waitUntilDone: NO];
4435            break;
4436       
4437        case TR_RPC_SESSION_CHANGED:
4438            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4439            break;
4440       
4441        default:
4442            NSAssert1(NO, @"Unknown RPC command received: %d", type);
4443            [torrent release];
4444    }
4445   
4446    [pool drain];
4447}
4448
4449- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4450{
4451    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4452    [torrentStructPtr release];
4453   
4454    NSString * location = nil;
4455    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4456        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4457   
4458    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4459   
4460    [torrent update];
4461    [fTorrents addObject: torrent];
4462    [torrent release];
4463   
4464    [self updateTorrentsInQueue];
4465}
4466
4467- (void) rpcRemoveTorrent: (Torrent *) torrent
4468{
4469    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4470    [torrent release];
4471}
4472
4473- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4474{
4475    [torrent update];
4476    [torrent release];
4477   
4478    [self updateUI];
4479    [self applyFilter: nil];
4480    [self updateTorrentHistory];
4481}
4482
4483- (void) rpcChangedTorrent: (Torrent *) torrent
4484{
4485    [torrent update];
4486   
4487    if ([[fTableView selectedTorrents] containsObject: torrent])
4488    {
4489        [fInfoController updateInfoStats]; //this will reload the file table
4490        [fInfoController updateOptions];
4491    }
4492   
4493    [torrent release];
4494}
4495
4496- (void) rpcMovedTorrent: (Torrent *) torrent
4497{
4498    [torrent update];
4499    [torrent updateTimeMachineExclude];
4500   
4501    if ([[fTableView selectedTorrents] containsObject: torrent])
4502        [fInfoController updateInfoStats];
4503   
4504    [torrent release];
4505}
4506
4507@end
Note: See TracBrowser for help on using the repository browser.