source: trunk/macosx/Controller.m @ 7570

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

make the toolbar images templates; auto-generate the blue highlight for selected toolbar buttons (thanks to Leopard)

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