source: trunk/macosx/Controller.m @ 10443

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

#3114 add option to transfers->management "Resume All includes seeding-complete transfers"

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