source: trunk/macosx/Controller.m @ 7892

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

have the mac ui use libT's ratio settings (attempt 1); when seed ratio is reached in libT, set the seed ratio setting to "seed forever"

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