source: trunk/macosx/Controller.m @ 11207

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

#3518 Snow Leopard systems should show file sizes and speeds in base 10

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