source: trunk/macosx/Controller.m @ 3698

Last change on this file since 3698 was 3698, checked in by livings124, 15 years ago

by popular demand the return of the advanced bar (now Pieces Bar)

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