source: trunk/macosx/Controller.m @ 10501

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

#3157 add hidden plist options "bind-address-ipv4/6"

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