source: trunk/macosx/Controller.m @ 10218

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

small tweaks

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