source: trunk/macosx/Controller.m @ 7521

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

small streamline of filter code

  • Property svn:keywords set to Date Rev Author Id
File size: 154.7 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 7521 2008-12-29 02:39:41Z 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        NSArray * oldTorrentGroups = nil;
2007        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2008            oldTorrentGroups = [NSArray arrayWithArray: 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 (; oldTorrentGroups && currentOldGroupIndex < [oldTorrentGroups count]; currentOldGroupIndex++)
2028                {
2029                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
2030                    if ([currentGroup groupIndex] == groupValue)
2031                    {
2032                        group = currentGroup;
2033                        [[currentGroup torrents] removeAllObjects];
2034                        break;
2035                    }
2036                }
2037               
2038                if (!group)
2039                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2040                [fDisplayedTorrents addObject: group];
2041               
2042                groupTorrents = [group torrents];
2043            }
2044           
2045            [groupTorrents addObject: torrent];
2046        }
2047    }
2048    else
2049        [fDisplayedTorrents setArray: allTorrents];
2050   
2051    //actually sort
2052    [self sortTorrentsIgnoreSelected];
2053   
2054    //reset expanded/collapsed rows
2055    if (groupRows)
2056    {
2057        for (TorrentGroup * group in fDisplayedTorrents)
2058        {
2059            if ([fTableView isGroupCollapsed: [group groupIndex]])
2060                [fTableView collapseItem: group];
2061            else
2062                [fTableView expandItem: group];
2063        }
2064    }
2065   
2066    [fTableView selectValues: selectedValues];
2067    #warning still happens anyway?
2068    //removed because it made the inspector reset (noticeable when a transfer with web seeds is selected)
2069    //[self resetInfo]; //if group is already selected, but the torrents in it change
2070   
2071    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2072   
2073    [self setWindowSizeToFit];
2074}
2075
2076//resets filter and sorts torrents
2077- (void) setFilter: (id) sender
2078{
2079    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2080   
2081    NSButton * prevFilterButton;
2082    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2083        prevFilterButton = fPauseFilterButton;
2084    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2085        prevFilterButton = fActiveFilterButton;
2086    else if ([oldFilterType isEqualToString: FILTER_SEED])
2087        prevFilterButton = fSeedFilterButton;
2088    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2089        prevFilterButton = fDownloadFilterButton;
2090    else
2091        prevFilterButton = fNoFilterButton;
2092   
2093    if (sender != prevFilterButton)
2094    {
2095        [prevFilterButton setState: NSOffState];
2096        [sender setState: NSOnState];
2097
2098        NSString * filterType;
2099        if (sender == fActiveFilterButton)
2100            filterType = FILTER_ACTIVE;
2101        else if (sender == fDownloadFilterButton)
2102            filterType = FILTER_DOWNLOAD;
2103        else if (sender == fPauseFilterButton)
2104            filterType = FILTER_PAUSE;
2105        else if (sender == fSeedFilterButton)
2106            filterType = FILTER_SEED;
2107        else
2108            filterType = FILTER_NONE;
2109
2110        [fDefaults setObject: filterType forKey: @"Filter"];
2111    }
2112    else
2113        [sender setState: NSOnState];
2114
2115    [self applyFilter: nil];
2116}
2117
2118- (void) setFilterSearchType: (id) sender
2119{
2120    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2121   
2122    NSInteger prevTag, currentTag = [sender tag];
2123    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2124        prevTag = FILTER_TYPE_TAG_TRACKER;
2125    else
2126        prevTag = FILTER_TYPE_TAG_NAME;
2127   
2128    if (currentTag != prevTag)
2129    {
2130        NSString * filterType;
2131        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2132            filterType = FILTER_TYPE_TRACKER;
2133        else
2134            filterType = FILTER_TYPE_NAME;
2135       
2136        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2137       
2138        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2139    }
2140   
2141    [self applyFilter: nil];
2142}
2143
2144- (void) switchFilter: (id) sender
2145{
2146    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2147   
2148    NSButton * button;
2149    if ([filterType isEqualToString: FILTER_NONE])
2150        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2151    else if ([filterType isEqualToString: FILTER_ACTIVE])
2152        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2153    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2154        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2155    else if ([filterType isEqualToString: FILTER_SEED])
2156        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2157    else if ([filterType isEqualToString: FILTER_PAUSE])
2158        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2159    else
2160        button = fNoFilterButton;
2161   
2162    [self setFilter: button];
2163}
2164
2165- (void) setStatusLabel: (id) sender
2166{
2167    NSString * statusLabel;
2168    switch ([sender tag])
2169    {
2170        case STATUS_RATIO_TOTAL_TAG:
2171            statusLabel = STATUS_RATIO_TOTAL;
2172            break;
2173        case STATUS_RATIO_SESSION_TAG:
2174            statusLabel = STATUS_RATIO_SESSION;
2175            break;
2176        case STATUS_TRANSFER_TOTAL_TAG:
2177            statusLabel = STATUS_TRANSFER_TOTAL;
2178            break;
2179        case STATUS_TRANSFER_SESSION_TAG:
2180            statusLabel = STATUS_TRANSFER_SESSION;
2181            break;
2182        default:
2183            return;
2184    }
2185   
2186    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2187    [self updateUI];
2188}
2189
2190- (void) menuNeedsUpdate: (NSMenu *) menu
2191{
2192    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu || menu == fGroupFilterMenu)
2193    {
2194        const BOOL filter = menu == fGroupFilterMenu;
2195       
2196        const NSInteger remaining = filter ? 3 : 0;
2197        for (NSInteger i = [menu numberOfItems]-1; i >= remaining; i--)
2198            [menu removeItemAtIndex: i];
2199       
2200        NSMenu * groupMenu;
2201        if (!filter)
2202            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2203        else
2204            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:) isSmall: YES];
2205       
2206        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2207        for (NSInteger i = 0; i < groupMenuCount; i++)
2208        {
2209            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2210            [groupMenu removeItemAtIndex: 0];
2211            [menu addItem: item];
2212            [item release];
2213        }
2214    }
2215    else if (menu == fUploadMenu || menu == fDownloadMenu)
2216    {
2217        if ([menu numberOfItems] > 3)
2218            return;
2219       
2220        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, -1 };
2221       
2222        NSMenuItem * item;
2223        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2224        {
2225            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2226                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2227                    keyEquivalent: @""];
2228            [item setTarget: self];
2229            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2230            [menu addItem: item];
2231            [item release];
2232        }
2233    }
2234    else if (menu == fRatioStopMenu)
2235    {
2236        if ([menu numberOfItems] > 3)
2237            return;
2238       
2239        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2240       
2241        NSMenuItem * item;
2242        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2243        {
2244            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2245                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2246            [item setTarget: self];
2247            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2248            [menu addItem: item];
2249            [item release];
2250        }
2251    }
2252    else;
2253}
2254
2255- (void) setGroup: (id) sender
2256{
2257    for (Torrent * torrent in [fTableView selectedTorrents])
2258    {
2259        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2260       
2261        [torrent setGroupValue: [sender tag]];
2262    }
2263   
2264    [self applyFilter: nil];
2265    [self updateUI];
2266    [self updateTorrentHistory];
2267}
2268
2269- (void) setGroupFilter: (id) sender
2270{
2271    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2272    [self updateGroupsFilterButton];
2273    [self applyFilter: nil];
2274}
2275
2276- (void) updateGroupsFilterButton
2277{
2278    NSInteger groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2279   
2280    NSImage * icon;
2281    NSString * toolTip;
2282    if (groupIndex == GROUP_FILTER_ALL_TAG)
2283    {
2284        icon = [NSImage imageNamed: @"PinTemplate.png"];
2285        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2286    }
2287    else
2288    {
2289        icon = [[GroupsController groups] imageForIndex: groupIndex];
2290        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2291                                                : NSLocalizedString(@"None", "Groups -> Button");
2292        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2293    }
2294   
2295    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2296    [fGroupsButton setToolTip: toolTip];
2297}
2298
2299- (void) updateGroupsFilters: (NSNotification *) notification
2300{
2301    [self updateGroupsFilterButton];
2302    [self applyFilter: nil];
2303}
2304
2305- (void) toggleSpeedLimit: (id) sender
2306{
2307    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2308    [fPrefsController applySpeedSettings: nil];
2309}
2310
2311- (void) autoSpeedLimitChange: (NSNotification *) notification
2312{
2313    //clear timer here in case it's not being reset
2314    [fSpeedLimitTimer invalidate];
2315    fSpeedLimitTimer = nil;
2316   
2317    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2318        return;
2319   
2320    NSCalendar * calendar = [NSCalendar currentCalendar];
2321    NSDateComponents * nowComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2322                    * onComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2323                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]],
2324                    * offComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2325                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]];
2326   
2327    //check if should be on if within range
2328    NSInteger onTime = [onComponents hour] * 60 + [onComponents minute],
2329        offTime = [offComponents hour] * 60 + [offComponents minute],
2330        nowTime = [nowComponents hour] * 60 + [nowComponents minute];
2331   
2332    BOOL shouldBeOn = NO;
2333    if (onTime < offTime)
2334        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2335    else if (onTime > offTime)
2336        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2337    else;
2338   
2339    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2340        [self toggleSpeedLimit: nil];
2341   
2342    //no need to set the timer if both times are equal
2343    if (onTime == offTime)
2344        return;
2345   
2346    [self setAutoSpeedLimitTimer: !shouldBeOn];
2347}
2348
2349//only called by fSpeedLimitTimer
2350- (void) autoSpeedLimit: (NSTimer *) timer
2351{
2352    BOOL shouldLimit = [[timer userInfo] boolValue];
2353   
2354    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldLimit)
2355    {
2356        [self toggleSpeedLimit: nil];
2357       
2358        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2359                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2360                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2361            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2362            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2363    }
2364   
2365    [self setAutoSpeedLimitTimer: !shouldLimit];
2366}
2367
2368- (void) setAutoSpeedLimitTimer: (BOOL) nextIsLimit
2369{
2370    NSDate * timerDate = [fDefaults objectForKey: nextIsLimit ? @"SpeedLimitAutoOnDate" : @"SpeedLimitAutoOffDate"];
2371   
2372    //create date with combination of the current date and the date to go off
2373    NSCalendar * calendar = [NSCalendar currentCalendar];
2374    NSDateComponents * nowComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
2375                                        | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2376                    * timerComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: timerDate];
2377   
2378    //check if should be the next day
2379    NSInteger nowTime = [nowComponents hour] * 60 + [nowComponents minute],
2380        timerTime = [timerComponents hour] * 60 + [timerComponents minute];
2381    if (timerTime < nowTime)
2382        [nowComponents setDay: [nowComponents day] + 1]; //properly goes to next month when appropriate
2383   
2384    [nowComponents setHour: [timerComponents hour]];
2385    [nowComponents setMinute: [timerComponents minute]];
2386    [nowComponents setSecond: 0];
2387   
2388    NSDate * dateToUse = [calendar dateFromComponents: nowComponents];
2389   
2390    fSpeedLimitTimer = [[NSTimer alloc] initWithFireDate: dateToUse interval: 0 target: self selector: @selector(autoSpeedLimit:)
2391                        userInfo: [NSNumber numberWithBool: nextIsLimit] repeats: NO];
2392   
2393    NSRunLoop * loop = [NSRunLoop mainRunLoop];
2394    [loop addTimer: fSpeedLimitTimer forMode: NSDefaultRunLoopMode];
2395    [loop addTimer: fSpeedLimitTimer forMode: NSModalPanelRunLoopMode];
2396    [loop addTimer: fSpeedLimitTimer forMode: NSEventTrackingRunLoopMode];
2397    [fSpeedLimitTimer release];
2398}
2399
2400- (void) setLimitGlobalEnabled: (id) sender
2401{
2402    BOOL upload = [sender menu] == fUploadMenu;
2403    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2404   
2405    [fPrefsController applySpeedSettings: nil];
2406}
2407
2408- (void) setQuickLimitGlobal: (id) sender
2409{
2410    BOOL upload = [sender menu] == fUploadMenu;
2411    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2412    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2413   
2414    [fPrefsController updateLimitFields];
2415    [fPrefsController applySpeedSettings: nil];
2416}
2417
2418- (void) setRatioGlobalEnabled: (id) sender
2419{
2420    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2421}
2422
2423- (void) setQuickRatioGlobal: (id) sender
2424{
2425    [fDefaults setBool: YES forKey: @"RatioCheck"];
2426    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2427   
2428    [fPrefsController updateRatioStopField];
2429}
2430
2431- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2432{
2433    fSoundPlaying = NO;
2434}
2435
2436- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2437{
2438    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2439    {
2440        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2441            return;
2442       
2443        if (fAutoImportTimer)
2444        {
2445            if ([fAutoImportTimer isValid])
2446                [fAutoImportTimer invalidate];
2447            [fAutoImportTimer release];
2448            fAutoImportTimer = nil;
2449        }
2450       
2451        //check again in 10 seconds in case torrent file wasn't complete
2452        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2453            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2454       
2455        [self checkAutoImportDirectory];
2456    }
2457}
2458
2459- (void) changeAutoImport
2460{
2461    if (fAutoImportTimer)
2462    {
2463        if ([fAutoImportTimer isValid])
2464            [fAutoImportTimer invalidate];
2465        [fAutoImportTimer release];
2466        fAutoImportTimer = nil;
2467    }
2468   
2469    if (fAutoImportedNames)
2470    {
2471        [fAutoImportedNames release];
2472        fAutoImportedNames = nil;
2473    }
2474   
2475    [self checkAutoImportDirectory];
2476}
2477
2478- (void) checkAutoImportDirectory
2479{
2480    NSString * path;
2481    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2482        return;
2483   
2484    path = [path stringByExpandingTildeInPath];
2485   
2486    NSArray * importedNames;
2487    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2488        return;
2489   
2490    //only check files that have not been checked yet
2491    NSMutableArray * newNames = [importedNames mutableCopy];
2492   
2493    if (fAutoImportedNames)
2494        [newNames removeObjectsInArray: fAutoImportedNames];
2495    else
2496        fAutoImportedNames = [[NSMutableArray alloc] init];
2497    [fAutoImportedNames setArray: importedNames];
2498   
2499    for (NSInteger i = [newNames count] - 1; i >= 0; i--)
2500    {
2501        NSString * file = [newNames objectAtIndex: i];
2502        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2503            [newNames removeObjectAtIndex: i];
2504        else
2505            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2506    }
2507   
2508    for (NSString * file in newNames)
2509    {
2510        tr_ctor * ctor = tr_ctorNew(fLib);
2511        tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2512       
2513        switch (tr_torrentParse(fLib, ctor, NULL))
2514        {
2515            case TR_OK:
2516                [self openFiles: [NSArray arrayWithObject: file] addType: ADD_AUTO forcePath: nil];
2517               
2518                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2519                    description: [file lastPathComponent] notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2520                    clickContext: nil];
2521                break;
2522           
2523            case TR_EINVALID:
2524                [fAutoImportedNames removeObject: [file lastPathComponent]];
2525        }
2526       
2527        tr_ctorFree(ctor);
2528    }
2529   
2530    [newNames release];
2531}
2532
2533- (void) beginCreateFile: (NSNotification *) notification
2534{
2535    if (![fDefaults boolForKey: @"AutoImport"])
2536        return;
2537   
2538    NSString * location = [notification object],
2539            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2540   
2541    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2542                                    isEqualToString: [path stringByExpandingTildeInPath]])
2543        [fAutoImportedNames addObject: [location lastPathComponent]];
2544}
2545
2546- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2547{
2548    if (item)
2549        return [[item torrents] count];
2550    else
2551        return [fDisplayedTorrents count];
2552}
2553
2554- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2555{
2556    if (item)
2557        return [[item torrents] objectAtIndex: index];
2558    else
2559        return [fDisplayedTorrents objectAtIndex: index];
2560}
2561
2562- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2563{
2564    return ![item isKindOfClass: [Torrent class]];
2565}
2566
2567- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2568{
2569    if ([item isKindOfClass: [Torrent class]])
2570        return [item hashString];
2571    else
2572    {
2573        NSString * ident = [tableColumn identifier];
2574        if ([ident isEqualToString: @"Group"])
2575        {
2576            NSInteger group = [item groupIndex];
2577            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2578                                : NSLocalizedString(@"No Group", "Group table row");
2579        }
2580        else if ([ident isEqualToString: @"Color"])
2581        {
2582            NSInteger group = [item groupIndex];
2583            return [[GroupsController groups] imageForIndex: group];
2584        }
2585        else if ([ident isEqualToString: @"DL Image"])
2586            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2587        else if ([ident isEqualToString: @"UL Image"])
2588            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2589                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2590        else
2591        {
2592            TorrentGroup * group = (TorrentGroup *)item;
2593           
2594            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2595                return [NSString stringForRatio: [group ratio]];
2596            else
2597            {
2598                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2599                return [NSString stringForSpeed: rate];
2600            }
2601        }
2602    }
2603}
2604
2605- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2606{
2607    //only allow reordering of rows if sorting by order
2608    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2609    {
2610        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2611        for (id torrent in items)
2612        {
2613            if (![torrent isKindOfClass: [Torrent class]])
2614                return NO;
2615           
2616            [indexSet addIndex: [fTableView rowForItem: torrent]];
2617        }
2618       
2619        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2620        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2621        return YES;
2622    }
2623    return NO;
2624}
2625
2626- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2627    proposedChildIndex: (NSInteger) index
2628{
2629    NSPasteboard * pasteboard = [info draggingPasteboard];
2630    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2631    {
2632        if ([fDefaults boolForKey: @"SortByGroup"])
2633        {
2634            if (!item)
2635                return NSDragOperationNone;
2636           
2637            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2638            {
2639                if ([item isKindOfClass: [Torrent class]])
2640                {
2641                    TorrentGroup * group = [fTableView parentForItem: item];
2642                    index = [[group torrents] indexOfObject: item] + 1;
2643                    item = group;
2644                }
2645            }
2646            else
2647            {
2648                if ([item isKindOfClass: [Torrent class]])
2649                    item = [fTableView parentForItem: item];
2650                index = NSOutlineViewDropOnItemIndex;
2651            }
2652        }
2653        else
2654        {
2655            if (item)
2656            {
2657                index = [fTableView rowForItem: item] + 1;
2658                item = nil;
2659            }
2660        }
2661       
2662        [fTableView setDropItem: item dropChildIndex: index];
2663        return NSDragOperationGeneric;
2664    }
2665   
2666    return NSDragOperationNone;
2667}
2668
2669- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2670    childIndex: (NSInteger) newRow
2671{
2672    NSPasteboard * pasteboard = [info draggingPasteboard];
2673    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2674    {
2675        //remember selected rows
2676        NSArray * selectedValues = [fTableView selectedValues];
2677   
2678        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2679       
2680        //get the torrents to move
2681        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2682        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2683            [movingTorrents addObject: [fTableView itemAtRow: i]];
2684       
2685        //reset groups
2686        if (item)
2687        {
2688            //change groups
2689            NSInteger groupValue = [item groupIndex];
2690            for (Torrent * torrent in movingTorrents)
2691            {
2692                //have to reset objects here to avoid weird crash
2693                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2694                [[item torrents] addObject: torrent];
2695               
2696                [torrent setGroupValue: groupValue];
2697            }
2698            //part 2 of avoiding weird crash
2699            [fTableView reloadItem: nil reloadChildren: YES];
2700        }
2701       
2702        //reorder queue order
2703        if (newRow != NSOutlineViewDropOnItemIndex)
2704        {
2705            //find torrent to place under
2706            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2707            Torrent * topTorrent = nil;
2708            for (NSInteger i = newRow-1; i >= 0; i--)
2709            {
2710                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2711                if (![movingTorrents containsObject: tempTorrent])
2712                {
2713                    topTorrent = tempTorrent;
2714                    break;
2715                }
2716            }
2717           
2718            //remove objects to reinsert
2719            [fTorrents removeObjectsInArray: movingTorrents];
2720           
2721            //insert objects at new location
2722            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2723            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2724            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2725           
2726            //redo order values
2727            for (NSInteger i = 0; i < [fTorrents count]; i++)
2728                [[fTorrents objectAtIndex: i] setOrderValue: i];
2729        }
2730       
2731        [self applyFilter: nil];
2732        [fTableView selectValues: selectedValues];
2733    }
2734   
2735    return YES;
2736}
2737
2738- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2739{
2740    [self resetInfo];
2741}
2742
2743- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2744{
2745    NSPasteboard * pasteboard = [info draggingPasteboard];
2746    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2747    {
2748        //check if any torrent files can be added
2749        BOOL torrent = NO;
2750        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2751        for (NSString * file in files)
2752        {
2753            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2754            {
2755                tr_ctor * ctor = tr_ctorNew(fLib);
2756                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2757                switch (tr_torrentParse(fLib, ctor, NULL))
2758                {
2759                    case TR_OK:
2760                        if (!fOverlayWindow)
2761                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2762                        [fOverlayWindow setTorrents: files];
2763                       
2764                        return NSDragOperationCopy;
2765                   
2766                    case TR_EDUPLICATE:
2767                        torrent = YES;
2768                }
2769                tr_ctorFree(ctor);
2770            }
2771        }
2772       
2773        //create a torrent file if a single file
2774        if (!torrent && [files count] == 1)
2775        {
2776            if (!fOverlayWindow)
2777                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2778            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2779           
2780            return NSDragOperationCopy;
2781        }
2782    }
2783    else if ([[pasteboard types] containsObject: NSURLPboardType])
2784    {
2785        if (!fOverlayWindow)
2786            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2787        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2788       
2789        return NSDragOperationCopy;
2790    }
2791    else;
2792   
2793    return NSDragOperationNone;
2794}
2795
2796- (void) draggingExited: (id <NSDraggingInfo>) info
2797{
2798    if (fOverlayWindow)
2799        [fOverlayWindow fadeOut];
2800}
2801
2802- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2803{
2804    if (fOverlayWindow)
2805        [fOverlayWindow fadeOut];
2806   
2807    NSPasteboard * pasteboard = [info draggingPasteboard];
2808    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2809    {
2810        BOOL torrent = NO, accept = YES;
2811       
2812        //create an array of files that can be opened
2813        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2814        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2815        for (NSString * file in files)
2816        {
2817            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2818            {
2819                tr_ctor * ctor = tr_ctorNew(fLib);
2820                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2821                switch (tr_torrentParse(fLib, ctor, NULL))
2822                {
2823                    case TR_OK:
2824                        [filesToOpen addObject: file];
2825                        torrent = YES;
2826                        break;
2827                       
2828                    case TR_EDUPLICATE:
2829                        torrent = YES;
2830                }
2831                tr_ctorFree(ctor);
2832            }
2833        }
2834       
2835        if ([filesToOpen count] > 0)
2836            [self application: NSApp openFiles: filesToOpen];
2837        else
2838        {
2839            if (!torrent && [files count] == 1)
2840                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2841            else
2842                accept = NO;
2843        }
2844        [filesToOpen release];
2845       
2846        return accept;
2847    }
2848    else if ([[pasteboard types] containsObject: NSURLPboardType])
2849    {
2850        NSURL * url;
2851        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2852        {
2853            [self openURL: url];
2854            return YES;
2855        }
2856    }
2857    else;
2858   
2859    return NO;
2860}
2861
2862- (void) toggleSmallView: (id) sender
2863{
2864    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2865    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2866   
2867    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2868   
2869    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2870   
2871    //window min height
2872    NSSize contentMinSize = [fWindow contentMinSize],
2873            contentSize = [[fWindow contentView] frame].size;
2874    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2875                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2876    [fWindow setContentMinSize: contentMinSize];
2877   
2878    //resize for larger min height if not set to auto size
2879    if (![fDefaults boolForKey: @"AutoSize"])
2880    {
2881        if (!makeSmall && contentSize.height < contentMinSize.height)
2882        {
2883            NSRect frame = [fWindow frame];
2884            CGFloat heightChange = contentMinSize.height - contentSize.height;
2885            frame.size.height += heightChange;
2886            frame.origin.y -= heightChange;
2887           
2888            [fWindow setFrame: frame display: YES];
2889        }
2890    }
2891    else
2892        [self setWindowSizeToFit];
2893}
2894
2895- (void) togglePiecesBar: (id) sender
2896{
2897    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2898    [fTableView togglePiecesBar];
2899}
2900
2901- (void) toggleAvailabilityBar: (id) sender
2902{
2903    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2904    [fTableView display];
2905}
2906
2907- (void) toggleStatusString: (id) sender
2908{
2909    if ([fDefaults boolForKey: @"SmallView"])
2910        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2911    else
2912        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2913   
2914    [fTableView reloadData];
2915}
2916
2917- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2918{
2919    NSScrollView * scrollView = [fTableView enclosingScrollView];
2920   
2921    //convert pixels to points
2922    NSRect windowFrame = [fWindow frame];
2923    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2924    windowSize.height += height;
2925   
2926    if (check)
2927    {
2928        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2929       
2930        if (windowSize.height < minSize.height)
2931            windowSize.height = minSize.height;
2932        else
2933        {
2934            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2935            if ([fStatusBar isHidden])
2936                maxSize.height -= [fStatusBar frame].size.height;
2937            if ([fFilterBar isHidden])
2938                maxSize.height -= [fFilterBar frame].size.height;
2939            if (windowSize.height > maxSize.height)
2940                windowSize.height = maxSize.height;
2941        }
2942    }
2943
2944    //convert points to pixels
2945    windowSize = [scrollView convertSize: windowSize toView: nil];
2946
2947    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2948    windowFrame.size.height = windowSize.height;
2949    return windowFrame;
2950}
2951
2952- (void) toggleStatusBar: (id) sender
2953{
2954    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2955    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2956}
2957
2958//doesn't save shown state
2959- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2960{
2961    if (show != [fStatusBar isHidden])
2962        return;
2963
2964    if (show)
2965        [fStatusBar setHidden: NO];
2966
2967    NSRect frame;
2968    CGFloat heightChange = [fStatusBar frame].size.height;
2969    if (!show)
2970        heightChange *= -1;
2971   
2972    //allow bar to show even if not enough room
2973    if (show && ![fDefaults boolForKey: @"AutoSize"])
2974    {
2975        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2976        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2977        if (change < 0.0)
2978        {
2979            frame = [fWindow frame];
2980            frame.size.height += change;
2981            frame.origin.y -= change;
2982            [fWindow setFrame: frame display: NO animate: NO];
2983        }
2984    }
2985
2986    [self updateUI];
2987   
2988    NSScrollView * scrollView = [fTableView enclosingScrollView];
2989   
2990    //set views to not autoresize
2991    NSUInteger statsMask = [fStatusBar autoresizingMask];
2992    NSUInteger filterMask = [fFilterBar autoresizingMask];
2993    NSUInteger scrollMask = [scrollView autoresizingMask];
2994    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2995    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2996    [scrollView setAutoresizingMask: NSViewNotSizable];
2997   
2998    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2999    [fWindow setFrame: frame display: YES animate: animate];
3000   
3001    //re-enable autoresize
3002    [fStatusBar setAutoresizingMask: statsMask];
3003    [fFilterBar setAutoresizingMask: filterMask];
3004    [scrollView setAutoresizingMask: scrollMask];
3005   
3006    //change min size
3007    NSSize minSize = [fWindow contentMinSize];
3008    minSize.height += heightChange;
3009    [fWindow setContentMinSize: minSize];
3010   
3011    if (!show)
3012        [fStatusBar setHidden: YES];
3013}
3014
3015- (void) toggleFilterBar: (id) sender
3016{
3017    //disable filtering when hiding
3018    if (![fFilterBar isHidden])
3019    {
3020        [fSearchFilterField setStringValue: @""];
3021        [self setFilter: fNoFilterButton];
3022        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3023    }
3024
3025    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3026    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3027}
3028
3029//doesn't save shown state
3030- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3031{
3032    if (show != [fFilterBar isHidden])
3033        return;
3034
3035    if (show)
3036        [fFilterBar setHidden: NO];
3037
3038    NSRect frame;
3039    CGFloat heightChange = [fFilterBar frame].size.height;
3040    if (!show)
3041        heightChange *= -1;
3042   
3043    //allow bar to show even if not enough room
3044    if (show && ![fDefaults boolForKey: @"AutoSize"])
3045    {
3046        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3047        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3048        if (change < 0.0)
3049        {
3050            frame = [fWindow frame];
3051            frame.size.height += change;
3052            frame.origin.y -= change;
3053            [fWindow setFrame: frame display: NO animate: NO];
3054        }
3055    }
3056   
3057    NSScrollView * scrollView = [fTableView enclosingScrollView];
3058
3059    //set views to not autoresize
3060    NSUInteger filterMask = [fFilterBar autoresizingMask];
3061    NSUInteger scrollMask = [scrollView autoresizingMask];
3062    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3063    [scrollView setAutoresizingMask: NSViewNotSizable];
3064   
3065    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3066    [fWindow setFrame: frame display: YES animate: animate];
3067   
3068    //re-enable autoresize
3069    [fFilterBar setAutoresizingMask: filterMask];
3070    [scrollView setAutoresizingMask: scrollMask];
3071   
3072    //change min size
3073    NSSize minSize = [fWindow contentMinSize];
3074    minSize.height += heightChange;
3075    [fWindow setContentMinSize: minSize];
3076   
3077    if (!show)
3078    {
3079        [fFilterBar setHidden: YES];
3080        [fWindow makeFirstResponder: fTableView];
3081    }
3082}
3083
3084- (void) focusFilterField
3085{
3086    [fWindow makeFirstResponder: fSearchFilterField];
3087    if ([fFilterBar isHidden])
3088        [self toggleFilterBar: self];
3089}
3090
3091- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3092{
3093    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3094   
3095    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3096    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3097    [button setStringValue: @""];
3098   
3099    [item setView: button];
3100    [button release];
3101   
3102    NSSize buttonSize = NSMakeSize(36.0, 25.0);
3103    [item setMinSize: buttonSize];
3104    [item setMaxSize: buttonSize];
3105   
3106    return [item autorelease];
3107}
3108
3109- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3110{
3111    if ([ident isEqualToString: TOOLBAR_CREATE])
3112    {
3113        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3114       
3115        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3116        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3117        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3118        [item setImage: [NSImage imageNamed: @"Create.png"]];
3119        [item setTarget: self];
3120        [item setAction: @selector(createFile:)];
3121        [item setAutovalidates: NO];
3122       
3123        return item;
3124    }
3125    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3126    {
3127        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3128       
3129        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3130        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3131        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3132        [item setImage: [NSImage imageNamed: @"Open.png"]];
3133        [item setTarget: self];
3134        [item setAction: @selector(openShowSheet:)];
3135        [item setAutovalidates: NO];
3136       
3137        return item;
3138    }
3139    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3140    {
3141        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3142       
3143        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3144        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3145        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3146        [item setImage: [NSImage imageNamed: @"OpenWeb.png"]];
3147        [item setTarget: self];
3148        [item setAction: @selector(openURLShowSheet:)];
3149        [item setAutovalidates: NO];
3150       
3151        return item;
3152    }
3153    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3154    {
3155        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3156       
3157        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3158        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3159        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3160        [item setImage: [NSImage imageNamed: @"Remove.png"]];
3161        [item setTarget: self];
3162        [item setAction: @selector(removeNoDelete:)];
3163       
3164        return item;
3165    }
3166    else if ([ident isEqualToString: TOOLBAR_INFO])
3167    {
3168        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3169       
3170        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3171        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3172        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3173        [item setImage: [NSImage imageNamed: @"Info.png"]];
3174        [item setTarget: self];
3175        [item setAction: @selector(showInfo:)];
3176       
3177        return item;
3178    }
3179    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3180    {
3181        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3182       
3183        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3184        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3185        [groupItem setView: segmentedControl];
3186        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3187       
3188        [segmentedControl setSegmentCount: 2];
3189        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3190       
3191        NSSize groupSize = NSMakeSize(72.0, 25.0);
3192        [groupItem setMinSize: groupSize];
3193        [groupItem setMaxSize: groupSize];
3194       
3195        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3196        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3197        [groupItem setTarget: self];
3198        [groupItem setAction: @selector(allToolbarClicked:)];
3199       
3200        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3201       
3202        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3203        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
3204        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3205                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3206       
3207        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3208        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
3209        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3210                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3211       
3212        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3213                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3214       
3215        [segmentedControl release];
3216        return [groupItem autorelease];
3217    }
3218    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3219    {
3220        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3221       
3222        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3223        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3224        [groupItem setView: segmentedControl];
3225        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3226       
3227        [segmentedControl setSegmentCount: 2];
3228        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3229       
3230        NSSize groupSize = NSMakeSize(72.0, 25.0);
3231        [groupItem setMinSize: groupSize];
3232        [groupItem setMaxSize: groupSize];
3233       
3234        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3235        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3236        [groupItem setTarget: self];
3237        [groupItem setAction: @selector(selectedToolbarClicked:)];
3238       
3239        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3240       
3241        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3242        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
3243        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3244                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3245       
3246        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3247        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
3248        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3249                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3250       
3251        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3252                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3253       
3254        [segmentedControl release];
3255        return [groupItem autorelease];
3256    }
3257    else if ([ident isEqualToString: TOOLBAR_FILTER])
3258    {
3259        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3260       
3261        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3262        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3263        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3264        [item setImage: [NSImage imageNamed: @"Filter.png"]];
3265        [item setTarget: self];
3266        [item setAction: @selector(toggleFilterBar:)];
3267       
3268        return item;
3269    }
3270    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3271    {
3272        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3273       
3274        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3275        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3276        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3277        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3278        [item setTarget: self];
3279        [item setAction: @selector(toggleQuickLook:)];
3280       
3281        return item;
3282    }
3283    else
3284        return nil;
3285}
3286
3287- (void) allToolbarClicked: (id) sender
3288{
3289    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3290                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3291    switch (tagValue)
3292    {
3293        case TOOLBAR_PAUSE_TAG:
3294            [self stopAllTorrents: sender];
3295            break;
3296        case TOOLBAR_RESUME_TAG:
3297            [self resumeAllTorrents: sender];
3298            break;
3299    }
3300}
3301
3302- (void) selectedToolbarClicked: (id) sender
3303{
3304    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3305                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3306    switch (tagValue)
3307    {
3308        case TOOLBAR_PAUSE_TAG:
3309            [self stopSelectedTorrents: sender];
3310            break;
3311        case TOOLBAR_RESUME_TAG:
3312            [self resumeSelectedTorrents: sender];
3313            break;
3314    }
3315}
3316
3317- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3318{
3319    return [NSArray arrayWithObjects:
3320            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3321            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3322            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3323            NSToolbarSeparatorItemIdentifier,
3324            NSToolbarSpaceItemIdentifier,
3325            NSToolbarFlexibleSpaceItemIdentifier,
3326            NSToolbarCustomizeToolbarItemIdentifier, nil];
3327}
3328
3329- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3330{
3331    return [NSArray arrayWithObjects:
3332            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSeparatorItemIdentifier,
3333            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3334            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3335}
3336
3337- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3338{
3339    NSString * ident = [toolbarItem itemIdentifier];
3340   
3341    //enable remove item
3342    if ([ident isEqualToString: TOOLBAR_REMOVE])
3343        return [fTableView numberOfSelectedRows] > 0;
3344
3345    //enable pause all item
3346    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3347    {
3348        for (Torrent * torrent in fTorrents)
3349            if ([torrent isActive] || [torrent waitingToStart])
3350                return YES;
3351        return NO;
3352    }
3353
3354    //enable resume all item
3355    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3356    {
3357        for (Torrent * torrent in fTorrents)
3358            if (![torrent isActive] && ![torrent waitingToStart])
3359                return YES;
3360        return NO;
3361    }
3362
3363    //enable pause item
3364    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3365    {
3366        for (Torrent * torrent in [fTableView selectedTorrents])
3367            if ([torrent isActive] || [torrent waitingToStart])
3368                return YES;
3369        return NO;
3370    }
3371   
3372    //enable resume item
3373    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3374    {
3375        for (Torrent * torrent in [fTableView selectedTorrents])
3376            if (![torrent isActive] && ![torrent waitingToStart])
3377                return YES;
3378        return NO;
3379    }
3380   
3381    //set info image
3382    if ([ident isEqualToString: TOOLBAR_INFO])
3383    {
3384        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue.png"]
3385                                                                    : [NSImage imageNamed: @"Info.png"]];
3386        return YES;
3387    }
3388   
3389    //set filter image
3390    if ([ident isEqualToString: TOOLBAR_FILTER])
3391    {
3392        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue.png"] : [NSImage imageNamed: @"Filter.png"]];
3393        return YES;
3394    }
3395   
3396    //enable quicklook item
3397    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3398        return [[QuickLookController quickLook] canQuickLook];
3399
3400    return YES;
3401}
3402
3403- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3404{
3405    SEL action = [menuItem action];
3406   
3407    if (action == @selector(toggleSpeedLimit:))
3408    {
3409        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3410        return YES;
3411    }
3412   
3413    //only enable some items if it is in a context menu or the window is useable
3414    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3415
3416    //enable open items
3417    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3418        return [fWindow attachedSheet] == nil;
3419   
3420    //enable sort options
3421    if (action == @selector(setSort:))
3422    {
3423        NSString * sortType;
3424        switch ([menuItem tag])
3425        {
3426            case SORT_ORDER_TAG:
3427                sortType = SORT_ORDER;
3428                break;
3429            case SORT_DATE_TAG:
3430                sortType = SORT_DATE;
3431                break;
3432            case SORT_NAME_TAG:
3433                sortType = SORT_NAME;
3434                break;
3435            case SORT_PROGRESS_TAG:
3436                sortType = SORT_PROGRESS;
3437                break;
3438            case SORT_STATE_TAG:
3439                sortType = SORT_STATE;
3440                break;
3441            case SORT_TRACKER_TAG:
3442                sortType = SORT_TRACKER;
3443                break;
3444            case SORT_ACTIVITY_TAG:
3445                sortType = SORT_ACTIVITY;
3446        }
3447       
3448        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3449        return [fWindow isVisible];
3450    }
3451   
3452    //enable sort options
3453    if (action == @selector(setStatusLabel:))
3454    {
3455        NSString * statusLabel;
3456        switch ([menuItem tag])
3457        {
3458            case STATUS_RATIO_TOTAL_TAG:
3459                statusLabel = STATUS_RATIO_TOTAL;
3460                break;
3461            case STATUS_RATIO_SESSION_TAG:
3462                statusLabel = STATUS_RATIO_SESSION;
3463                break;
3464            case STATUS_TRANSFER_TOTAL_TAG:
3465                statusLabel = STATUS_TRANSFER_TOTAL;
3466                break;
3467            case STATUS_TRANSFER_SESSION_TAG:
3468                statusLabel = STATUS_TRANSFER_SESSION;
3469        }
3470       
3471        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3472        return YES;
3473    }
3474   
3475    if (action == @selector(setGroup:))
3476    {
3477        BOOL checked = NO;
3478       
3479        NSInteger index = [menuItem tag];
3480        for (Torrent * torrent in [fTableView selectedTorrents])
3481            if (index == [torrent groupValue])
3482            {
3483                checked = YES;
3484                break;
3485            }
3486       
3487        [menuItem setState: checked ? NSOnState : NSOffState];
3488        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3489    }
3490   
3491    if (action == @selector(setGroupFilter:))
3492    {
3493        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3494        return YES;
3495    }
3496   
3497    if (action == @selector(toggleSmallView:))
3498    {
3499        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3500        return [fWindow isVisible];
3501    }
3502   
3503    if (action == @selector(togglePiecesBar:))
3504    {
3505        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3506        return [fWindow isVisible];
3507    }
3508   
3509    if (action == @selector(toggleStatusString:))
3510    {
3511        if ([fDefaults boolForKey: @"SmallView"])
3512        {
3513            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3514            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3515        }
3516        else
3517        {
3518            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3519            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3520        }
3521       
3522        return [fWindow isVisible];
3523    }
3524   
3525    if (action == @selector(toggleAvailabilityBar:))
3526    {
3527        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3528        return [fWindow isVisible];
3529    }
3530   
3531    if (action == @selector(setLimitGlobalEnabled:))
3532    {
3533        BOOL upload = [menuItem menu] == fUploadMenu;
3534        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3535        if (limit)
3536            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3537                                    "Action menu -> upload/download limit"),
3538                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3539       
3540        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3541        return YES;
3542    }
3543   
3544    if (action == @selector(setRatioGlobalEnabled:))
3545    {
3546        BOOL check = menuItem == fCheckRatioItem;
3547        if (check)
3548            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3549                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3550       
3551        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3552        return YES;
3553    }
3554
3555    //enable show info
3556    if (action == @selector(showInfo:))
3557    {
3558        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3559                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3560        [menuItem setTitle: title];
3561
3562        return YES;
3563    }
3564   
3565    //enable prev/next inspector tab
3566    if (action == @selector(setInfoTab:))
3567        return [[fInfoController window] isVisible];
3568   
3569    //enable toggle status bar
3570    if (action == @selector(toggleStatusBar:))
3571    {
3572        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3573                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3574        [menuItem setTitle: title];
3575
3576        return [fWindow isVisible];
3577    }
3578   
3579    //enable toggle filter bar
3580    if (action == @selector(toggleFilterBar:))
3581    {
3582        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3583                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3584        [menuItem setTitle: title];
3585
3586        return [fWindow isVisible];
3587    }
3588   
3589    //enable prev/next filter button
3590    if (action == @selector(switchFilter:))
3591        return [fWindow isVisible] && ![fFilterBar isHidden];
3592   
3593    //enable quicklook item
3594    if (action == @selector(toggleQuickLook:))
3595        return [[QuickLookController quickLook] canQuickLook];
3596   
3597    //enable reveal in finder
3598    if (action == @selector(revealFile:))
3599        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3600
3601    //enable remove items
3602    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3603        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3604    {
3605        BOOL warning = NO,
3606            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3607            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3608       
3609        for (Torrent * torrent in [fTableView selectedTorrents])
3610        {
3611            if (!warning && [torrent isActive])
3612            {
3613                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3614                if (warning && canDelete)
3615                    break;
3616            }
3617            if (!canDelete && [torrent publicTorrent])
3618            {
3619                canDelete = YES;
3620                if (warning)
3621                    break;
3622            }
3623        }
3624   
3625        //append or remove ellipsis when needed
3626        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3627        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3628        {
3629            if (![title hasSuffix: ellipsis])
3630                [menuItem setTitle: [title stringByAppendingEllipsis]];
3631        }
3632        else
3633        {
3634            if ([title hasSuffix: ellipsis])
3635                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3636        }
3637       
3638        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3639    }
3640
3641    //enable pause all item
3642    if (action == @selector(stopAllTorrents:))
3643    {
3644        for (Torrent * torrent in fTorrents)
3645            if ([torrent isActive] || [torrent waitingToStart])
3646                return YES;
3647        return NO;
3648    }
3649   
3650    //enable resume all item
3651    if (action == @selector(resumeAllTorrents:))
3652    {
3653        for (Torrent * torrent in fTorrents)
3654            if (![torrent isActive] && ![torrent waitingToStart])
3655                return YES;
3656        return NO;
3657    }
3658   
3659    //enable resume all waiting item
3660    if (action == @selector(resumeWaitingTorrents:))
3661    {
3662        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3663            return NO;
3664   
3665        for (Torrent * torrent in fTorrents)
3666            if (![torrent isActive] && [torrent waitingToStart])
3667                return YES;
3668        return NO;
3669    }
3670   
3671    //enable resume selected waiting item
3672    if (action == @selector(resumeSelectedTorrentsNoWait:))
3673    {
3674        if (!canUseTable)
3675            return NO;
3676       
3677        for (Torrent * torrent in [fTableView selectedTorrents])
3678            if (![torrent isActive])
3679                return YES;
3680        return NO;
3681    }
3682
3683    //enable pause item
3684    if (action == @selector(stopSelectedTorrents:))
3685    {
3686        if (!canUseTable)
3687            return NO;
3688   
3689        for (Torrent * torrent in [fTableView selectedTorrents])
3690            if ([torrent isActive] || [torrent waitingToStart])
3691                return YES;
3692        return NO;
3693    }
3694   
3695    //enable resume item
3696    if (action == @selector(resumeSelectedTorrents:))
3697    {
3698        if (!canUseTable)
3699            return NO;
3700   
3701        for (Torrent * torrent in [fTableView selectedTorrents])
3702            if (![torrent isActive] && ![torrent waitingToStart])
3703                return YES;
3704        return NO;
3705    }
3706   
3707    //enable manual announce item
3708    if (action == @selector(announceSelectedTorrents:))
3709    {
3710        if (!canUseTable)
3711            return NO;
3712       
3713        for (Torrent * torrent in [fTableView selectedTorrents])
3714            if ([torrent canManualAnnounce])
3715                return YES;
3716        return NO;
3717    }
3718   
3719    //enable reset cache item
3720    if (action == @selector(verifySelectedTorrents:))
3721        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3722   
3723    //enable move torrent file item
3724    if (action == @selector(moveDataFilesSelected:))
3725        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3726   
3727    //enable copy torrent file item
3728    if (action == @selector(copyTorrentFiles:))
3729        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3730   
3731    //enable reverse sort item
3732    if (action == @selector(setSortReverse:))
3733    {
3734        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3735        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3736    }
3737   
3738    //enable group sort item
3739    if (action == @selector(setSortByGroup:))
3740    {
3741        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3742        return YES;
3743    }
3744   
3745    //check proper filter search item
3746    if (action == @selector(setFilterSearchType:))
3747    {
3748        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3749       
3750        BOOL state;
3751        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3752            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3753        else
3754            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3755       
3756        [menuItem setState: state ? NSOnState : NSOffState];
3757        return YES;
3758    }
3759   
3760    return YES;
3761}
3762
3763- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3764{
3765    switch (messageType)
3766    {
3767        case kIOMessageSystemWillSleep:
3768            //if there are any running transfers, wait 15 seconds for them to stop
3769            for (Torrent * torrent in fTorrents)
3770                if ([torrent isActive])
3771                {
3772                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3773                    [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3774                    sleep(15);
3775                    break;
3776                }
3777
3778            IOAllowPowerChange(fRootPort, (long) messageArgument);
3779            break;
3780
3781        case kIOMessageCanSystemSleep:
3782            if ([fDefaults boolForKey: @"SleepPrevent"])
3783            {
3784                //prevent idle sleep unless no torrents are active
3785                for (Torrent * torrent in fTorrents)
3786                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3787                    {
3788                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3789                        return;
3790                    }
3791            }
3792           
3793            IOAllowPowerChange(fRootPort, (long) messageArgument);
3794            break;
3795
3796        case kIOMessageSystemHasPoweredOn:
3797            //resume sleeping transfers after we wake up
3798            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3799            [self autoSpeedLimitChange: nil];
3800            break;
3801    }
3802}
3803
3804- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3805{
3806    NSInteger seeding = 0, downloading = 0;
3807    for (Torrent * torrent in fTorrents)
3808    {
3809        if ([torrent isSeeding])
3810            seeding++;
3811        else if ([torrent isActive])
3812            downloading++;
3813        else;
3814    }
3815   
3816    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3817            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3818   
3819    BOOL hasSeparator = seedingItem || downloadingItem;
3820   
3821    if (seeding > 0)
3822    {
3823        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3824        if (!seedingItem)
3825        {
3826            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3827            [seedingItem setTag: DOCK_SEEDING_TAG];
3828            [fDockMenu insertItem: seedingItem atIndex: 0];
3829        }
3830        else
3831            [seedingItem setTitle: title];
3832    }
3833    else
3834    {
3835        if (seedingItem)
3836            [fDockMenu removeItem: seedingItem];
3837    }
3838   
3839    if (downloading > 0)
3840    {
3841        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3842        if (!downloadingItem)
3843        {
3844            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3845            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3846            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3847        }
3848        else
3849            [downloadingItem setTitle: title];
3850    }
3851    else
3852    {
3853        if (downloadingItem)
3854            [fDockMenu removeItem: downloadingItem];
3855    }
3856   
3857    if (seeding > 0 || downloading > 0)
3858    {
3859        if (!hasSeparator)
3860            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3861    }
3862    else
3863    {
3864        if (hasSeparator)
3865            [fDockMenu removeItemAtIndex: 0];
3866    }
3867   
3868    return fDockMenu;
3869}
3870
3871- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3872{
3873    //if auto size is enabled, the current frame shouldn't need to change
3874    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3875   
3876    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3877    return frame;
3878}
3879
3880- (void) setWindowSizeToFit
3881{
3882    if ([fDefaults boolForKey: @"AutoSize"])
3883    {
3884        NSScrollView * scrollView = [fTableView enclosingScrollView];
3885       
3886        [scrollView setHasVerticalScroller: NO];
3887        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3888        [scrollView setHasVerticalScroller: YES];
3889       
3890        //hack to ensure scrollbars don't disappear after resizing
3891        [scrollView setAutohidesScrollers: NO];
3892        [scrollView setAutohidesScrollers: YES];
3893    }
3894}
3895
3896- (NSRect) sizedWindowFrame
3897{
3898    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3899                    ? [fDisplayedTorrents count] : 0;
3900   
3901    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3902                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3903                        - [[fTableView enclosingScrollView] frame].size.height;
3904   
3905    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3906}
3907
3908- (void) updateForExpandCollape
3909{
3910    [self setWindowSizeToFit];
3911    [self setBottomCountText: YES];
3912}
3913
3914- (void) showMainWindow: (id) sender
3915{
3916    [fWindow makeKeyAndOrderFront: nil];
3917}
3918
3919- (void) windowDidBecomeMain: (NSNotification *) notification
3920{
3921    [fBadger clearCompleted];
3922    [self updateUI];
3923}
3924
3925- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3926{
3927    //only resize horizontally if autosize is enabled
3928    if ([fDefaults boolForKey: @"AutoSize"])
3929        proposedFrameSize.height = [fWindow frame].size.height;
3930    return proposedFrameSize;
3931}
3932
3933- (void) windowDidResize: (NSNotification *) notification
3934{
3935    if (![fStatusBar isHidden])
3936        [self resizeStatusButton];
3937   
3938    if ([fFilterBar isHidden])
3939        return;
3940   
3941    //replace all buttons
3942    [fActiveFilterButton sizeToFit];
3943    [fDownloadFilterButton sizeToFit];
3944    [fSeedFilterButton sizeToFit];
3945    [fPauseFilterButton sizeToFit];
3946   
3947    NSRect activeRect = [fActiveFilterButton frame];
3948   
3949    NSRect downloadRect = [fDownloadFilterButton frame];
3950    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
3951   
3952    NSRect seedRect = [fSeedFilterButton frame];
3953    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
3954   
3955    NSRect pauseRect = [fPauseFilterButton frame];
3956    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
3957   
3958    //size search filter to not overlap buttons
3959    NSRect searchFrame = [fSearchFilterField frame];
3960    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
3961    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
3962   
3963    //make sure it is not too long
3964    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
3965    {
3966        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
3967        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
3968    }
3969    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
3970    {
3971        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
3972        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
3973       
3974        //resize the buttons so they don't overlay
3975        NSInteger difference = (NSMaxX(pauseRect) + 5.0) - searchFrame.origin.x - 1; //subtract 1, since 0 will be counted
3976       
3977        //decrease downloading by 8, seeding by 1, paused by 1, active by 1, repeat
3978        NSInteger download = (difference / 11 * 8) + MIN(difference % 11 + 1, 8); //8 for every 11
3979        NSInteger seed = (difference / 11) + (difference % 11 >= 8 ? 1 : 0);
3980        NSInteger paused = (difference / 11) + (difference % 11 >= 9 ? 1 : 0);
3981        NSInteger active = (difference / 11) + (difference % 11 >= 10 ? 1 : 0);
3982       
3983        activeRect.size.width -= active;
3984       
3985        downloadRect.origin.x -= active;
3986        downloadRect.size.width -= download;
3987       
3988        seedRect.origin.x -= active + download;
3989        seedRect.size.width -= seed;
3990       
3991        pauseRect.origin.x -= active + download + seed;
3992        pauseRect.size.width -= paused;
3993    }
3994    else;
3995   
3996    [fActiveFilterButton setFrame: activeRect];
3997    [fDownloadFilterButton setFrame: downloadRect];
3998    [fSeedFilterButton setFrame: seedRect];
3999    [fPauseFilterButton setFrame: pauseRect];
4000   
4001    [fSearchFilterField setFrame: searchFrame];
4002}
4003
4004- (void) applicationWillUnhide: (NSNotification *) notification
4005{
4006    [self updateUI];
4007}
4008
4009- (NSArray *) quickLookURLs
4010{
4011    NSArray * selectedTorrents = [fTableView selectedTorrents];
4012    NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
4013   
4014    for (Torrent * torrent in selectedTorrents)
4015        if ([self canQuickLookTorrent: torrent])
4016            [urlArray addObject: [NSURL fileURLWithPath: [torrent dataLocation]]];
4017   
4018    return urlArray;
4019}
4020
4021- (BOOL) canQuickLook
4022{
4023    for (Torrent * torrent in [fTableView selectedTorrents])
4024        if ([self canQuickLookTorrent: torrent])
4025            return YES;
4026   
4027    return NO;
4028}
4029
4030- (BOOL) canQuickLookTorrent: (Torrent *) torrent
4031{
4032    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent dataLocation]])
4033        return NO;
4034   
4035    return [torrent isFolder] || [torrent isComplete];
4036}
4037
4038- (NSRect) quickLookFrameWithURL: (NSURL *) url
4039{
4040    if ([fWindow isVisible])
4041    {
4042        NSString * fullPath = [url path];
4043        NSRange visibleRows = [fTableView rowsInRect: [fTableView bounds]];
4044       
4045        for (NSInteger row = 0; row < NSMaxRange(visibleRows); row++)
4046        {
4047            id item = [fTableView itemAtRow: row];
4048            if ([item isKindOfClass: [Torrent class]] && [[(Torrent *)item dataLocation] isEqualToString: fullPath])
4049            {
4050                NSRect frame = [fTableView iconRectForRow: row];
4051                frame.origin = [fTableView convertPoint: frame.origin toView: nil];
4052                frame.origin = [fWindow convertBaseToScreen: frame.origin];
4053                frame.origin.y -= frame.size.height;
4054                return frame;
4055            }
4056        }
4057    }
4058   
4059    return NSZeroRect;
4060}
4061
4062- (void) toggleQuickLook: (id) sender
4063{
4064    [[QuickLookController quickLook] toggleQuickLook];
4065}
4066
4067- (void) linkHomepage: (id) sender
4068{
4069    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4070}
4071
4072- (void) linkForums: (id) sender
4073{
4074    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4075}
4076
4077- (void) linkTrac: (id) sender
4078{
4079    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4080}
4081
4082- (void) linkDonate: (id) sender
4083{
4084    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4085}
4086
4087- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4088{
4089    fUpdateInProgress = YES;
4090}
4091
4092- (NSDictionary *) registrationDictionaryForGrowl
4093{
4094    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4095                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4096    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4097                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4098}
4099
4100- (void) growlNotificationWasClicked: (id) clickContext
4101{
4102    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4103        return;
4104   
4105    NSString * type = [clickContext objectForKey: @"Type"], * location;
4106    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4107            && (location = [clickContext objectForKey: @"Location"]))
4108        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4109}
4110
4111- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4112{
4113    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4114   
4115    //get the torrent
4116    Torrent * torrent = nil;
4117    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4118    {
4119        for (torrent in fTorrents)
4120            if (torrentStruct == [torrent torrentStruct])
4121            {
4122                [torrent retain];
4123                break;
4124            }
4125       
4126        if (!torrent)
4127        {
4128            [pool release];
4129           
4130            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4131            return;
4132        }
4133    }
4134   
4135    switch (type)
4136    {
4137        case TR_RPC_TORRENT_ADDED:
4138            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4139                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4140            break;
4141       
4142        case TR_RPC_TORRENT_STARTED:
4143        case TR_RPC_TORRENT_STOPPED:
4144            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4145            break;
4146       
4147        case TR_RPC_TORRENT_REMOVING:
4148            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4149            break;
4150       
4151        case TR_RPC_TORRENT_CHANGED:
4152            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4153            break;
4154       
4155        case TR_RPC_SESSION_CHANGED:
4156            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4157            break;
4158       
4159        default:
4160            NSLog(@"Unknown RPC command received!");
4161            [torrent release];
4162    }
4163   
4164    [pool release];
4165}
4166
4167- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4168{
4169    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4170    [torrentStructPtr release];
4171   
4172    NSString * location = nil;
4173    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4174        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4175   
4176    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4177   
4178    [torrent update];
4179    [fTorrents addObject: torrent];
4180    [torrent release];
4181   
4182    [self updateTorrentsInQueue];
4183}
4184
4185- (void) rpcRemoveTorrent: (Torrent *) torrent
4186{
4187    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO deleteTorrent: NO];
4188    [torrent release];
4189}
4190
4191- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4192{
4193    [torrent update];
4194    [torrent release];
4195   
4196    [self updateUI];
4197    [self applyFilter: nil];
4198    [self updateTorrentHistory];
4199}
4200
4201- (void) rpcChangedTorrent: (Torrent *) torrent
4202{
4203    [torrent update];
4204   
4205    if ([[fTableView selectedTorrents] containsObject: torrent])
4206    {
4207        [fInfoController updateInfoStats]; //this will reload the file table
4208        [fInfoController updateOptions];
4209    }
4210   
4211    [torrent release];
4212}
4213
4214@end
Note: See TracBrowser for help on using the repository browser.