source: trunk/macosx/Controller.m @ 11046

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

update Mac build for the change from inactive to idle

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