source: trunk/macosx/Controller.m @ 5786

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

make the "group = none" image an empty box

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