source: trunk/macosx/Controller.m @ 7983

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

trivial changes

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