source: trunk/macosx/Controller.m @ 5163

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

make the group "ying-yang" full sized; hide dl speed columns when showing ratio

  • Property svn:keywords set to Date Rev Author Id
File size: 149.2 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 5163 2008-02-28 16:40:14Z 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 [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2501        else if ([ident isEqualToString: @"UL Image"])
2502            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2503                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2504        else
2505        {
2506            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2507            {
2508                uint64_t uploaded = 0, downloaded = 0;
2509                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2510                Torrent * torrent;
2511                while ((torrent = [enumerator nextObject]))
2512                {
2513                    uploaded += [torrent uploadedTotal];
2514                    downloaded += [torrent downloadedTotal];
2515                }
2516               
2517                return [NSString stringForRatio: tr_getRatio(uploaded, downloaded)];
2518            }
2519            else
2520            {
2521                BOOL upload = [ident isEqualToString: @"UL"];
2522               
2523                float rate = 0.0;
2524                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2525                Torrent * torrent;
2526                while ((torrent = [enumerator nextObject]))
2527                    rate += upload ? [torrent uploadRate] : [torrent downloadRate];
2528               
2529                return [NSString stringForSpeed: rate];
2530            }
2531        }
2532    }
2533    else
2534        return [item hashString];
2535}
2536
2537- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2538{
2539    //only allow reordering of rows if sorting by order
2540    if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2541    {
2542        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2543       
2544        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2545        NSEnumerator * enumerator = [items objectEnumerator];
2546        Torrent * torrent;
2547        while ((torrent = [enumerator nextObject]))
2548            [indexSet addIndex: [fTableView rowForItem: torrent]];
2549       
2550        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2551        return YES;
2552    }
2553    return NO;
2554}
2555
2556- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2557    proposedChildIndex: (NSInteger) index
2558{
2559    NSPasteboard * pasteboard = [info draggingPasteboard];
2560    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2561    {
2562        if (item)
2563            index = [fTableView rowForItem: item] + 1;
2564       
2565        [fTableView setDropItem: nil dropChildIndex: index];
2566        return NSDragOperationGeneric;
2567    }
2568   
2569    return NSDragOperationNone;
2570}
2571
2572- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2573    childIndex: (NSInteger) newRow
2574{
2575    NSPasteboard * pasteboard = [info draggingPasteboard];
2576    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2577    {
2578        //remember selected rows
2579        NSArray * selectedValues = [fTableView selectedValues];
2580   
2581        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
2582                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2583       
2584        //determine where to move them
2585        int i, originalRow = newRow;
2586        for (i = [indexes firstIndex]; i < originalRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2587            newRow--;
2588       
2589        //reinsert into array
2590        int insertIndex = newRow > 0 ? [[fDisplayedTorrents objectAtIndex: newRow-1] orderValue] + 1 : 0;
2591       
2592        //get all torrents to reorder
2593        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
2594                                                @"orderValue" ascending: YES] autorelease];
2595       
2596        NSMutableArray * sortedTorrents = [[fTorrents sortedArrayUsingDescriptors:
2597                                            [NSArray arrayWithObject: orderDescriptor]] mutableCopy];
2598       
2599        //remove objects to reinsert
2600        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
2601        [sortedTorrents removeObjectsInArray: movingTorrents];
2602       
2603        //insert objects at new location
2604        for (i = 0; i < [movingTorrents count]; i++)
2605            [sortedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2606       
2607        [movingTorrents release];
2608       
2609        //redo order values
2610        i = 0;
2611        for (i = 0; i < [sortedTorrents count]; i++)
2612            [[sortedTorrents objectAtIndex: i] setOrderValue: i];
2613       
2614        [sortedTorrents release];
2615       
2616        [self applyFilter: nil];
2617       
2618        //set selected rows
2619        [fTableView selectValues: selectedValues];
2620    }
2621   
2622    return YES;
2623}
2624
2625- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2626{
2627    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
2628}
2629
2630- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2631{
2632    NSPasteboard * pasteboard = [info draggingPasteboard];
2633    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2634    {
2635        //check if any torrent files can be added
2636        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2637        NSEnumerator * enumerator = [files objectEnumerator];
2638        NSString * file;
2639        BOOL torrent = NO;
2640        tr_ctor * ctor;
2641        while ((file = [enumerator nextObject]))
2642        {
2643            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2644            {
2645                ctor = tr_ctorNew(fLib);
2646                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2647                switch (tr_torrentParse(fLib, ctor, NULL))
2648                {
2649                    case TR_OK:
2650                        if (!fOverlayWindow)
2651                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2652                        [fOverlayWindow setTorrents: files];
2653                       
2654                        return NSDragOperationCopy;
2655                   
2656                    case TR_EDUPLICATE:
2657                        torrent = YES;
2658                }
2659                tr_ctorFree(ctor);
2660            }
2661        }
2662       
2663        //create a torrent file if a single file
2664        if (!torrent && [files count] == 1)
2665        {
2666            if (!fOverlayWindow)
2667                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2668            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2669           
2670            return NSDragOperationCopy;
2671        }
2672    }
2673    else if ([[pasteboard types] containsObject: NSURLPboardType])
2674    {
2675        if (!fOverlayWindow)
2676            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2677        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2678       
2679        return NSDragOperationCopy;
2680    }
2681    else;
2682   
2683    return NSDragOperationNone;
2684}
2685
2686- (void) draggingExited: (id <NSDraggingInfo>) info
2687{
2688    if (fOverlayWindow)
2689        [fOverlayWindow fadeOut];
2690}
2691
2692- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2693{
2694    if (fOverlayWindow)
2695        [fOverlayWindow fadeOut];
2696   
2697    NSPasteboard * pasteboard = [info draggingPasteboard];
2698    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2699    {
2700        BOOL torrent = NO, accept = YES;
2701       
2702        //create an array of files that can be opened
2703        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2704        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2705        NSEnumerator * enumerator = [files objectEnumerator];
2706        NSString * file;
2707        tr_ctor * ctor;
2708        while ((file = [enumerator nextObject]))
2709        {
2710            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2711            {
2712                ctor = tr_ctorNew(fLib);
2713                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2714                switch (tr_torrentParse(fLib, ctor, NULL))
2715                {
2716                    case TR_OK:
2717                        [filesToOpen addObject: file];
2718                        torrent = YES;
2719                        break;
2720                       
2721                    case TR_EDUPLICATE:
2722                        torrent = YES;
2723                }
2724                tr_ctorFree(ctor);
2725            }
2726        }
2727       
2728        if ([filesToOpen count] > 0)
2729            [self application: NSApp openFiles: filesToOpen];
2730        else
2731        {
2732            if (!torrent && [files count] == 1)
2733                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2734            else
2735                accept = NO;
2736        }
2737        [filesToOpen release];
2738       
2739        return accept;
2740    }
2741    else if ([[pasteboard types] containsObject: NSURLPboardType])
2742    {
2743        NSURL * url;
2744        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2745        {
2746            [self openURL: url];
2747            return YES;
2748        }
2749    }
2750    else;
2751   
2752    return NO;
2753}
2754
2755- (void) toggleSmallView: (id) sender
2756{
2757    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2758    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2759   
2760    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2761   
2762    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2763   
2764    //window min height
2765    NSSize contentMinSize = [fWindow contentMinSize],
2766            contentSize = [[fWindow contentView] frame].size;
2767    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2768                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2769    [fWindow setContentMinSize: contentMinSize];
2770   
2771    //resize for larger min height if not set to auto size
2772    if (![fDefaults boolForKey: @"AutoSize"])
2773    {
2774        if (!makeSmall && contentSize.height < contentMinSize.height)
2775        {
2776            NSRect frame = [fWindow frame];
2777            float heightChange = contentMinSize.height - contentSize.height;
2778            frame.size.height += heightChange;
2779            frame.origin.y -= heightChange;
2780           
2781            [fWindow setFrame: frame display: YES];
2782        }
2783    }
2784    else
2785        [self setWindowSizeToFit];
2786}
2787
2788- (void) togglePiecesBar: (id) sender
2789{
2790    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2791    [fTableView togglePiecesBar];
2792}
2793
2794- (void) toggleAvailabilityBar: (id) sender
2795{
2796    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2797    [fTableView display];
2798}
2799
2800- (void) toggleStatusBar: (id) sender
2801{
2802    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2803    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2804}
2805
2806- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2807{
2808    NSScrollView * scrollView = [fTableView enclosingScrollView];
2809   
2810    //convert pixels to points
2811    NSRect windowFrame = [fWindow frame];
2812    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2813    windowSize.height += height;
2814   
2815    if (check)
2816    {
2817        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2818       
2819        if (windowSize.height < minSize.height)
2820            windowSize.height = minSize.height;
2821        else
2822        {
2823            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2824            if ([fStatusBar isHidden])
2825                maxSize.height -= [fStatusBar frame].size.height;
2826            if ([fFilterBar isHidden])
2827                maxSize.height -= [fFilterBar frame].size.height;
2828            if (windowSize.height > maxSize.height)
2829                windowSize.height = maxSize.height;
2830        }
2831    }
2832
2833    //convert points to pixels
2834    windowSize = [scrollView convertSize: windowSize toView: nil];
2835
2836    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2837    windowFrame.size.height = windowSize.height;
2838    return windowFrame;
2839}
2840
2841- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2842{
2843    if (show != [fStatusBar isHidden])
2844        return;
2845
2846    if (show)
2847        [fStatusBar setHidden: NO];
2848
2849    NSRect frame;
2850    float heightChange = [fStatusBar frame].size.height;
2851    if (!show)
2852        heightChange *= -1;
2853   
2854    //allow bar to show even if not enough room
2855    if (show && ![fDefaults boolForKey: @"AutoSize"])
2856    {
2857        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2858        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2859        if (change < 0.0)
2860        {
2861            frame = [fWindow frame];
2862            frame.size.height += change;
2863            frame.origin.y -= change;
2864            [fWindow setFrame: frame display: NO animate: NO];
2865        }
2866    }
2867
2868    [self updateUI];
2869   
2870    NSScrollView * scrollView = [fTableView enclosingScrollView];
2871   
2872    //set views to not autoresize
2873    unsigned int statsMask = [fStatusBar autoresizingMask];
2874    unsigned int filterMask = [fFilterBar autoresizingMask];
2875    unsigned int scrollMask = [scrollView autoresizingMask];
2876    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2877    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2878    [scrollView setAutoresizingMask: NSViewNotSizable];
2879   
2880    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2881    [fWindow setFrame: frame display: YES animate: animate];
2882   
2883    //re-enable autoresize
2884    [fStatusBar setAutoresizingMask: statsMask];
2885    [fFilterBar setAutoresizingMask: filterMask];
2886    [scrollView setAutoresizingMask: scrollMask];
2887   
2888    //change min size
2889    NSSize minSize = [fWindow contentMinSize];
2890    minSize.height += heightChange;
2891    [fWindow setContentMinSize: minSize];
2892   
2893    if (!show)
2894        [fStatusBar setHidden: YES];
2895}
2896
2897- (void) toggleFilterBar: (id) sender
2898{
2899    //disable filtering when hiding
2900    if (![fFilterBar isHidden])
2901    {
2902        [fSearchFilterField setStringValue: @""];
2903        [self setFilter: fNoFilterButton];
2904        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
2905    }
2906
2907    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2908    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2909}
2910
2911- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2912{
2913    if (show != [fFilterBar isHidden])
2914        return;
2915
2916    if (show)
2917        [fFilterBar setHidden: NO];
2918
2919    NSRect frame;
2920    float heightChange = [fFilterBar frame].size.height;
2921    if (!show)
2922        heightChange *= -1;
2923   
2924    //allow bar to show even if not enough room
2925    if (show && ![fDefaults boolForKey: @"AutoSize"])
2926    {
2927        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2928        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2929        if (change < 0.0)
2930        {
2931            frame = [fWindow frame];
2932            frame.size.height += change;
2933            frame.origin.y -= change;
2934            [fWindow setFrame: frame display: NO animate: NO];
2935        }
2936    }
2937   
2938    NSScrollView * scrollView = [fTableView enclosingScrollView];
2939
2940    //set views to not autoresize
2941    unsigned int filterMask = [fFilterBar autoresizingMask];
2942    unsigned int scrollMask = [scrollView autoresizingMask];
2943    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2944    [scrollView setAutoresizingMask: NSViewNotSizable];
2945   
2946    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2947    [fWindow setFrame: frame display: YES animate: animate];
2948   
2949    //re-enable autoresize
2950    [fFilterBar setAutoresizingMask: filterMask];
2951    [scrollView setAutoresizingMask: scrollMask];
2952   
2953    //change min size
2954    NSSize minSize = [fWindow contentMinSize];
2955    minSize.height += heightChange;
2956    [fWindow setContentMinSize: minSize];
2957   
2958    if (!show)
2959    {
2960        [fFilterBar setHidden: YES];
2961        [fWindow makeFirstResponder: fTableView];
2962    }
2963}
2964
2965- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
2966{
2967    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
2968   
2969    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
2970    [button setBezelStyle: NSTexturedRoundedBezelStyle];
2971    [button setStringValue: @""];
2972   
2973    [item setView: button];
2974    [button release];
2975   
2976    NSSize buttonSize = NSMakeSize(36.0, 25.0);
2977    [item setMinSize: buttonSize];
2978    [item setMaxSize: buttonSize];
2979   
2980    return [item autorelease];
2981}
2982
2983- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2984{
2985    if ([ident isEqualToString: TOOLBAR_CREATE])
2986    {
2987        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2988       
2989        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
2990        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
2991        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
2992        [item setImage: [NSImage imageNamed: @"Create.png"]];
2993        [item setTarget: self];
2994        [item setAction: @selector(createFile:)];
2995        [item setAutovalidates: NO];
2996       
2997        return item;
2998    }
2999    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3000    {
3001        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3002       
3003        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3004        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3005        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3006        [item setImage: [NSImage imageNamed: @"Open.png"]];
3007        [item setTarget: self];
3008        [item setAction: @selector(openShowSheet:)];
3009        [item setAutovalidates: NO];
3010       
3011        return item;
3012    }
3013    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3014    {
3015        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3016       
3017        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3018        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3019        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3020        [item setImage: [NSImage imageNamed: @"OpenWeb.png"]];
3021        [item setTarget: self];
3022        [item setAction: @selector(openURLShowSheet:)];
3023        [item setAutovalidates: NO];
3024       
3025        return item;
3026    }
3027    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3028    {
3029        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3030       
3031        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3032        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3033        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3034        [item setImage: [NSImage imageNamed: @"Remove.png"]];
3035        [item setTarget: self];
3036        [item setAction: @selector(removeNoDelete:)];
3037       
3038        return item;
3039    }
3040    else if ([ident isEqualToString: TOOLBAR_INFO])
3041    {
3042        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3043       
3044        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3045        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3046        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3047        [item setImage: [NSImage imageNamed: @"Info.png"]];
3048        [item setTarget: self];
3049        [item setAction: @selector(showInfo:)];
3050       
3051        return item;
3052    }
3053    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3054    {
3055        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3056       
3057        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3058        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3059        [groupItem setView: segmentedControl];
3060        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3061       
3062        [segmentedControl setSegmentCount: 2];
3063        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3064       
3065        NSSize groupSize = NSMakeSize(72.0, 25.0);
3066        [groupItem setMinSize: groupSize];
3067        [groupItem setMaxSize: groupSize];
3068       
3069        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3070        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3071        [groupItem setTarget: self];
3072        [groupItem setAction: @selector(allToolbarClicked:)];
3073       
3074        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3075       
3076        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3077        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
3078        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3079                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3080       
3081        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3082        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
3083        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3084                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3085       
3086        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3087                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3088       
3089        [segmentedControl release];
3090        return [groupItem autorelease];
3091    }
3092    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3093    {
3094        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3095       
3096        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3097        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3098        [groupItem setView: segmentedControl];
3099        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3100       
3101        [segmentedControl setSegmentCount: 2];
3102        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3103       
3104        NSSize groupSize = NSMakeSize(72.0, 25.0);
3105        [groupItem setMinSize: groupSize];
3106        [groupItem setMaxSize: groupSize];
3107       
3108        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3109        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3110        [groupItem setTarget: self];
3111        [groupItem setAction: @selector(selectedToolbarClicked:)];
3112       
3113        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3114       
3115        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3116        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
3117        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3118                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3119       
3120        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3121        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
3122        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3123                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3124       
3125        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3126                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3127       
3128        [segmentedControl release];
3129        return [groupItem autorelease];
3130    }
3131    else if ([ident isEqualToString: TOOLBAR_FILTER])
3132    {
3133        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3134       
3135        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3136        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3137        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3138        [item setImage: [NSImage imageNamed: @"Filter.png"]];
3139        [item setTarget: self];
3140        [item setAction: @selector(toggleFilterBar:)];
3141       
3142        return item;
3143    }
3144    else
3145        return nil;
3146}
3147
3148- (void) allToolbarClicked: (id) sender
3149{
3150    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3151                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3152    switch (tagValue)
3153    {
3154        case TOOLBAR_PAUSE_TAG:
3155            [self stopAllTorrents: sender];
3156            break;
3157        case TOOLBAR_RESUME_TAG:
3158            [self resumeAllTorrents: sender];
3159            break;
3160    }
3161}
3162
3163- (void) selectedToolbarClicked: (id) sender
3164{
3165    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3166                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3167    switch (tagValue)
3168    {
3169        case TOOLBAR_PAUSE_TAG:
3170            [self stopSelectedTorrents: sender];
3171            break;
3172        case TOOLBAR_RESUME_TAG:
3173            [self resumeSelectedTorrents: sender];
3174            break;
3175    }
3176}
3177
3178- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3179{
3180    return [NSArray arrayWithObjects:
3181            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB,
3182            TOOLBAR_REMOVE, TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3183            TOOLBAR_FILTER, TOOLBAR_INFO,
3184            NSToolbarSeparatorItemIdentifier,
3185            NSToolbarSpaceItemIdentifier,
3186            NSToolbarFlexibleSpaceItemIdentifier,
3187            NSToolbarCustomizeToolbarItemIdentifier, nil];
3188}
3189
3190- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3191{
3192    return [NSArray arrayWithObjects:
3193            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE,
3194            NSToolbarSeparatorItemIdentifier,
3195            TOOLBAR_PAUSE_RESUME_ALL,
3196            NSToolbarFlexibleSpaceItemIdentifier,
3197            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3198}
3199
3200- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3201{
3202    NSString * ident = [toolbarItem itemIdentifier];
3203   
3204    //enable remove item
3205    if ([ident isEqualToString: TOOLBAR_REMOVE])
3206        return [fTableView numberOfSelectedRows] > 0;
3207
3208    //enable pause all item
3209    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3210    {
3211        Torrent * torrent;
3212        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3213        while ((torrent = [enumerator nextObject]))
3214            if ([torrent isActive] || [torrent waitingToStart])
3215                return YES;
3216        return NO;
3217    }
3218
3219    //enable resume all item
3220    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3221    {
3222        Torrent * torrent;
3223        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3224        while ((torrent = [enumerator nextObject]))
3225            if (![torrent isActive] && ![torrent waitingToStart])
3226                return YES;
3227        return NO;
3228    }
3229
3230    //enable pause item
3231    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3232    {
3233        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3234        Torrent * torrent;
3235        while ((torrent = [enumerator nextObject]))
3236            if ([torrent isActive] || [torrent waitingToStart])
3237                return YES;
3238        return NO;
3239    }
3240   
3241    //enable resume item
3242    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3243    {
3244        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3245        Torrent * torrent;
3246        while ((torrent = [enumerator nextObject]))
3247            if (![torrent isActive] && ![torrent waitingToStart])
3248                return YES;
3249        return NO;
3250    }
3251   
3252    //set info image
3253    if ([ident isEqualToString: TOOLBAR_INFO])
3254    {
3255        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue.png"]
3256                                                                    : [NSImage imageNamed: @"Info.png"]];
3257        return YES;
3258    }
3259   
3260    //set filter image
3261    if ([ident isEqualToString: TOOLBAR_FILTER])
3262    {
3263        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue.png"] : [NSImage imageNamed: @"Filter.png"]];
3264        return YES;
3265    }
3266
3267    return YES;
3268}
3269
3270- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3271{
3272    SEL action = [menuItem action];
3273   
3274    if (action == @selector(toggleSpeedLimit:))
3275    {
3276        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3277        return YES;
3278    }
3279   
3280    //only enable some items if it is in a context menu or the window is useable
3281    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3282
3283    //enable open items
3284    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3285        return [fWindow attachedSheet] == nil;
3286   
3287    //enable sort options
3288    if (action == @selector(setSort:))
3289    {
3290        NSString * sortType;
3291        switch ([menuItem tag])
3292        {
3293            case SORT_ORDER_TAG:
3294                sortType = SORT_ORDER;
3295                break;
3296            case SORT_DATE_TAG:
3297                sortType = SORT_DATE;
3298                break;
3299            case SORT_NAME_TAG:
3300                sortType = SORT_NAME;
3301                break;
3302            case SORT_PROGRESS_TAG:
3303                sortType = SORT_PROGRESS;
3304                break;
3305            case SORT_STATE_TAG:
3306                sortType = SORT_STATE;
3307                break;
3308            case SORT_TRACKER_TAG:
3309                sortType = SORT_TRACKER;
3310                break;
3311            case SORT_ACTIVITY_TAG:
3312                sortType = SORT_ACTIVITY;
3313                break;
3314            default:
3315                sortType = @"";
3316        }
3317       
3318        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3319        return [fWindow isVisible];
3320    }
3321   
3322    //enable sort options
3323    if (action == @selector(setStatusLabel:))
3324    {
3325        NSString * statusLabel;
3326        switch ([menuItem tag])
3327        {
3328            case STATUS_RATIO_TOTAL_TAG:
3329                statusLabel = STATUS_RATIO_TOTAL;
3330                break;
3331            case STATUS_RATIO_SESSION_TAG:
3332                statusLabel = STATUS_RATIO_SESSION;
3333                break;
3334            case STATUS_TRANSFER_TOTAL_TAG:
3335                statusLabel = STATUS_TRANSFER_TOTAL;
3336                break;
3337            case STATUS_TRANSFER_SESSION_TAG:
3338                statusLabel = STATUS_TRANSFER_SESSION;
3339                break;
3340            default:
3341                statusLabel = @"";;
3342        }
3343       
3344        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3345        return YES;
3346    }
3347   
3348    if (action == @selector(setGroup:))
3349    {
3350        BOOL checked = NO;
3351       
3352        int index = [menuItem tag];
3353        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3354        Torrent * torrent;
3355        while ((torrent = [enumerator nextObject]))
3356            if (index == [torrent groupValue])
3357            {
3358                checked = YES;
3359                break;
3360            }
3361       
3362        [menuItem setState: checked ? NSOnState : NSOffState];
3363        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3364    }
3365   
3366    if (action == @selector(setGroupFilter:))
3367    {
3368        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3369        return YES;
3370    }
3371   
3372    if (action == @selector(toggleSmallView:))
3373    {
3374        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3375        return [fWindow isVisible];
3376    }
3377   
3378    if (action == @selector(togglePiecesBar:))
3379    {
3380        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3381        return [fWindow isVisible];
3382    }
3383   
3384    if (action == @selector(toggleAvailabilityBar:))
3385    {
3386        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3387        return [fWindow isVisible];
3388    }
3389   
3390    if (action == @selector(setLimitGlobalEnabled:))
3391    {
3392        BOOL upload = [menuItem menu] == fUploadMenu;
3393        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3394        if (limit)
3395            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3396                                    "Action menu -> upload/download limit"),
3397                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3398       
3399        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3400        return YES;
3401    }
3402   
3403    if (action == @selector(setRatioGlobalEnabled:))
3404    {
3405        BOOL check = menuItem == fCheckRatioItem;
3406        if (check)
3407            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3408                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3409       
3410        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3411        return YES;
3412    }
3413
3414    //enable show info
3415    if (action == @selector(showInfo:))
3416    {
3417        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3418                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3419        [menuItem setTitle: title];
3420
3421        return YES;
3422    }
3423   
3424    //enable prev/next inspector tab
3425    if (action == @selector(setInfoTab:))
3426        return [[fInfoController window] isVisible];
3427   
3428    //enable toggle status bar
3429    if (action == @selector(toggleStatusBar:))
3430    {
3431        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3432                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3433        [menuItem setTitle: title];
3434
3435        return [fWindow isVisible];
3436    }
3437   
3438    //enable toggle filter bar
3439    if (action == @selector(toggleFilterBar:))
3440    {
3441        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3442                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3443        [menuItem setTitle: title];
3444
3445        return [fWindow isVisible];
3446    }
3447   
3448    //enable prev/next filter button
3449    if (action == @selector(switchFilter:))
3450        return [fWindow isVisible] && ![fFilterBar isHidden];
3451
3452    //enable reveal in finder
3453    if (action == @selector(revealFile:))
3454        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3455
3456    //enable remove items
3457    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3458        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3459    {
3460        BOOL warning = NO,
3461            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3462            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3463       
3464        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3465        Torrent * torrent;
3466        while ((torrent = [enumerator nextObject]))
3467        {
3468            if (!warning && [torrent isActive])
3469            {
3470                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3471                if (warning && canDelete)
3472                    break;
3473            }
3474            if (!canDelete && [torrent publicTorrent])
3475            {
3476                canDelete = YES;
3477                if (warning)
3478                    break;
3479            }
3480        }
3481   
3482        //append or remove ellipsis when needed
3483        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3484        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3485        {
3486            if (![title hasSuffix: ellipsis])
3487                [menuItem setTitle: [title stringByAppendingEllipsis]];
3488        }
3489        else
3490        {
3491            if ([title hasSuffix: ellipsis])
3492                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3493        }
3494       
3495        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3496    }
3497
3498    //enable pause all item
3499    if (action == @selector(stopAllTorrents:))
3500    {
3501        Torrent * torrent;
3502        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3503        while ((torrent = [enumerator nextObject]))
3504            if ([torrent isActive] || [torrent waitingToStart])
3505                return YES;
3506        return NO;
3507    }
3508   
3509    //enable resume all item
3510    if (action == @selector(resumeAllTorrents:))
3511    {
3512        Torrent * torrent;
3513        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3514        while ((torrent = [enumerator nextObject]))
3515            if (![torrent isActive] && ![torrent waitingToStart])
3516                return YES;
3517        return NO;
3518    }
3519   
3520    #warning hide queue options if all queues are disabled?
3521   
3522    //enable resume all waiting item
3523    if (action == @selector(resumeWaitingTorrents:))
3524    {
3525        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3526            return NO;
3527   
3528        Torrent * torrent;
3529        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3530        while ((torrent = [enumerator nextObject]))
3531            if (![torrent isActive] && [torrent waitingToStart])
3532                return YES;
3533        return NO;
3534    }
3535   
3536    //enable resume selected waiting item
3537    if (action == @selector(resumeSelectedTorrentsNoWait:))
3538    {
3539        if (!canUseTable)
3540            return NO;
3541       
3542        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3543        Torrent * torrent;
3544        while ((torrent = [enumerator nextObject]))
3545            if (![torrent isActive])
3546                return YES;
3547        return NO;
3548    }
3549
3550    //enable pause item
3551    if (action == @selector(stopSelectedTorrents:))
3552    {
3553        if (!canUseTable)
3554            return NO;
3555   
3556        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3557        Torrent * torrent;
3558        while ((torrent = [enumerator nextObject]))
3559            if ([torrent isActive] || [torrent waitingToStart])
3560                return YES;
3561        return NO;
3562    }
3563   
3564    //enable resume item
3565    if (action == @selector(resumeSelectedTorrents:))
3566    {
3567        if (!canUseTable)
3568            return NO;
3569   
3570        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3571        Torrent * torrent;
3572        while ((torrent = [enumerator nextObject]))
3573            if (![torrent isActive] && ![torrent waitingToStart])
3574                return YES;
3575        return NO;
3576    }
3577   
3578    //enable manual announce item
3579    if (action == @selector(announceSelectedTorrents:))
3580    {
3581        if (!canUseTable)
3582            return NO;
3583       
3584        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3585        Torrent * torrent;
3586        while ((torrent = [enumerator nextObject]))
3587            if ([torrent canManualAnnounce])
3588                return YES;
3589        return NO;
3590    }
3591   
3592    //enable reset cache item
3593    if (action == @selector(verifySelectedTorrents:))
3594        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3595   
3596    //enable move torrent file item
3597    if (action == @selector(moveDataFiles:))
3598        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3599   
3600    //enable copy torrent file item
3601    if (action == @selector(copyTorrentFiles:))
3602        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3603   
3604    //enable reverse sort item
3605    if (action == @selector(setSortReverse:))
3606    {
3607        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3608        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3609    }
3610   
3611    //enable group sort item
3612    if (action == @selector(setSortByGroup:))
3613    {
3614        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3615        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3616    }
3617   
3618    //check proper filter search item
3619    if (action == @selector(setFilterSearchType:))
3620    {
3621        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3622       
3623        BOOL state;
3624        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3625            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3626        else
3627            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3628       
3629        [menuItem setState: state ? NSOnState : NSOffState];
3630        return YES;
3631    }
3632   
3633    return YES;
3634}
3635
3636- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
3637{
3638    NSEnumerator * enumerator;
3639    Torrent * torrent;
3640    BOOL allowSleep;
3641
3642    switch (messageType)
3643    {
3644        case kIOMessageSystemWillSleep:
3645            //close all connections before going to sleep and remember we should resume when we wake up
3646            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3647
3648            //wait for running transfers to stop (5 second timeout)
3649            NSDate * start = [NSDate date];
3650            BOOL timeUp = NO;
3651           
3652            enumerator = [fTorrents objectEnumerator];
3653            while (!timeUp && (torrent = [enumerator nextObject]))
3654                while ([torrent isActive] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
3655                {
3656                    usleep(100000);
3657                    [torrent update];
3658                }
3659
3660            IOAllowPowerChange(fRootPort, (long) messageArgument);
3661            break;
3662
3663        case kIOMessageCanSystemSleep:
3664            allowSleep = YES;
3665            if ([fDefaults boolForKey: @"SleepPrevent"])
3666            {
3667                //prevent idle sleep unless no torrents are active
3668                enumerator = [fTorrents objectEnumerator];
3669                while ((torrent = [enumerator nextObject]))
3670                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3671                    {
3672                        allowSleep = NO;
3673                        break;
3674                    }
3675            }
3676
3677            if (allowSleep)
3678                IOAllowPowerChange(fRootPort, (long) messageArgument);
3679            else
3680                IOCancelPowerChange(fRootPort, (long) messageArgument);
3681            break;
3682
3683        case kIOMessageSystemHasPoweredOn:
3684            //resume sleeping transfers after we wake up
3685            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3686            [self autoSpeedLimitChange: nil];
3687            break;
3688    }
3689}
3690
3691- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3692{
3693    int seeding = 0, downloading = 0;
3694    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3695    Torrent * torrent;
3696    while ((torrent = [enumerator nextObject]))
3697    {
3698        if ([torrent isSeeding])
3699            seeding++;
3700        else if ([torrent isActive])
3701            downloading++;
3702        else;
3703    }
3704   
3705    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3706            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3707   
3708    BOOL hasSeparator = seedingItem || downloadingItem;
3709   
3710    if (seeding > 0)
3711    {
3712        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding",
3713                                                        "Dock item - Seeding"), seeding];
3714        if (!seedingItem)
3715        {
3716            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3717            [seedingItem setTag: DOCK_SEEDING_TAG];
3718            [fDockMenu insertItem: seedingItem atIndex: 0];
3719        }
3720        else
3721            [seedingItem setTitle: title];
3722    }
3723    else
3724    {
3725        if (seedingItem)
3726            [fDockMenu removeItem: seedingItem];
3727    }
3728   
3729    if (downloading > 0)
3730    {
3731        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading",
3732                                                        "Dock item - Downloading"), downloading];
3733        if (!downloadingItem)
3734        {
3735            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3736            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3737            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3738        }
3739        else
3740            [downloadingItem setTitle: title];
3741    }
3742    else
3743    {
3744        if (downloadingItem)
3745            [fDockMenu removeItem: downloadingItem];
3746    }
3747   
3748    if (seeding > 0 || downloading > 0)
3749    {
3750        if (!hasSeparator)
3751            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3752    }
3753    else
3754    {
3755        if (hasSeparator)
3756            [fDockMenu removeItemAtIndex: 0];
3757    }
3758   
3759    return fDockMenu;
3760}
3761
3762- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3763{
3764    //if auto size is enabled, the current frame shouldn't need to change
3765    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3766   
3767    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3768    return frame;
3769}
3770
3771- (void) setWindowSizeToFit
3772{
3773    if ([fDefaults boolForKey: @"AutoSize"])
3774    {
3775        NSScrollView * scrollView = [fTableView enclosingScrollView];
3776       
3777        [scrollView setHasVerticalScroller: NO];
3778        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3779        [scrollView setHasVerticalScroller: YES];
3780    }
3781}
3782
3783- (NSRect) sizedWindowFrame
3784{
3785    int groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3786                    ? [fDisplayedTorrents count] : 0;
3787   
3788    float heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3789                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3790                        - [[fTableView enclosingScrollView] frame].size.height;
3791   
3792    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3793}
3794
3795- (void) updateForExpandCollape
3796{
3797    [self setWindowSizeToFit];
3798    [self setBottomCountTextFiltering: YES];
3799}
3800
3801- (void) showMainWindow: (id) sender
3802{
3803    [fWindow makeKeyAndOrderFront: nil];
3804}
3805
3806- (void) windowDidBecomeMain: (NSNotification *) notification
3807{
3808    [fBadger clearCompleted];
3809    [self updateUI];
3810}
3811
3812- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3813{
3814    //only resize horizontally if autosize is enabled
3815    if ([fDefaults boolForKey: @"AutoSize"])
3816        proposedFrameSize.height = [fWindow frame].size.height;
3817    return proposedFrameSize;
3818}
3819
3820- (void) windowDidResize: (NSNotification *) notification
3821{
3822    if ([fFilterBar isHidden])
3823        return;
3824   
3825    //replace all buttons
3826    [fActiveFilterButton sizeToFit];
3827    [fDownloadFilterButton sizeToFit];
3828    [fSeedFilterButton sizeToFit];
3829    [fPauseFilterButton sizeToFit];
3830   
3831    NSRect activeRect = [fActiveFilterButton frame];
3832   
3833    NSRect downloadRect = [fDownloadFilterButton frame];
3834    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
3835   
3836    NSRect seedRect = [fSeedFilterButton frame];
3837    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
3838   
3839    NSRect pauseRect = [fPauseFilterButton frame];
3840    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
3841   
3842    //size search filter to not overlap buttons
3843    NSRect searchFrame = [fSearchFilterField frame];
3844    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
3845    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
3846   
3847    //make sure it is not too long
3848    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
3849    {
3850        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
3851        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
3852    }
3853    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
3854    {
3855        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
3856        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
3857       
3858        //resize each button until they don't overlap search
3859        int download = 0;
3860        BOOL seeding = NO, paused = NO;
3861        do
3862        {
3863            if (download < 8)
3864            {
3865                download++;
3866                downloadRect.size.width--;
3867               
3868                seedRect.origin.x--;
3869                pauseRect.origin.x--;
3870            }
3871            else if (!seeding)
3872            {
3873                seeding = YES;
3874                seedRect.size.width--;
3875               
3876                pauseRect.origin.x--;
3877            }
3878            else if (!paused)
3879            {
3880                paused = YES;
3881                pauseRect.size.width--;
3882            }
3883            else
3884            {
3885                activeRect.size.width--;
3886               
3887                downloadRect.origin.x--;
3888                seedRect.origin.x--;
3889                pauseRect.origin.x--;
3890               
3891                //reset
3892                download = 0;
3893                seeding = NO;
3894                paused = NO;
3895            }
3896        }
3897        while (NSMaxX(pauseRect) + 5.0 > searchFrame.origin.x);
3898    }
3899    else;
3900   
3901    [fActiveFilterButton setFrame: activeRect];
3902    [fDownloadFilterButton setFrame: downloadRect];
3903    [fSeedFilterButton setFrame: seedRect];
3904    [fPauseFilterButton setFrame: pauseRect];
3905   
3906    [fSearchFilterField setFrame: searchFrame];
3907}
3908
3909- (void) applicationWillUnhide: (NSNotification *) notification
3910{
3911    [self updateUI];
3912}
3913
3914- (void) linkHomepage: (id) sender
3915{
3916    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
3917}
3918
3919- (void) linkForums: (id) sender
3920{
3921    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
3922}
3923
3924- (void) linkDonate: (id) sender
3925{
3926    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
3927}
3928
3929- (void) prepareForUpdate: (NSNotification *) notification
3930{
3931    fUpdateInProgress = YES;
3932}
3933
3934- (NSDictionary *) registrationDictionaryForGrowl
3935{
3936    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
3937                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
3938    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
3939                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
3940}
3941
3942- (void) growlNotificationWasClicked: (id) clickContext
3943{
3944    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
3945        return;
3946   
3947    NSString * type = [clickContext objectForKey: @"Type"], * location;
3948    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
3949            && (location = [clickContext objectForKey: @"Location"]))
3950        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
3951}
3952
3953- (void) ipcQuit
3954{
3955    fRemoteQuit = YES;
3956    [NSApp terminate: self];
3957}
3958
3959- (NSArray *) ipcGetTorrentsByID: (NSArray *) idlist
3960{
3961    if (!idlist)
3962        return fTorrents;
3963   
3964    NSMutableArray * torrents = [NSMutableArray array];
3965   
3966    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * idEnum;
3967    int torId;
3968    Torrent * torrent;
3969    NSNumber * tempId;
3970    while ((torrent = [torrentEnum nextObject]))
3971    {
3972        torId = [torrent torrentID];
3973       
3974        idEnum = [idlist objectEnumerator];
3975        while ((tempId = [idEnum nextObject]))
3976        {
3977            if ([tempId intValue] == torId)
3978            {
3979                [torrents addObject: torrent];
3980                break;
3981            }
3982        }
3983    }
3984
3985    return torrents;
3986}
3987
3988- (NSArray *) ipcGetTorrentsByHash: (NSArray *) hashlist
3989{
3990    if (!hashlist)
3991        return fTorrents;
3992   
3993    NSMutableArray * torrents = [NSMutableArray array];
3994   
3995    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * hashEnum;
3996    NSString * torHash, * tempHash;
3997    Torrent * torrent;
3998    while ((torrent = [torrentEnum nextObject]))
3999    {
4000        torHash = [torrent hashString];
4001       
4002        hashEnum = [hashlist objectEnumerator];
4003        while ((tempHash = [hashEnum nextObject]))
4004        {
4005            if ([torHash caseInsensitiveCompare: tempHash] == NSOrderedSame)
4006            {
4007                [torrents addObject: torrent];
4008                break;
4009            }
4010        }
4011    }
4012   
4013    return torrents;
4014}
4015
4016- (BOOL) ipcAddTorrents: (NSArray *) torrents
4017{
4018    int oldCount = [fTorrents count];
4019   
4020    [self openFiles: torrents addType: ADD_NORMAL forcePath: nil];
4021   
4022    return [fTorrents count] > oldCount;
4023}
4024
4025- (BOOL) ipcAddTorrentFile: (NSString *) path directory: (NSString *) directory
4026{
4027    int oldCount = [fTorrents count];
4028   
4029    [self openFiles: [NSArray arrayWithObject: path] addType: ADD_NORMAL forcePath: directory];
4030   
4031    return [fTorrents count] > oldCount;
4032}
4033
4034- (BOOL) ipcAddTorrentFileAutostart: (NSString *) path directory: (NSString *) directory autostart: (BOOL) autostart
4035{
4036    NSArray * torrents = nil;
4037    if (autostart)
4038        torrents = [fTorrents copy];
4039    BOOL success = [self ipcAddTorrentFile: path directory: directory];
4040   
4041    if (success && autostart)
4042    {
4043        NSEnumerator * enumerator = [torrents reverseObjectEnumerator];
4044        Torrent * torrent;
4045        while ((torrent = [enumerator nextObject]))
4046            if (![torrents containsObject: torrent])
4047                break;
4048       
4049        if (torrent)
4050            [torrent startTransfer];
4051        else
4052            success = NO;
4053    }
4054   
4055    [torrents release];
4056    return success;
4057}
4058
4059- (BOOL) ipcAddTorrentData: (NSData *) data directory: (NSString *) directory
4060{
4061    return [self ipcAddTorrentDataAutostart: data directory: directory autostart: [fDefaults boolForKey: @"AutoStartDownload"]];
4062}
4063
4064- (BOOL) ipcAddTorrentDataAutostart: (NSData *) data directory: (NSString *) directory autostart: (BOOL) autostart
4065{
4066    Torrent * torrent;
4067    if ((torrent = [[Torrent alloc] initWithData: data location: directory lib: fLib]))
4068    {
4069        [torrent update];
4070        [fTorrents addObject: torrent];
4071       
4072        if (autostart)
4073            [torrent startTransfer];
4074       
4075        [torrent release];
4076       
4077        [self updateTorrentsInQueue];
4078        return YES;
4079    }
4080    else
4081        return NO;
4082}
4083
4084- (BOOL) ipcStartTorrents: (NSArray *) torrents
4085{
4086    if (!torrents)
4087        [self resumeAllTorrents: self];
4088    else
4089        [self resumeTorrents: torrents];
4090
4091    return YES;
4092}
4093
4094- (BOOL) ipcStopTorrents: (NSArray *) torrents
4095{
4096    if (!torrents)
4097        [self stopAllTorrents: self];
4098    else
4099        [self stopTorrents: torrents];
4100
4101    return YES;
4102}
4103
4104- (BOOL) ipcVerifyTorrents: (NSArray *) torrents
4105{
4106    if (!torrents)
4107        return NO;
4108
4109    [self verifyTorrents: torrents];
4110    return YES;
4111}
4112
4113- (BOOL) ipcRemoveTorrents: (NSArray *) torrents
4114{
4115    if (!torrents)
4116        torrents = [NSArray arrayWithArray: fTorrents];
4117    [torrents retain];
4118
4119    [self confirmRemoveTorrents: torrents deleteData: NO deleteTorrent: NO];
4120
4121    return YES;
4122}
4123
4124@end
Note: See TracBrowser for help on using the repository browser.