source: trunk/macosx/Controller.m @ 5309

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

#799 treat "waiting to check..." as paused

  • Property svn:keywords set to Date Rev Author Id
File size: 149.5 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 5309 2008-03-19 18:03:02Z 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 = [NSString stringWithFormat: @"%@: %@", NSLocalizedString(@"Ratio", "status bar -> status label"),
1425                                    [NSString stringForRatio: stats.ratio]];
1426                }
1427                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1428                {
1429                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1430                   
1431                    tr_session_stats stats;
1432                    if (total)
1433                        tr_getCumulativeSessionStats(fLib, &stats);
1434                    else
1435                        tr_getSessionStats(fLib, &stats);
1436                   
1437                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1438                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1439                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1440                }
1441               
1442                if ([NSApp isOnLeopardOrBetter])
1443                {
1444                    [fStatusButton setTitle: statusString];
1445                    [fStatusButton sizeToFit];
1446                   
1447                    //width ends up being too long
1448                    NSRect statusFrame = [fStatusButton frame];
1449                    statusFrame.size.width -= 25.0;
1450                    [fStatusButton setFrame: statusFrame];
1451                }
1452                else
1453                    [fStatusTigerField setStringValue: statusString];
1454            }
1455        }
1456
1457        //update non-constant parts of info window
1458        if ([[fInfoController window] isVisible])
1459            [fInfoController updateInfoStats];
1460    }
1461   
1462    //badge dock
1463    [fBadger updateBadge];
1464}
1465
1466- (void) setBottomCountTextFiltering: (BOOL) filtering
1467{
1468    NSString * totalTorrentsString;
1469    int totalCount = [fTorrents count];
1470    if (totalCount != 1)
1471        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1472    else
1473        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1474   
1475    if (filtering)
1476    {
1477        int count = 0, rows = [fTableView numberOfRows];
1478        if (rows > 0 && ![[fTableView itemAtRow: 0] isKindOfClass: [Torrent class]])
1479        {
1480            int i;
1481            for (i = 1; i < rows; i++)
1482                if ([[fTableView itemAtRow: i] isKindOfClass: [Torrent class]])
1483                    count++;
1484        }
1485        else
1486            count = rows;
1487       
1488        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d of %@", "Status bar transfer count"),
1489                                count, totalTorrentsString];
1490    }
1491   
1492    [fTotalTorrentsField setStringValue: totalTorrentsString];
1493}
1494
1495- (void) updateTorrentsInQueue
1496{
1497    BOOL download = [fDefaults boolForKey: @"Queue"],
1498        seed = [fDefaults boolForKey: @"QueueSeed"];
1499   
1500    int desiredDownloadActive = [self numToStartFromQueue: YES],
1501        desiredSeedActive = [self numToStartFromQueue: NO];
1502   
1503    //sort torrents by order value
1504    NSArray * sortedTorrents;
1505    if ([fTorrents count] > 1 && (desiredDownloadActive > 0 || desiredSeedActive > 0))
1506    {
1507        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: YES] autorelease];
1508        sortedTorrents = [fTorrents sortedArrayUsingDescriptors: [NSArray arrayWithObject: orderDescriptor]];
1509    }
1510    else
1511        sortedTorrents = fTorrents;
1512   
1513    Torrent * torrent;
1514    NSEnumerator * enumerator = [sortedTorrents objectEnumerator];
1515    while ((torrent = [enumerator nextObject]))
1516    {
1517        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1518        {
1519            if (![torrent allDownloaded])
1520            {
1521                if (!download || desiredDownloadActive > 0)
1522                {
1523                    [torrent startTransfer];
1524                    if ([torrent isActive])
1525                        desiredDownloadActive--;
1526                    [torrent update];
1527                }
1528            }
1529            else
1530            {
1531                if (!seed || desiredSeedActive > 0)
1532                {
1533                    [torrent startTransfer];
1534                    if ([torrent isActive])
1535                        desiredSeedActive--;
1536                    [torrent update];
1537                }
1538            }
1539        }
1540    }
1541   
1542    [self updateUI];
1543    [self applyFilter: nil];
1544    [self updateTorrentHistory];
1545}
1546
1547- (int) numToStartFromQueue: (BOOL) downloadQueue
1548{
1549    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1550        return 0;
1551   
1552    int desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1553       
1554    Torrent * torrent;
1555    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1556    while ((torrent = [enumerator nextObject]))
1557    {
1558        if ([torrent isChecking])
1559        {
1560            desired--;
1561            if (desired <= 0)
1562                return 0;
1563        }
1564        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1565        {
1566            if ([torrent allDownloaded] != downloadQueue)
1567            {
1568                desired--;
1569                if (desired <= 0)
1570                    return 0;
1571            }
1572        }
1573        else;
1574    }
1575   
1576    return desired;
1577}
1578
1579- (void) torrentFinishedDownloading: (NSNotification *) notification
1580{
1581    Torrent * torrent = [notification object];
1582    if ([torrent isActive])
1583    {
1584        if ([fDefaults boolForKey: @"PlayDownloadSound"])
1585        {
1586            NSSound * sound;
1587            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1588                [sound play];
1589        }
1590       
1591        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1592                                        [torrent dataLocation] , @"Location", nil];
1593        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1594                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1595                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1596       
1597        if (![fWindow isMainWindow])
1598            [fBadger incrementCompleted];
1599       
1600        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1601        {
1602            [torrent stopTransfer];
1603            [torrent setWaitToStart: YES];
1604        }
1605    }
1606   
1607    [self updateTorrentsInQueue];
1608}
1609
1610- (void) torrentRestartedDownloading: (NSNotification *) notification
1611{
1612    Torrent * torrent = [notification object];
1613    if ([torrent isActive])
1614    {
1615        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1616        {
1617            [torrent stopTransfer];
1618            [torrent setWaitToStart: YES];
1619        }
1620    }
1621   
1622    [self updateTorrentsInQueue];
1623}
1624
1625- (void) updateTorrentHistory
1626{
1627    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1628
1629    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1630    Torrent * torrent;
1631    while ((torrent = [enumerator nextObject]))
1632        [history addObject: [torrent history]];
1633
1634    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER] atomically: YES];
1635}
1636
1637- (void) setSort: (id) sender
1638{
1639    NSString * sortType;
1640    switch ([sender tag])
1641    {
1642        case SORT_ORDER_TAG:
1643            sortType = SORT_ORDER;
1644            [fDefaults setBool: NO forKey: @"SortReverse"];
1645           
1646            [fDefaults setBool: NO forKey: @"SortByGroup"];
1647            [fTableView removeAllCollapsedGroups];
1648           
1649            [self applyFilter: nil]; //ensure groups are removed
1650            break;
1651        case SORT_DATE_TAG:
1652            sortType = SORT_DATE;
1653            break;
1654        case SORT_NAME_TAG:
1655            sortType = SORT_NAME;
1656            break;
1657        case SORT_PROGRESS_TAG:
1658            sortType = SORT_PROGRESS;
1659            break;
1660        case SORT_STATE_TAG:
1661            sortType = SORT_STATE;
1662            break;
1663        case SORT_TRACKER_TAG:
1664            sortType = SORT_TRACKER;
1665            break;
1666        case SORT_ACTIVITY_TAG:
1667            sortType = SORT_ACTIVITY;
1668            break;
1669        default:
1670            return;
1671    }
1672   
1673    [fDefaults setObject: sortType forKey: @"Sort"];
1674    [self sortTorrents];
1675}
1676
1677- (void) setSortByGroup: (id) sender
1678{
1679    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1680    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1681   
1682    //expand all groups
1683    if (sortByGroup)
1684        [fTableView removeAllCollapsedGroups];
1685   
1686    [self applyFilter: nil];
1687}
1688
1689- (void) setSortReverse: (id) sender
1690{
1691    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1692    [self sortTorrents];
1693}
1694
1695- (void) sortTorrents
1696{
1697    NSArray * selectedValues = [fTableView selectedValues];
1698   
1699    [self sortTorrentsIgnoreSelected]; //actually sort
1700   
1701    [fTableView selectValues: selectedValues];
1702}
1703
1704- (void) sortTorrentsIgnoreSelected
1705{
1706    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1707    BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1708   
1709    NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: asc] autorelease];
1710   
1711    NSArray * descriptors;
1712    if ([sortType isEqualToString: SORT_ORDER])
1713        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1714    else if ([sortType isEqualToString: SORT_NAME])
1715    {
1716        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1717                                                selector: @selector(caseInsensitiveCompare:)] autorelease];
1718       
1719        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1720    }
1721    else if ([sortType isEqualToString: SORT_STATE])
1722    {
1723        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1724                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1725                        * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1726                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1727                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1728       
1729        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1730                                                            nameDescriptor, orderDescriptor, nil];
1731    }
1732    else if ([sortType isEqualToString: SORT_PROGRESS])
1733    {
1734        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1735                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1736                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1737                        * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1738                                                        ascending: asc] autorelease],
1739                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1740       
1741        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1742                                                            nameDescriptor, orderDescriptor, nil];
1743    }
1744    else if ([sortType isEqualToString: SORT_TRACKER])
1745    {
1746        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1747                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1748                        * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddress" ascending: asc
1749                                                selector: @selector(caseInsensitiveCompare:)] autorelease];
1750       
1751        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, orderDescriptor, nil];
1752    }
1753    else if ([sortType isEqualToString: SORT_ACTIVITY])
1754    {
1755        NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1756        NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1757                                                    autorelease];
1758       
1759        descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, orderDescriptor, nil];
1760    }
1761    else
1762    {
1763        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1764   
1765        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1766    }
1767   
1768    //on Tiger add the group sort descriptor to the front
1769    if (![NSApp isOnLeopardOrBetter] && [fDefaults boolForKey: @"SortByGroup"])
1770    {
1771        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
1772       
1773        NSMutableArray * temp = [[NSMutableArray alloc] initWithCapacity: [descriptors count]+1];
1774        [temp addObject: groupDescriptor];
1775        [temp addObjectsFromArray: descriptors];
1776       
1777        [descriptors release];
1778        descriptors = temp;
1779    }
1780   
1781    //actually sort
1782    if ([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
1783    {
1784        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1785        NSDictionary * dict;
1786        while ((dict = [enumerator nextObject]))
1787            [[dict objectForKey: @"Torrents"] sortUsingDescriptors: descriptors];
1788    }
1789    else
1790        [fDisplayedTorrents sortUsingDescriptors: descriptors];
1791   
1792    [descriptors release];
1793   
1794    [fTableView reloadData];
1795}
1796
1797- (void) applyFilter: (id) sender
1798{
1799    //get all the torrents in the table
1800    NSMutableArray * previousTorrents;
1801    if ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1802    {
1803        previousTorrents = [NSMutableArray array];
1804       
1805        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1806        NSDictionary * dict;
1807        while ((dict = [enumerator nextObject]))
1808            [previousTorrents addObjectsFromArray: [dict objectForKey: @"Torrents"]];
1809    }
1810    else
1811        previousTorrents = fDisplayedTorrents;
1812   
1813    NSArray * selectedValues = [fTableView selectedValues];
1814   
1815    int active = 0, downloading = 0, seeding = 0, paused = 0;
1816    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1817    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1818    if ([filterType isEqualToString: FILTER_ACTIVE])
1819        filterActive = YES;
1820    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1821        filterDownload = YES;
1822    else if ([filterType isEqualToString: FILTER_SEED])
1823        filterSeed = YES;
1824    else if ([filterType isEqualToString: FILTER_PAUSE])
1825        filterPause = YES;
1826    else
1827        filterStatus = NO;
1828   
1829    int groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
1830    BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
1831   
1832    NSString * searchString = [fSearchFilterField stringValue];
1833    BOOL filterText = [searchString length] > 0,
1834        filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
1835   
1836    NSMutableIndexSet * indexes = [NSMutableIndexSet indexSet];
1837   
1838    //get count of each type
1839    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1840    Torrent * torrent;
1841    int i = -1;
1842    while ((torrent = [enumerator nextObject]))
1843    {
1844        i++;
1845       
1846        //check status
1847        if ([torrent isActive] && ![torrent isCheckingWaiting])
1848        {
1849            if ([torrent isSeeding])
1850            {
1851                seeding++;
1852                BOOL isActive = ![torrent isStalled];
1853                if (isActive)
1854                    active++;
1855               
1856                if (filterStatus && (!(filterActive && isActive) && !filterSeed))
1857                    continue;
1858            }
1859            else
1860            {
1861                downloading++;
1862                BOOL isActive = ![torrent isStalled];
1863                if (isActive)
1864                    active++;
1865               
1866                if (filterStatus && (!(filterActive && isActive) && !filterDownload))
1867                    continue;
1868            }
1869        }
1870        else
1871        {
1872            paused++;
1873            if (filterStatus && !filterPause)
1874                continue;
1875        }
1876       
1877        //checkGroup
1878        if (filterGroup)
1879            if ([torrent groupValue] != groupFilterValue)
1880                continue;
1881       
1882        //check text field
1883        if (filterText)
1884        {
1885            if (filterTracker)
1886            {
1887                BOOL removeTextField = YES;
1888                NSEnumerator * trackerEnumerator = [[torrent allTrackers] objectEnumerator], * subTrackerEnumerator;
1889                NSArray * subTrackers;
1890                NSString * tracker;
1891                while (removeTextField && (subTrackers = [trackerEnumerator nextObject]))
1892                {
1893                    subTrackerEnumerator = [subTrackers objectEnumerator];
1894                    while ((tracker = [subTrackerEnumerator nextObject]))
1895                        if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1896                        {
1897                            removeTextField = NO;
1898                            break;
1899                        }
1900                }
1901               
1902                if (removeTextField)
1903                    continue;
1904            }
1905            else
1906            {
1907                if ([[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound)
1908                    continue;
1909            }
1910        }
1911       
1912        [indexes addIndex: i];
1913    }
1914   
1915    NSArray * allTorrents = [fTorrents objectsAtIndexes: indexes];
1916   
1917    //set button tooltips
1918    [fNoFilterButton setCount: [fTorrents count]];
1919    [fActiveFilterButton setCount: active];
1920    [fDownloadFilterButton setCount: downloading];
1921    [fSeedFilterButton setCount: seeding];
1922    [fPauseFilterButton setCount: paused];
1923   
1924    //clear display cache for not-shown torrents
1925    [previousTorrents removeObjectsInArray: allTorrents];
1926    enumerator = [previousTorrents objectEnumerator];
1927    while ((torrent = [enumerator nextObject]))
1928        [torrent setPreviousAmountFinished: NULL];
1929   
1930    //place torrents into groups
1931    BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter];
1932    if (groupRows)
1933    {
1934        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
1935        allTorrents = [allTorrents sortedArrayUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
1936       
1937        NSMutableArray * groups = [NSMutableArray array], * groupTorrents;
1938        int oldGroupValue = -2;
1939        for (i = 0; i < [allTorrents count]; i++)
1940        {
1941            Torrent * torrent = [allTorrents objectAtIndex: i];
1942            int groupValue = [torrent groupValue];
1943            if (groupValue != oldGroupValue)
1944            {
1945                groupTorrents = [NSMutableArray array];
1946                NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt: groupValue], @"Group",
1947                                        groupTorrents, @"Torrents", nil];
1948                [groups addObject: dict];
1949               
1950                oldGroupValue = groupValue;
1951            }
1952           
1953            [groupTorrents addObject: torrent];
1954        }
1955       
1956        [fDisplayedTorrents setArray: groups];
1957    }
1958    else
1959        [fDisplayedTorrents setArray: allTorrents];
1960   
1961    //actually sort
1962    [self sortTorrentsIgnoreSelected];
1963    [fTableView selectValues: selectedValues];
1964   
1965    //reset expanded/collapsed rows
1966    if (groupRows)
1967    {
1968        enumerator = [fDisplayedTorrents objectEnumerator];
1969        NSDictionary * dict;
1970        while ((dict = [enumerator nextObject]))
1971        {
1972            if ([fTableView isGroupCollapsed: [[dict objectForKey: @"Group"] intValue]])
1973                [fTableView collapseItem: dict];
1974            else
1975                [fTableView expandItem: dict];
1976        }
1977    }
1978   
1979    [self setBottomCountTextFiltering: groupRows || filterStatus || filterGroup || filterText];
1980
1981    [self setWindowSizeToFit];
1982}
1983
1984//resets filter and sorts torrents
1985- (void) setFilter: (id) sender
1986{
1987    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
1988   
1989    NSButton * prevFilterButton;
1990    if ([oldFilterType isEqualToString: FILTER_PAUSE])
1991        prevFilterButton = fPauseFilterButton;
1992    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
1993        prevFilterButton = fActiveFilterButton;
1994    else if ([oldFilterType isEqualToString: FILTER_SEED])
1995        prevFilterButton = fSeedFilterButton;
1996    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
1997        prevFilterButton = fDownloadFilterButton;
1998    else
1999        prevFilterButton = fNoFilterButton;
2000   
2001    if (sender != prevFilterButton)
2002    {
2003        [prevFilterButton setState: NSOffState];
2004        [sender setState: NSOnState];
2005
2006        NSString * filterType;
2007        if (sender == fActiveFilterButton)
2008            filterType = FILTER_ACTIVE;
2009        else if (sender == fDownloadFilterButton)
2010            filterType = FILTER_DOWNLOAD;
2011        else if (sender == fPauseFilterButton)
2012            filterType = FILTER_PAUSE;
2013        else if (sender == fSeedFilterButton)
2014            filterType = FILTER_SEED;
2015        else
2016            filterType = FILTER_NONE;
2017
2018        [fDefaults setObject: filterType forKey: @"Filter"];
2019    }
2020    else
2021        [sender setState: NSOnState];
2022
2023    [self applyFilter: nil];
2024}
2025
2026- (void) setFilterSearchType: (id) sender
2027{
2028    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2029   
2030    int prevTag, currentTag = [sender tag];
2031    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2032        prevTag = FILTER_TYPE_TAG_TRACKER;
2033    else
2034        prevTag = FILTER_TYPE_TAG_NAME;
2035   
2036    if (currentTag != prevTag)
2037    {
2038        NSString * filterType;
2039        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2040            filterType = FILTER_TYPE_TRACKER;
2041        else
2042            filterType = FILTER_TYPE_NAME;
2043       
2044        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2045       
2046        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2047    }
2048   
2049    [self applyFilter: nil];
2050}
2051
2052- (void) switchFilter: (id) sender
2053{
2054    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2055   
2056    NSButton * button;
2057    if ([filterType isEqualToString: FILTER_NONE])
2058        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2059    else if ([filterType isEqualToString: FILTER_ACTIVE])
2060        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2061    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2062        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2063    else if ([filterType isEqualToString: FILTER_SEED])
2064        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2065    else if ([filterType isEqualToString: FILTER_PAUSE])
2066        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2067    else
2068        button = fNoFilterButton;
2069   
2070    [self setFilter: button];
2071}
2072
2073- (void) setStatusLabel: (id) sender
2074{
2075    NSString * statusLabel;
2076    switch ([sender tag])
2077    {
2078        case STATUS_RATIO_TOTAL_TAG:
2079            statusLabel = STATUS_RATIO_TOTAL;
2080            break;
2081        case STATUS_RATIO_SESSION_TAG:
2082            statusLabel = STATUS_RATIO_SESSION;
2083            break;
2084        case STATUS_TRANSFER_TOTAL_TAG:
2085            statusLabel = STATUS_TRANSFER_TOTAL;
2086            break;
2087        case STATUS_TRANSFER_SESSION_TAG:
2088            statusLabel = STATUS_TRANSFER_SESSION;
2089            break;
2090        default:
2091            return;
2092    }
2093   
2094    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2095    [self updateUI];
2096}
2097
2098- (void) showGroups: (id) sender
2099{
2100    [[GroupsWindowController groups] showWindow: self];
2101}
2102
2103- (void) menuNeedsUpdate: (NSMenu *) menu
2104{
2105    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2106    {
2107        int i;
2108        for (i = [menu numberOfItems]-1 - 2; i >= 0; i--)
2109            [menu removeItemAtIndex: i];
2110       
2111        NSMenu * groupMenu = [[GroupsWindowController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2112        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2113                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: NO];
2114    }
2115    else if (menu == fGroupFilterMenu)
2116    {
2117        int i;
2118        for (i = [menu numberOfItems]-1; i >= 3; i--)
2119            [menu removeItemAtIndex: i];
2120       
2121        NSMenu * groupMenu = [[GroupsWindowController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:)
2122                                isSmall: YES];
2123        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2124                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: YES];
2125    }
2126    else if (menu == fUploadMenu || menu == fDownloadMenu)
2127    {
2128        if ([menu numberOfItems] > 3)
2129            return;
2130       
2131        const int speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, -1 };
2132       
2133        NSMenuItem * item;
2134        int i;
2135        for (i = 0; speedLimitActionValue[i] != -1; i++)
2136        {
2137            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2138                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2139                    keyEquivalent: @""];
2140            [item setTarget: self];
2141            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2142            [menu addItem: item];
2143            [item release];
2144        }
2145    }
2146    else if (menu == fRatioStopMenu)
2147    {
2148        if ([menu numberOfItems] > 3)
2149            return;
2150       
2151        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2152       
2153        NSMenuItem * item;
2154        int i;
2155        for (i = 0; ratioLimitActionValue[i] != -1; i++)
2156        {
2157            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2158                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2159            [item setTarget: self];
2160            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2161            [menu addItem: item];
2162            [item release];
2163        }
2164    }
2165    else;
2166}
2167
2168- (void) setGroup: (id) sender
2169{
2170    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
2171    Torrent * torrent;
2172    while ((torrent = [enumerator nextObject]))
2173    {
2174        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2175       
2176        [torrent setGroupValue: [sender tag]];
2177    }
2178   
2179    [self applyFilter: nil];
2180    [self updateUI];
2181    [self updateTorrentHistory];
2182}
2183
2184- (void) setGroupFilter: (id) sender
2185{
2186    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2187    [self updateGroupsFilterButton];
2188    [self applyFilter: nil];
2189}
2190
2191- (void) updateGroupsFilterButton
2192{
2193    int index = [fDefaults integerForKey: @"FilterGroup"];
2194   
2195    NSImage * icon = nil;
2196    NSString * toolTip;
2197    switch (index)
2198    {
2199        case GROUP_FILTER_ALL_TAG:
2200            icon = [NSImage imageNamed: @"PinTemplate.png"];
2201            toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2202            break;
2203        case -1:
2204            if ([NSApp isOnLeopardOrBetter])
2205                icon = [NSImage imageNamed: NSImageNameStopProgressTemplate];
2206            toolTip = NSLocalizedString(@"Group: No Label", "Groups -> Button");
2207            break;
2208        default:
2209            icon = [[GroupsWindowController groups] imageForIndex: index isSmall: YES];
2210            toolTip = [NSLocalizedString(@"Group: ", "Groups -> Button") stringByAppendingString:
2211                        [[GroupsWindowController groups] nameForIndex: index]];
2212    }
2213   
2214    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2215    [fGroupsButton setToolTip: toolTip];
2216}
2217
2218- (void) updateGroupsFilters: (NSNotification *) notification
2219{
2220    [self updateGroupsFilterButton];
2221    [self applyFilter: nil];
2222}
2223
2224- (void) toggleSpeedLimit: (id) sender
2225{
2226    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2227    [fPrefsController applySpeedSettings: nil];
2228}
2229
2230- (void) autoSpeedLimitChange: (NSNotification *) notification
2231{
2232    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2233        return;
2234 
2235    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2236                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
2237        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2238                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
2239        * nowDate = [NSCalendarDate calendarDate];
2240   
2241    //check if should be on if within range
2242    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
2243        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
2244        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
2245   
2246    BOOL shouldBeOn = NO;
2247    if (onTime < offTime)
2248        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2249    else if (onTime > offTime)
2250        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2251    else;
2252   
2253    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2254        [self toggleSpeedLimit: nil];
2255}
2256
2257- (void) autoSpeedLimit
2258{
2259    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2260        return;
2261   
2262    //only toggle if within first few seconds of minutes
2263    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
2264    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
2265        return;
2266   
2267    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2268                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
2269   
2270    BOOL toggle;
2271    if ([fDefaults boolForKey: @"SpeedLimit"])
2272        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
2273    else
2274    {
2275        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2276                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
2277        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
2278                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
2279    }
2280   
2281    if (toggle)
2282    {
2283        [self toggleSpeedLimit: nil];
2284       
2285        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2286                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2287                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2288            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2289            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2290    }
2291}
2292
2293- (void) setLimitGlobalEnabled: (id) sender
2294{
2295    BOOL upload = [sender menu] == fUploadMenu;
2296    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2297   
2298    [fPrefsController applySpeedSettings: nil];
2299}
2300
2301- (void) setQuickLimitGlobal: (id) sender
2302{
2303    BOOL upload = [sender menu] == fUploadMenu;
2304    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2305    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2306   
2307    [fPrefsController updateLimitFields];
2308    [fPrefsController applySpeedSettings: nil];
2309}
2310
2311- (void) setRatioGlobalEnabled: (id) sender
2312{
2313    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2314}
2315
2316- (void) setQuickRatioGlobal: (id) sender
2317{
2318    [fDefaults setBool: YES forKey: @"RatioCheck"];
2319    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2320   
2321    [fPrefsController updateRatioStopField];
2322}
2323
2324- (void) torrentStoppedForRatio: (NSNotification *) notification
2325{
2326    Torrent * torrent = [notification object];
2327   
2328    [self updateTorrentsInQueue];
2329    [fInfoController updateInfoStats];
2330    [fInfoController updateOptions];
2331   
2332    if ([fDefaults boolForKey: @"PlaySeedingSound"])
2333    {
2334        NSSound * sound;
2335        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
2336            [sound play];
2337    }
2338   
2339    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
2340                                    [torrent dataLocation], @"Location", nil];
2341    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
2342                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2343                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2344}
2345
2346-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2347{
2348    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2349    {
2350        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2351            return;
2352       
2353        if (fAutoImportTimer)
2354        {
2355            if ([fAutoImportTimer isValid])
2356                [fAutoImportTimer invalidate];
2357            [fAutoImportTimer release];
2358            fAutoImportTimer = nil;
2359        }
2360       
2361        //check again in 10 seconds in case torrent file wasn't complete
2362        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2363            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2364       
2365        [self checkAutoImportDirectory];
2366    }
2367}
2368
2369- (void) changeAutoImport
2370{
2371    if (fAutoImportTimer)
2372    {
2373        if ([fAutoImportTimer isValid])
2374            [fAutoImportTimer invalidate];
2375        [fAutoImportTimer release];
2376        fAutoImportTimer = nil;
2377    }
2378   
2379    if (fAutoImportedNames)
2380    {
2381        [fAutoImportedNames release];
2382        fAutoImportedNames = nil;
2383    }
2384   
2385    [self checkAutoImportDirectory];
2386}
2387
2388- (void) checkAutoImportDirectory
2389{
2390    NSString * path;
2391    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2392        return;
2393   
2394    path = [path stringByExpandingTildeInPath];
2395   
2396    NSArray * importedNames;
2397    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2398        return;
2399   
2400    //only check files that have not been checked yet
2401    NSMutableArray * newNames = [importedNames mutableCopy];
2402   
2403    if (fAutoImportedNames)
2404        [newNames removeObjectsInArray: fAutoImportedNames];
2405    else
2406        fAutoImportedNames = [[NSMutableArray alloc] init];
2407    [fAutoImportedNames setArray: importedNames];
2408   
2409    NSString * file;
2410    int i;
2411    for (i = [newNames count] - 1; i >= 0; i--)
2412    {
2413        file = [newNames objectAtIndex: i];
2414        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2415            [newNames removeObjectAtIndex: i];
2416        else
2417            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2418    }
2419   
2420    NSEnumerator * enumerator = [newNames objectEnumerator];
2421    tr_ctor * ctor;
2422    while ((file = [enumerator nextObject]))
2423    {
2424        ctor = tr_ctorNew(fLib);
2425        tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2426       
2427        switch (tr_torrentParse(fLib, ctor, NULL))
2428        {
2429            case TR_OK:
2430                [self openFiles: [NSArray arrayWithObject: file] addType: ADD_NORMAL forcePath: nil];
2431               
2432                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2433                    description: [file lastPathComponent] notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2434                    clickContext: nil];
2435                break;
2436           
2437            case TR_EINVALID:
2438                [fAutoImportedNames removeObject: [file lastPathComponent]];
2439        }
2440       
2441        tr_ctorFree(ctor);
2442    }
2443   
2444    [newNames release];
2445}
2446
2447- (void) beginCreateFile: (NSNotification *) notification
2448{
2449    if (![fDefaults boolForKey: @"AutoImport"])
2450        return;
2451   
2452    NSString * location = [notification object],
2453            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2454   
2455    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2456                                    isEqualToString: [path stringByExpandingTildeInPath]])
2457        [fAutoImportedNames addObject: [location lastPathComponent]];
2458}
2459
2460- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2461{
2462    if (item)
2463        return [[item objectForKey: @"Torrents"] count];
2464    else
2465        return [fDisplayedTorrents count];
2466}
2467
2468- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2469{
2470    if (item)
2471        return [[item objectForKey: @"Torrents"] objectAtIndex: index];
2472    else
2473        return [fDisplayedTorrents objectAtIndex: index];
2474}
2475
2476- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2477{
2478    return ![item isKindOfClass: [Torrent class]];
2479}
2480
2481- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2482{
2483    if (![item isKindOfClass: [Torrent class]])
2484    {
2485        NSString * ident = [tableColumn identifier];
2486        if ([ident isEqualToString: @"Group"])
2487        {
2488            int group = [[item objectForKey: @"Group"] intValue];
2489            return group != -1 ? [[GroupsWindowController groups] nameForIndex: group]
2490                                : NSLocalizedString(@"No Group", "Group table row");
2491        }
2492        else if ([ident isEqualToString: @"Color"])
2493        {
2494            int group = [[item objectForKey: @"Group"] intValue];
2495            return group != -1 ? [[GroupsWindowController groups] imageForIndex: group isSmall: YES]
2496                                : [NSImage imageNamed: NSImageNameStopProgressTemplate];
2497        }
2498        else if ([ident isEqualToString: @"DL Image"])
2499            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2500        else if ([ident isEqualToString: @"UL Image"])
2501            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2502                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2503        else
2504        {
2505            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2506            {
2507                uint64_t uploaded = 0, downloaded = 0;
2508                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2509                Torrent * torrent;
2510                while ((torrent = [enumerator nextObject]))
2511                {
2512                    uploaded += [torrent uploadedTotal];
2513                    downloaded += [torrent downloadedTotal];
2514                }
2515               
2516                return [NSString stringForRatio: tr_getRatio(uploaded, downloaded)];
2517            }
2518            else
2519            {
2520                BOOL upload = [ident isEqualToString: @"UL"];
2521               
2522                float rate = 0.0;
2523                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2524                Torrent * torrent;
2525                while ((torrent = [enumerator nextObject]))
2526                    rate += upload ? [torrent uploadRate] : [torrent downloadRate];
2527               
2528                return [NSString stringForSpeed: rate];
2529            }
2530        }
2531    }
2532    else
2533        return [item hashString];
2534}
2535
2536- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2537{
2538    //only allow reordering of rows if sorting by order
2539    if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2540    {
2541        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2542       
2543        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2544        NSEnumerator * enumerator = [items objectEnumerator];
2545        Torrent * torrent;
2546        while ((torrent = [enumerator nextObject]))
2547            [indexSet addIndex: [fTableView rowForItem: torrent]];
2548       
2549        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2550        return YES;
2551    }
2552    return NO;
2553}
2554
2555- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2556    proposedChildIndex: (NSInteger) index
2557{
2558    NSPasteboard * pasteboard = [info draggingPasteboard];
2559    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2560    {
2561        if (item)
2562            index = [fTableView rowForItem: item] + 1;
2563       
2564        [fTableView setDropItem: nil dropChildIndex: index];
2565        return NSDragOperationGeneric;
2566    }
2567   
2568    return NSDragOperationNone;
2569}
2570
2571- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2572    childIndex: (NSInteger) newRow
2573{
2574    NSPasteboard * pasteboard = [info draggingPasteboard];
2575    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2576    {
2577        //remember selected rows
2578        NSArray * selectedValues = [fTableView selectedValues];
2579   
2580        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
2581                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2582       
2583        //determine where to move them
2584        int i, originalRow = newRow;
2585        for (i = [indexes firstIndex]; i < originalRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2586            newRow--;
2587       
2588        //reinsert into array
2589        int insertIndex = newRow > 0 ? [[fDisplayedTorrents objectAtIndex: newRow-1] orderValue] + 1 : 0;
2590       
2591        //get all torrents to reorder
2592        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
2593                                                @"orderValue" ascending: YES] autorelease];
2594       
2595        NSMutableArray * sortedTorrents = [[fTorrents sortedArrayUsingDescriptors:
2596                                            [NSArray arrayWithObject: orderDescriptor]] mutableCopy];
2597       
2598        //remove objects to reinsert
2599        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
2600        [sortedTorrents removeObjectsInArray: movingTorrents];
2601       
2602        //insert objects at new location
2603        for (i = 0; i < [movingTorrents count]; i++)
2604            [sortedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2605       
2606        [movingTorrents release];
2607       
2608        //redo order values
2609        i = 0;
2610        for (i = 0; i < [sortedTorrents count]; i++)
2611            [[sortedTorrents objectAtIndex: i] setOrderValue: i];
2612       
2613        [sortedTorrents release];
2614       
2615        [self applyFilter: nil];
2616       
2617        //set selected rows
2618        [fTableView selectValues: selectedValues];
2619    }
2620   
2621    return YES;
2622}
2623
2624- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2625{
2626    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
2627}
2628
2629- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2630{
2631    NSPasteboard * pasteboard = [info draggingPasteboard];
2632    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2633    {
2634        //check if any torrent files can be added
2635        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2636        NSEnumerator * enumerator = [files objectEnumerator];
2637        NSString * file;
2638        BOOL torrent = NO;
2639        tr_ctor * ctor;
2640        while ((file = [enumerator nextObject]))
2641        {
2642            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2643            {
2644                ctor = tr_ctorNew(fLib);
2645                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2646                switch (tr_torrentParse(fLib, ctor, NULL))
2647                {
2648                    case TR_OK:
2649                        if (!fOverlayWindow)
2650                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2651                        [fOverlayWindow setTorrents: files];
2652                       
2653                        return NSDragOperationCopy;
2654                   
2655                    case TR_EDUPLICATE:
2656                        torrent = YES;
2657                }
2658                tr_ctorFree(ctor);
2659            }
2660        }
2661       
2662        //create a torrent file if a single file
2663        if (!torrent && [files count] == 1)
2664        {
2665            if (!fOverlayWindow)
2666                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2667            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2668           
2669            return NSDragOperationCopy;
2670        }
2671    }
2672    else if ([[pasteboard types] containsObject: NSURLPboardType])
2673    {
2674        if (!fOverlayWindow)
2675            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2676        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2677       
2678        return NSDragOperationCopy;
2679    }
2680    else;
2681   
2682    return NSDragOperationNone;
2683}
2684
2685- (void) draggingExited: (id <NSDraggingInfo>) info
2686{
2687    if (fOverlayWindow)
2688        [fOverlayWindow fadeOut];
2689}
2690
2691- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2692{
2693    if (fOverlayWindow)
2694        [fOverlayWindow fadeOut];
2695   
2696    NSPasteboard * pasteboard = [info draggingPasteboard];
2697    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2698    {
2699        BOOL torrent = NO, accept = YES;
2700       
2701        //create an array of files that can be opened
2702        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2703        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2704        NSEnumerator * enumerator = [files objectEnumerator];
2705        NSString * file;
2706        tr_ctor * ctor;
2707        while ((file = [enumerator nextObject]))
2708        {
2709            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2710            {
2711                ctor = tr_ctorNew(fLib);
2712                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2713                switch (tr_torrentParse(fLib, ctor, NULL))
2714                {
2715                    case TR_OK:
2716                        [filesToOpen addObject: file];
2717                        torrent = YES;
2718                        break;
2719                       
2720                    case TR_EDUPLICATE:
2721                        torrent = YES;
2722                }
2723                tr_ctorFree(ctor);
2724            }
2725        }
2726       
2727        if ([filesToOpen count] > 0)
2728            [self application: NSApp openFiles: filesToOpen];
2729        else
2730        {
2731            if (!torrent && [files count] == 1)
2732                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2733            else
2734                accept = NO;
2735        }
2736        [filesToOpen release];
2737       
2738        return accept;
2739    }
2740    else if ([[pasteboard types] containsObject: NSURLPboardType])
2741    {
2742        NSURL * url;
2743        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2744        {
2745            [self openURL: url];
2746            return YES;
2747        }
2748    }
2749    else;
2750   
2751    return NO;
2752}
2753
2754- (void) toggleSmallView: (id) sender
2755{
2756    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2757    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2758   
2759    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2760   
2761    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2762   
2763    //window min height
2764    NSSize contentMinSize = [fWindow contentMinSize],
2765            contentSize = [[fWindow contentView] frame].size;
2766    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2767                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2768    [fWindow setContentMinSize: contentMinSize];
2769   
2770    //resize for larger min height if not set to auto size
2771    if (![fDefaults boolForKey: @"AutoSize"])
2772    {
2773        if (!makeSmall && contentSize.height < contentMinSize.height)
2774        {
2775            NSRect frame = [fWindow frame];
2776            float heightChange = contentMinSize.height - contentSize.height;
2777            frame.size.height += heightChange;
2778            frame.origin.y -= heightChange;
2779           
2780            [fWindow setFrame: frame display: YES];
2781        }
2782    }
2783    else
2784        [self setWindowSizeToFit];
2785}
2786
2787- (void) togglePiecesBar: (id) sender
2788{
2789    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2790    [fTableView togglePiecesBar];
2791}
2792
2793- (void) toggleAvailabilityBar: (id) sender
2794{
2795    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2796    [fTableView display];
2797}
2798
2799- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2800{
2801    NSScrollView * scrollView = [fTableView enclosingScrollView];
2802   
2803    //convert pixels to points
2804    NSRect windowFrame = [fWindow frame];
2805    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2806    windowSize.height += height;
2807   
2808    if (check)
2809    {
2810        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2811       
2812        if (windowSize.height < minSize.height)
2813            windowSize.height = minSize.height;
2814        else
2815        {
2816            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2817            if ([fStatusBar isHidden])
2818                maxSize.height -= [fStatusBar frame].size.height;
2819            if ([fFilterBar isHidden])
2820                maxSize.height -= [fFilterBar frame].size.height;
2821            if (windowSize.height > maxSize.height)
2822                windowSize.height = maxSize.height;
2823        }
2824    }
2825
2826    //convert points to pixels
2827    windowSize = [scrollView convertSize: windowSize toView: nil];
2828
2829    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2830    windowFrame.size.height = windowSize.height;
2831    return windowFrame;
2832}
2833
2834- (void) toggleStatusBar: (id) sender
2835{
2836    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2837    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2838}
2839
2840//doesn't save shown state
2841- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2842{
2843    if (show != [fStatusBar isHidden])
2844        return;
2845
2846    if (show)
2847        [fStatusBar setHidden: NO];
2848
2849    NSRect frame;
2850    float heightChange = [fStatusBar frame].size.height;
2851    if (!show)
2852        heightChange *= -1;
2853   
2854    //allow bar to show even if not enough room
2855    if (show && ![fDefaults boolForKey: @"AutoSize"])
2856    {
2857        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2858        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2859        if (change < 0.0)
2860        {
2861            frame = [fWindow frame];
2862            frame.size.height += change;
2863            frame.origin.y -= change;
2864            [fWindow setFrame: frame display: NO animate: NO];
2865        }
2866    }
2867
2868    [self updateUI];
2869   
2870    NSScrollView * scrollView = [fTableView enclosingScrollView];
2871   
2872    //set views to not autoresize
2873    unsigned int statsMask = [fStatusBar autoresizingMask];
2874    unsigned int filterMask = [fFilterBar autoresizingMask];
2875    unsigned int scrollMask = [scrollView autoresizingMask];
2876    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2877    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2878    [scrollView setAutoresizingMask: NSViewNotSizable];
2879   
2880    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2881    [fWindow setFrame: frame display: YES animate: animate];
2882   
2883    //re-enable autoresize
2884    [fStatusBar setAutoresizingMask: statsMask];
2885    [fFilterBar setAutoresizingMask: filterMask];
2886    [scrollView setAutoresizingMask: scrollMask];
2887   
2888    //change min size
2889    NSSize minSize = [fWindow contentMinSize];
2890    minSize.height += heightChange;
2891    [fWindow setContentMinSize: minSize];
2892   
2893    if (!show)
2894        [fStatusBar setHidden: YES];
2895}
2896
2897- (void) toggleFilterBar: (id) sender
2898{
2899    //disable filtering when hiding
2900    if (![fFilterBar isHidden])
2901    {
2902        [fSearchFilterField setStringValue: @""];
2903        [self setFilter: fNoFilterButton];
2904        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
2905    }
2906
2907    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2908    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2909}
2910
2911//doesn't save shown state
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- (void) focusFilterField
2967{
2968    [fWindow makeFirstResponder: fSearchFilterField];
2969    if ([fFilterBar isHidden])
2970        [self toggleFilterBar: self];
2971}
2972
2973- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
2974{
2975    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
2976   
2977    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
2978    [button setBezelStyle: NSTexturedRoundedBezelStyle];
2979    [button setStringValue: @""];
2980   
2981    [item setView: button];
2982    [button release];
2983   
2984    NSSize buttonSize = NSMakeSize(36.0, 25.0);
2985    [item setMinSize: buttonSize];
2986    [item setMaxSize: buttonSize];
2987   
2988    return [item autorelease];
2989}
2990
2991- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2992{
2993    if ([ident isEqualToString: TOOLBAR_CREATE])
2994    {
2995        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2996       
2997        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
2998        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
2999        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3000        [item setImage: [NSImage imageNamed: @"Create.png"]];
3001        [item setTarget: self];
3002        [item setAction: @selector(createFile:)];
3003        [item setAutovalidates: NO];
3004       
3005        return item;
3006    }
3007    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3008    {
3009        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3010       
3011        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3012        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3013        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3014        [item setImage: [NSImage imageNamed: @"Open.png"]];
3015        [item setTarget: self];
3016        [item setAction: @selector(openShowSheet:)];
3017        [item setAutovalidates: NO];
3018       
3019        return item;
3020    }
3021    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3022    {
3023        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3024       
3025        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3026        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3027        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3028        [item setImage: [NSImage imageNamed: @"OpenWeb.png"]];
3029        [item setTarget: self];
3030        [item setAction: @selector(openURLShowSheet:)];
3031        [item setAutovalidates: NO];
3032       
3033        return item;
3034    }
3035    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3036    {
3037        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3038       
3039        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3040        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3041        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3042        [item setImage: [NSImage imageNamed: @"Remove.png"]];
3043        [item setTarget: self];
3044        [item setAction: @selector(removeNoDelete:)];
3045       
3046        return item;
3047    }
3048    else if ([ident isEqualToString: TOOLBAR_INFO])
3049    {
3050        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3051       
3052        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3053        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3054        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3055        [item setImage: [NSImage imageNamed: @"Info.png"]];
3056        [item setTarget: self];
3057        [item setAction: @selector(showInfo:)];
3058       
3059        return item;
3060    }
3061    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3062    {
3063        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3064       
3065        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3066        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3067        [groupItem setView: segmentedControl];
3068        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3069       
3070        [segmentedControl setSegmentCount: 2];
3071        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3072       
3073        NSSize groupSize = NSMakeSize(72.0, 25.0);
3074        [groupItem setMinSize: groupSize];
3075        [groupItem setMaxSize: groupSize];
3076       
3077        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3078        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3079        [groupItem setTarget: self];
3080        [groupItem setAction: @selector(allToolbarClicked:)];
3081       
3082        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3083       
3084        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3085        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
3086        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3087                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3088       
3089        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3090        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
3091        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3092                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3093       
3094        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3095                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3096       
3097        [segmentedControl release];
3098        return [groupItem autorelease];
3099    }
3100    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3101    {
3102        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3103       
3104        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3105        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3106        [groupItem setView: segmentedControl];
3107        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3108       
3109        [segmentedControl setSegmentCount: 2];
3110        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3111       
3112        NSSize groupSize = NSMakeSize(72.0, 25.0);
3113        [groupItem setMinSize: groupSize];
3114        [groupItem setMaxSize: groupSize];
3115       
3116        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3117        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3118        [groupItem setTarget: self];
3119        [groupItem setAction: @selector(selectedToolbarClicked:)];
3120       
3121        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3122       
3123        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3124        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
3125        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3126                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3127       
3128        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3129        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
3130        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3131                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3132       
3133        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3134                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3135       
3136        [segmentedControl release];
3137        return [groupItem autorelease];
3138    }
3139    else if ([ident isEqualToString: TOOLBAR_FILTER])
3140    {
3141        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3142       
3143        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3144        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3145        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3146        [item setImage: [NSImage imageNamed: @"Filter.png"]];
3147        [item setTarget: self];
3148        [item setAction: @selector(toggleFilterBar:)];
3149       
3150        return item;
3151    }
3152    else
3153        return nil;
3154}
3155
3156- (void) allToolbarClicked: (id) sender
3157{
3158    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3159                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3160    switch (tagValue)
3161    {
3162        case TOOLBAR_PAUSE_TAG:
3163            [self stopAllTorrents: sender];
3164            break;
3165        case TOOLBAR_RESUME_TAG:
3166            [self resumeAllTorrents: sender];
3167            break;
3168    }
3169}
3170
3171- (void) selectedToolbarClicked: (id) sender
3172{
3173    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3174                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3175    switch (tagValue)
3176    {
3177        case TOOLBAR_PAUSE_TAG:
3178            [self stopSelectedTorrents: sender];
3179            break;
3180        case TOOLBAR_RESUME_TAG:
3181            [self resumeSelectedTorrents: sender];
3182            break;
3183    }
3184}
3185
3186- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3187{
3188    return [NSArray arrayWithObjects:
3189            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB,
3190            TOOLBAR_REMOVE, TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3191            TOOLBAR_FILTER, TOOLBAR_INFO,
3192            NSToolbarSeparatorItemIdentifier,
3193            NSToolbarSpaceItemIdentifier,
3194            NSToolbarFlexibleSpaceItemIdentifier,
3195            NSToolbarCustomizeToolbarItemIdentifier, nil];
3196}
3197
3198- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3199{
3200    return [NSArray arrayWithObjects:
3201            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE,
3202            NSToolbarSeparatorItemIdentifier,
3203            TOOLBAR_PAUSE_RESUME_ALL,
3204            NSToolbarFlexibleSpaceItemIdentifier,
3205            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3206}
3207
3208- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3209{
3210    NSString * ident = [toolbarItem itemIdentifier];
3211   
3212    //enable remove item
3213    if ([ident isEqualToString: TOOLBAR_REMOVE])
3214        return [fTableView numberOfSelectedRows] > 0;
3215
3216    //enable pause all item
3217    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3218    {
3219        Torrent * torrent;
3220        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3221        while ((torrent = [enumerator nextObject]))
3222            if ([torrent isActive] || [torrent waitingToStart])
3223                return YES;
3224        return NO;
3225    }
3226
3227    //enable resume all item
3228    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3229    {
3230        Torrent * torrent;
3231        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3232        while ((torrent = [enumerator nextObject]))
3233            if (![torrent isActive] && ![torrent waitingToStart])
3234                return YES;
3235        return NO;
3236    }
3237
3238    //enable pause item
3239    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3240    {
3241        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3242        Torrent * torrent;
3243        while ((torrent = [enumerator nextObject]))
3244            if ([torrent isActive] || [torrent waitingToStart])
3245                return YES;
3246        return NO;
3247    }
3248   
3249    //enable resume item
3250    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3251    {
3252        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3253        Torrent * torrent;
3254        while ((torrent = [enumerator nextObject]))
3255            if (![torrent isActive] && ![torrent waitingToStart])
3256                return YES;
3257        return NO;
3258    }
3259   
3260    //set info image
3261    if ([ident isEqualToString: TOOLBAR_INFO])
3262    {
3263        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue.png"]
3264                                                                    : [NSImage imageNamed: @"Info.png"]];
3265        return YES;
3266    }
3267   
3268    //set filter image
3269    if ([ident isEqualToString: TOOLBAR_FILTER])
3270    {
3271        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue.png"] : [NSImage imageNamed: @"Filter.png"]];
3272        return YES;
3273    }
3274
3275    return YES;
3276}
3277
3278- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3279{
3280    SEL action = [menuItem action];
3281   
3282    if (action == @selector(toggleSpeedLimit:))
3283    {
3284        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3285        return YES;
3286    }
3287   
3288    //only enable some items if it is in a context menu or the window is useable
3289    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3290
3291    //enable open items
3292    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3293        return [fWindow attachedSheet] == nil;
3294   
3295    //enable sort options
3296    if (action == @selector(setSort:))
3297    {
3298        NSString * sortType;
3299        switch ([menuItem tag])
3300        {
3301            case SORT_ORDER_TAG:
3302                sortType = SORT_ORDER;
3303                break;
3304            case SORT_DATE_TAG:
3305                sortType = SORT_DATE;
3306                break;
3307            case SORT_NAME_TAG:
3308                sortType = SORT_NAME;
3309                break;
3310            case SORT_PROGRESS_TAG:
3311                sortType = SORT_PROGRESS;
3312                break;
3313            case SORT_STATE_TAG:
3314                sortType = SORT_STATE;
3315                break;
3316            case SORT_TRACKER_TAG:
3317                sortType = SORT_TRACKER;
3318                break;
3319            case SORT_ACTIVITY_TAG:
3320                sortType = SORT_ACTIVITY;
3321                break;
3322            default:
3323                sortType = @"";
3324        }
3325       
3326        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3327        return [fWindow isVisible];
3328    }
3329   
3330    //enable sort options
3331    if (action == @selector(setStatusLabel:))
3332    {
3333        NSString * statusLabel;
3334        switch ([menuItem tag])
3335        {
3336            case STATUS_RATIO_TOTAL_TAG:
3337                statusLabel = STATUS_RATIO_TOTAL;
3338                break;
3339            case STATUS_RATIO_SESSION_TAG:
3340                statusLabel = STATUS_RATIO_SESSION;
3341                break;
3342            case STATUS_TRANSFER_TOTAL_TAG:
3343                statusLabel = STATUS_TRANSFER_TOTAL;
3344                break;
3345            case STATUS_TRANSFER_SESSION_TAG:
3346                statusLabel = STATUS_TRANSFER_SESSION;
3347                break;
3348            default:
3349                statusLabel = @"";;
3350        }
3351       
3352        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3353        return YES;
3354    }
3355   
3356    if (action == @selector(setGroup:))
3357    {
3358        BOOL checked = NO;
3359       
3360        int index = [menuItem tag];
3361        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3362        Torrent * torrent;
3363        while ((torrent = [enumerator nextObject]))
3364            if (index == [torrent groupValue])
3365            {
3366                checked = YES;
3367                break;
3368            }
3369       
3370        [menuItem setState: checked ? NSOnState : NSOffState];
3371        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3372    }
3373   
3374    if (action == @selector(setGroupFilter:))
3375    {
3376        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3377        return YES;
3378    }
3379   
3380    if (action == @selector(toggleSmallView:))
3381    {
3382        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3383        return [fWindow isVisible];
3384    }
3385   
3386    if (action == @selector(togglePiecesBar:))
3387    {
3388        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3389        return [fWindow isVisible];
3390    }
3391   
3392    if (action == @selector(toggleAvailabilityBar:))
3393    {
3394        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3395        return [fWindow isVisible];
3396    }
3397   
3398    if (action == @selector(setLimitGlobalEnabled:))
3399    {
3400        BOOL upload = [menuItem menu] == fUploadMenu;
3401        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3402        if (limit)
3403            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3404                                    "Action menu -> upload/download limit"),
3405                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3406       
3407        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3408        return YES;
3409    }
3410   
3411    if (action == @selector(setRatioGlobalEnabled:))
3412    {
3413        BOOL check = menuItem == fCheckRatioItem;
3414        if (check)
3415            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3416                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3417       
3418        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3419        return YES;
3420    }
3421
3422    //enable show info
3423    if (action == @selector(showInfo:))
3424    {
3425        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3426                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3427        [menuItem setTitle: title];
3428
3429        return YES;
3430    }
3431   
3432    //enable prev/next inspector tab
3433    if (action == @selector(setInfoTab:))
3434        return [[fInfoController window] isVisible];
3435   
3436    //enable toggle status bar
3437    if (action == @selector(toggleStatusBar:))
3438    {
3439        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3440                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3441        [menuItem setTitle: title];
3442
3443        return [fWindow isVisible];
3444    }
3445   
3446    //enable toggle filter bar
3447    if (action == @selector(toggleFilterBar:))
3448    {
3449        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3450                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3451        [menuItem setTitle: title];
3452
3453        return [fWindow isVisible];
3454    }
3455   
3456    //enable prev/next filter button
3457    if (action == @selector(switchFilter:))
3458        return [fWindow isVisible] && ![fFilterBar isHidden];
3459
3460    //enable reveal in finder
3461    if (action == @selector(revealFile:))
3462        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3463
3464    //enable remove items
3465    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3466        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3467    {
3468        BOOL warning = NO,
3469            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3470            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3471       
3472        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3473        Torrent * torrent;
3474        while ((torrent = [enumerator nextObject]))
3475        {
3476            if (!warning && [torrent isActive])
3477            {
3478                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3479                if (warning && canDelete)
3480                    break;
3481            }
3482            if (!canDelete && [torrent publicTorrent])
3483            {
3484                canDelete = YES;
3485                if (warning)
3486                    break;
3487            }
3488        }
3489   
3490        //append or remove ellipsis when needed
3491        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3492        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3493        {
3494            if (![title hasSuffix: ellipsis])
3495                [menuItem setTitle: [title stringByAppendingEllipsis]];
3496        }
3497        else
3498        {
3499            if ([title hasSuffix: ellipsis])
3500                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3501        }
3502       
3503        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3504    }
3505
3506    //enable pause all item
3507    if (action == @selector(stopAllTorrents:))
3508    {
3509        Torrent * torrent;
3510        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3511        while ((torrent = [enumerator nextObject]))
3512            if ([torrent isActive] || [torrent waitingToStart])
3513                return YES;
3514        return NO;
3515    }
3516   
3517    //enable resume all item
3518    if (action == @selector(resumeAllTorrents:))
3519    {
3520        Torrent * torrent;
3521        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3522        while ((torrent = [enumerator nextObject]))
3523            if (![torrent isActive] && ![torrent waitingToStart])
3524                return YES;
3525        return NO;
3526    }
3527   
3528    #warning hide queue options if all queues are disabled?
3529   
3530    //enable resume all waiting item
3531    if (action == @selector(resumeWaitingTorrents:))
3532    {
3533        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3534            return NO;
3535   
3536        Torrent * torrent;
3537        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3538        while ((torrent = [enumerator nextObject]))
3539            if (![torrent isActive] && [torrent waitingToStart])
3540                return YES;
3541        return NO;
3542    }
3543   
3544    //enable resume selected waiting item
3545    if (action == @selector(resumeSelectedTorrentsNoWait:))
3546    {
3547        if (!canUseTable)
3548            return NO;
3549       
3550        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3551        Torrent * torrent;
3552        while ((torrent = [enumerator nextObject]))
3553            if (![torrent isActive])
3554                return YES;
3555        return NO;
3556    }
3557
3558    //enable pause item
3559    if (action == @selector(stopSelectedTorrents:))
3560    {
3561        if (!canUseTable)
3562            return NO;
3563   
3564        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3565        Torrent * torrent;
3566        while ((torrent = [enumerator nextObject]))
3567            if ([torrent isActive] || [torrent waitingToStart])
3568                return YES;
3569        return NO;
3570    }
3571   
3572    //enable resume item
3573    if (action == @selector(resumeSelectedTorrents:))
3574    {
3575        if (!canUseTable)
3576            return NO;
3577   
3578        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3579        Torrent * torrent;
3580        while ((torrent = [enumerator nextObject]))
3581            if (![torrent isActive] && ![torrent waitingToStart])
3582                return YES;
3583        return NO;
3584    }
3585   
3586    //enable manual announce item
3587    if (action == @selector(announceSelectedTorrents:))
3588    {
3589        if (!canUseTable)
3590            return NO;
3591       
3592        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3593        Torrent * torrent;
3594        while ((torrent = [enumerator nextObject]))
3595            if ([torrent canManualAnnounce])
3596                return YES;
3597        return NO;
3598    }
3599   
3600    //enable reset cache item
3601    if (action == @selector(verifySelectedTorrents:))
3602        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3603   
3604    //enable move torrent file item
3605    if (action == @selector(moveDataFiles:))
3606        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3607   
3608    //enable copy torrent file item
3609    if (action == @selector(copyTorrentFiles:))
3610        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3611   
3612    //enable reverse sort item
3613    if (action == @selector(setSortReverse:))
3614    {
3615        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3616        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3617    }
3618   
3619    //enable group sort item
3620    if (action == @selector(setSortByGroup:))
3621    {
3622        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3623        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3624    }
3625   
3626    //check proper filter search item
3627    if (action == @selector(setFilterSearchType:))
3628    {
3629        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3630       
3631        BOOL state;
3632        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3633            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3634        else
3635            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3636       
3637        [menuItem setState: state ? NSOnState : NSOffState];
3638        return YES;
3639    }
3640   
3641    return YES;
3642}
3643
3644- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
3645{
3646    NSEnumerator * enumerator;
3647    Torrent * torrent;
3648    BOOL allowSleep;
3649
3650    switch (messageType)
3651    {
3652        case kIOMessageSystemWillSleep:
3653            //close all connections before going to sleep and remember we should resume when we wake up
3654            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3655
3656            //wait for running transfers to stop (5 second timeout)
3657            NSDate * start = [NSDate date];
3658            BOOL timeUp = NO;
3659           
3660            enumerator = [fTorrents objectEnumerator];
3661            while (!timeUp && (torrent = [enumerator nextObject]))
3662                while ([torrent isActive] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
3663                {
3664                    usleep(100000);
3665                    [torrent update];
3666                }
3667
3668            IOAllowPowerChange(fRootPort, (long) messageArgument);
3669            break;
3670
3671        case kIOMessageCanSystemSleep:
3672            allowSleep = YES;
3673            if ([fDefaults boolForKey: @"SleepPrevent"])
3674            {
3675                //prevent idle sleep unless no torrents are active
3676                enumerator = [fTorrents objectEnumerator];
3677                while ((torrent = [enumerator nextObject]))
3678                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3679                    {
3680                        allowSleep = NO;
3681                        break;
3682                    }
3683            }
3684
3685            if (allowSleep)
3686                IOAllowPowerChange(fRootPort, (long) messageArgument);
3687            else
3688                IOCancelPowerChange(fRootPort, (long) messageArgument);
3689            break;
3690
3691        case kIOMessageSystemHasPoweredOn:
3692            //resume sleeping transfers after we wake up
3693            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3694            [self autoSpeedLimitChange: nil];
3695            break;
3696    }
3697}
3698
3699- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3700{
3701    int seeding = 0, downloading = 0;
3702    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3703    Torrent * torrent;
3704    while ((torrent = [enumerator nextObject]))
3705    {
3706        if ([torrent isSeeding])
3707            seeding++;
3708        else if ([torrent isActive])
3709            downloading++;
3710        else;
3711    }
3712   
3713    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3714            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3715   
3716    BOOL hasSeparator = seedingItem || downloadingItem;
3717   
3718    if (seeding > 0)
3719    {
3720        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding",
3721                                                        "Dock item - Seeding"), seeding];
3722        if (!seedingItem)
3723        {
3724            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3725            [seedingItem setTag: DOCK_SEEDING_TAG];
3726            [fDockMenu insertItem: seedingItem atIndex: 0];
3727        }
3728        else
3729            [seedingItem setTitle: title];
3730    }
3731    else
3732    {
3733        if (seedingItem)
3734            [fDockMenu removeItem: seedingItem];
3735    }
3736   
3737    if (downloading > 0)
3738    {
3739        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading",
3740                                                        "Dock item - Downloading"), downloading];
3741        if (!downloadingItem)
3742        {
3743            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3744            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3745            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3746        }
3747        else
3748            [downloadingItem setTitle: title];
3749    }
3750    else
3751    {
3752        if (downloadingItem)
3753            [fDockMenu removeItem: downloadingItem];
3754    }
3755   
3756    if (seeding > 0 || downloading > 0)
3757    {
3758        if (!hasSeparator)
3759            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3760    }
3761    else
3762    {
3763        if (hasSeparator)
3764            [fDockMenu removeItemAtIndex: 0];
3765    }
3766   
3767    return fDockMenu;
3768}
3769
3770- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3771{
3772    //if auto size is enabled, the current frame shouldn't need to change
3773    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3774   
3775    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3776    return frame;
3777}
3778
3779- (void) setWindowSizeToFit
3780{
3781    if ([fDefaults boolForKey: @"AutoSize"])
3782    {
3783        NSScrollView * scrollView = [fTableView enclosingScrollView];
3784       
3785        [scrollView setHasVerticalScroller: NO];
3786        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3787        [scrollView setHasVerticalScroller: YES];
3788    }
3789}
3790
3791- (NSRect) sizedWindowFrame
3792{
3793    int groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3794                    ? [fDisplayedTorrents count] : 0;
3795   
3796    float heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3797                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3798                        - [[fTableView enclosingScrollView] frame].size.height;
3799   
3800    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3801}
3802
3803- (void) updateForExpandCollape
3804{
3805    [self setWindowSizeToFit];
3806    [self setBottomCountTextFiltering: YES];
3807}
3808
3809- (void) showMainWindow: (id) sender
3810{
3811    [fWindow makeKeyAndOrderFront: nil];
3812}
3813
3814- (void) windowDidBecomeMain: (NSNotification *) notification
3815{
3816    [fBadger clearCompleted];
3817    [self updateUI];
3818}
3819
3820- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3821{
3822    //only resize horizontally if autosize is enabled
3823    if ([fDefaults boolForKey: @"AutoSize"])
3824        proposedFrameSize.height = [fWindow frame].size.height;
3825    return proposedFrameSize;
3826}
3827
3828- (void) windowDidResize: (NSNotification *) notification
3829{
3830    if ([fFilterBar isHidden])
3831        return;
3832   
3833    //replace all buttons
3834    [fActiveFilterButton sizeToFit];
3835    [fDownloadFilterButton sizeToFit];
3836    [fSeedFilterButton sizeToFit];
3837    [fPauseFilterButton sizeToFit];
3838   
3839    NSRect activeRect = [fActiveFilterButton frame];
3840   
3841    NSRect downloadRect = [fDownloadFilterButton frame];
3842    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
3843   
3844    NSRect seedRect = [fSeedFilterButton frame];
3845    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
3846   
3847    NSRect pauseRect = [fPauseFilterButton frame];
3848    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
3849   
3850    //size search filter to not overlap buttons
3851    NSRect searchFrame = [fSearchFilterField frame];
3852    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
3853    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
3854   
3855    //make sure it is not too long
3856    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
3857    {
3858        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
3859        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
3860    }
3861    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
3862    {
3863        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
3864        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
3865       
3866        //resize each button until they don't overlap search
3867        int download = 0;
3868        BOOL seeding = NO, paused = NO;
3869        do
3870        {
3871            if (download < 8)
3872            {
3873                download++;
3874                downloadRect.size.width--;
3875               
3876                seedRect.origin.x--;
3877                pauseRect.origin.x--;
3878            }
3879            else if (!seeding)
3880            {
3881                seeding = YES;
3882                seedRect.size.width--;
3883               
3884                pauseRect.origin.x--;
3885            }
3886            else if (!paused)
3887            {
3888                paused = YES;
3889                pauseRect.size.width--;
3890            }
3891            else
3892            {
3893                activeRect.size.width--;
3894               
3895                downloadRect.origin.x--;
3896                seedRect.origin.x--;
3897                pauseRect.origin.x--;
3898               
3899                //reset
3900                download = 0;
3901                seeding = NO;
3902                paused = NO;
3903            }
3904        }
3905        while (NSMaxX(pauseRect) + 5.0 > searchFrame.origin.x);
3906    }
3907    else;
3908   
3909    [fActiveFilterButton setFrame: activeRect];
3910    [fDownloadFilterButton setFrame: downloadRect];
3911    [fSeedFilterButton setFrame: seedRect];
3912    [fPauseFilterButton setFrame: pauseRect];
3913   
3914    [fSearchFilterField setFrame: searchFrame];
3915}
3916
3917- (void) applicationWillUnhide: (NSNotification *) notification
3918{
3919    [self updateUI];
3920}
3921
3922- (void) linkHomepage: (id) sender
3923{
3924    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
3925}
3926
3927- (void) linkForums: (id) sender
3928{
3929    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
3930}
3931
3932- (void) linkDonate: (id) sender
3933{
3934    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
3935}
3936
3937- (void) prepareForUpdate: (NSNotification *) notification
3938{
3939    fUpdateInProgress = YES;
3940}
3941
3942- (NSDictionary *) registrationDictionaryForGrowl
3943{
3944    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
3945                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
3946    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
3947                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
3948}
3949
3950- (void) growlNotificationWasClicked: (id) clickContext
3951{
3952    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
3953        return;
3954   
3955    NSString * type = [clickContext objectForKey: @"Type"], * location;
3956    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
3957            && (location = [clickContext objectForKey: @"Location"]))
3958        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
3959}
3960
3961- (void) ipcQuit
3962{
3963    fRemoteQuit = YES;
3964    [NSApp terminate: self];
3965}
3966
3967- (NSArray *) ipcGetTorrentsByID: (NSArray *) idlist
3968{
3969    if (!idlist)
3970        return fTorrents;
3971   
3972    NSMutableArray * torrents = [NSMutableArray array];
3973   
3974    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * idEnum;
3975    int torId;
3976    Torrent * torrent;
3977    NSNumber * tempId;
3978    while ((torrent = [torrentEnum nextObject]))
3979    {
3980        torId = [torrent torrentID];
3981       
3982        idEnum = [idlist objectEnumerator];
3983        while ((tempId = [idEnum nextObject]))
3984        {
3985            if ([tempId intValue] == torId)
3986            {
3987                [torrents addObject: torrent];
3988                break;
3989            }
3990        }
3991    }
3992
3993    return torrents;
3994}
3995
3996- (NSArray *) ipcGetTorrentsByHash: (NSArray *) hashlist
3997{
3998    if (!hashlist)
3999        return fTorrents;
4000   
4001    NSMutableArray * torrents = [NSMutableArray array];
4002   
4003    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * hashEnum;
4004    NSString * torHash, * tempHash;
4005    Torrent * torrent;
4006    while ((torrent = [torrentEnum nextObject]))
4007    {
4008        torHash = [torrent hashString];
4009       
4010        hashEnum = [hashlist objectEnumerator];
4011        while ((tempHash = [hashEnum nextObject]))
4012        {
4013            if ([torHash caseInsensitiveCompare: tempHash] == NSOrderedSame)
4014            {
4015                [torrents addObject: torrent];
4016                break;
4017            }
4018        }
4019    }
4020   
4021    return torrents;
4022}
4023
4024- (BOOL) ipcAddTorrents: (NSArray *) torrents
4025{
4026    int oldCount = [fTorrents count];
4027   
4028    [self openFiles: torrents addType: ADD_NORMAL forcePath: nil];
4029   
4030    return [fTorrents count] > oldCount;
4031}
4032
4033- (BOOL) ipcAddTorrentFile: (NSString *) path directory: (NSString *) directory
4034{
4035    int oldCount = [fTorrents count];
4036   
4037    [self openFiles: [NSArray arrayWithObject: path] addType: ADD_NORMAL forcePath: directory];
4038   
4039    return [fTorrents count] > oldCount;
4040}
4041
4042- (BOOL) ipcAddTorrentFileAutostart: (NSString *) path directory: (NSString *) directory autostart: (BOOL) autostart
4043{
4044    NSArray * torrents = nil;
4045    if (autostart)
4046        torrents = [fTorrents copy];
4047    BOOL success = [self ipcAddTorrentFile: path directory: directory];
4048   
4049    if (success && autostart)
4050    {
4051        NSEnumerator * enumerator = [torrents reverseObjectEnumerator];
4052        Torrent * torrent;
4053        while ((torrent = [enumerator nextObject]))
4054            if (![torrents containsObject: torrent])
4055                break;
4056       
4057        if (torrent)
4058            [torrent startTransfer];
4059        else
4060            success = NO;
4061    }
4062   
4063    [torrents release];
4064    return success;
4065}
4066
4067- (BOOL) ipcAddTorrentData: (NSData *) data directory: (NSString *) directory
4068{
4069    return [self ipcAddTorrentDataAutostart: data directory: directory autostart: [fDefaults boolForKey: @"AutoStartDownload"]];
4070}
4071
4072- (BOOL) ipcAddTorrentDataAutostart: (NSData *) data directory: (NSString *) directory autostart: (BOOL) autostart
4073{
4074    Torrent * torrent;
4075    if ((torrent = [[Torrent alloc] initWithData: data location: directory lib: fLib]))
4076    {
4077        [torrent update];
4078        [fTorrents addObject: torrent];
4079       
4080        if (autostart)
4081            [torrent startTransfer];
4082       
4083        [torrent release];
4084       
4085        [self updateTorrentsInQueue];
4086        return YES;
4087    }
4088    else
4089        return NO;
4090}
4091
4092- (BOOL) ipcStartTorrents: (NSArray *) torrents
4093{
4094    if (!torrents)
4095        [self resumeAllTorrents: self];
4096    else
4097        [self resumeTorrents: torrents];
4098
4099    return YES;
4100}
4101
4102- (BOOL) ipcStopTorrents: (NSArray *) torrents
4103{
4104    if (!torrents)
4105        [self stopAllTorrents: self];
4106    else
4107        [self stopTorrents: torrents];
4108
4109    return YES;
4110}
4111
4112- (BOOL) ipcVerifyTorrents: (NSArray *) torrents
4113{
4114    if (!torrents)
4115        return NO;
4116
4117    [self verifyTorrents: torrents];
4118    return YES;
4119}
4120
4121- (BOOL) ipcRemoveTorrents: (NSArray *) torrents
4122{
4123    if (!torrents)
4124        torrents = [NSArray arrayWithArray: fTorrents];
4125    [torrents retain];
4126
4127    [self confirmRemoveTorrents: torrents deleteData: NO deleteTorrent: NO];
4128
4129    return YES;
4130}
4131
4132@end
Note: See TracBrowser for help on using the repository browser.