source: trunk/macosx/Controller.m @ 8949

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

whoops

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