source: trunk/macosx/Controller.m @ 11178

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

don't set an idle eta if the transfer is currently uploading

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