source: trunk/macosx/Controller.m @ 2198

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

fix #233 (move menu item applies to all items)

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