source: trunk/macosx/Controller.m @ 11364

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

remove proxy support from the Mac client

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