source: trunk/macosx/Controller.m @ 5156

Last change on this file since 5156 was 5156, checked in by livings124, 14 years ago

clicking on the group speed rates will toggle with ratio

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