source: trunk/macosx/Controller.m @ 10119

Last change on this file since 10119 was 10119, checked in by livings124, 13 years ago

#2844 Add option to disable ".part" suffix for incomplete files (Mac)

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