source: trunk/macosx/Controller.m @ 7794

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

determine queue order solely on order in the fTorrent array - this gets around potential problems when relaunching with less torrents

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