source: trunk/macosx/Controller.m @ 10444

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

#3114 remove preference, now resume all always excludes "seeding complete" transfers

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