source: trunk/macosx/Controller.m @ 10526

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

eliminate a warning

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