source: trunk/macosx/Controller.m @ 5195

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

get mac build compiling again

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