source: trunk/macosx/Controller.m @ 11967

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

add µTP to the Prefs window

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