source: trunk/macosx/Controller.m @ 7755

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

(trunk) streamline the filter button resize code a bit

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