source: trunk/macosx/Controller.m @ 7802

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

random cleanup and update the strings file

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