source: branches/2.0x/macosx/Controller.m @ 10878

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

(2.0x) #3320 When a download completes at the same time seeding completes, still show a Growl notification and play a sound

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