source: trunk/macosx/Controller.m @ 11417

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

add a string function to format an NSUInteger as a formatted string

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