source: trunk/macosx/Controller.m @ 2169

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

simplify some of the repetitive queue code a bit

  • Property svn:keywords set to Date Rev Author Id
File size: 118.5 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 2169 2007-06-20 00:54:05Z 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    [self moveDataFileForTorrents: [[NSMutableArray alloc] initWithArray:
1187            [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]]];
1188}
1189
1190- (void) moveDataFileForTorrents: (NSMutableArray *) torrents
1191{
1192    if ([torrents count] <= 0)
1193    {
1194        [torrents release];
1195        return;
1196    }
1197
1198    Torrent * torrent = [torrents objectAtIndex: 0];
1199
1200    NSOpenPanel * panel = [NSOpenPanel openPanel];
1201   
1202    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1203    [panel setAllowsMultipleSelection: NO];
1204    [panel setCanChooseFiles: NO];
1205    [panel setCanChooseDirectories: YES];
1206    [panel setCanCreateDirectories: YES];
1207
1208    [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\"",
1209                        "Move torrent -> select destination folder"), [torrent name]]];
1210       
1211    [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1212        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1213}
1214
1215- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSMutableArray *) torrents
1216{
1217    //move torrent data file to new location
1218    if (code == NSOKButton)
1219        [[torrents objectAtIndex: 0] moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1220   
1221    [torrents removeObjectAtIndex: 0];
1222    [self performSelectorOnMainThread: @selector(moveDataFileForTorrents:) withObject: torrents waitUntilDone: NO];
1223}
1224
1225- (void) copyTorrentFiles: (id) sender
1226{
1227    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
1228            [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]]];
1229}
1230
1231- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1232{
1233    if ([torrents count] <= 0)
1234    {
1235        [torrents release];
1236        return;
1237    }
1238
1239    Torrent * torrent = [torrents objectAtIndex: 0];
1240
1241    //warn user if torrent file can't be found
1242    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1243    {
1244        NSAlert * alert = [[NSAlert alloc] init];
1245        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1246        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1247                                "Torrent file copy alert -> title"), [torrent name]]];
1248        [alert setInformativeText: [NSString stringWithFormat:
1249                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1250                                    [torrent torrentLocation]]];
1251        [alert setAlertStyle: NSWarningAlertStyle];
1252       
1253        [alert runModal];
1254        [alert release];
1255       
1256        [torrents removeObjectAtIndex: 0];
1257        [self copyTorrentFileForTorrents: torrents];
1258    }
1259    else
1260    {
1261        NSSavePanel * panel = [NSSavePanel savePanel];
1262        [panel setRequiredFileType: @"torrent"];
1263        [panel setCanSelectHiddenExtension: YES];
1264       
1265        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1266            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1267    }
1268}
1269
1270- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (NSMutableArray *) torrents
1271{
1272    //copy torrent to new location with name of data file
1273    if (code == NSOKButton)
1274        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1275   
1276    [torrents removeObjectAtIndex: 0];
1277    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1278}
1279
1280- (void) revealFile: (id) sender
1281{
1282    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
1283    Torrent * torrent;
1284    while ((torrent = [enumerator nextObject]))
1285        [torrent revealData];
1286}
1287
1288- (void) announceSelectedTorrents: (id) sender
1289{
1290    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
1291    Torrent * torrent;
1292    NSDate * date;
1293    while ((torrent = [enumerator nextObject]))
1294    {
1295        //time interval returned will be negative
1296        if (!(date = [torrent announceDate]) || [date timeIntervalSinceNow] <= ANNOUNCE_WAIT_INTERVAL_SECONDS)
1297            [torrent announce];
1298    }
1299}
1300
1301- (void) resetCacheForSelectedTorrents: (id) sender
1302{
1303    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
1304    Torrent * torrent;
1305    while ((torrent = [enumerator nextObject]))
1306    {
1307        [torrent resetCache];
1308    }
1309}
1310
1311- (void) showPreferenceWindow: (id) sender
1312{
1313    NSWindow * window = [fPrefsController window];
1314    if (![window isVisible])
1315        [window center];
1316
1317    [window makeKeyAndOrderFront: nil];
1318}
1319
1320- (void) showInfo: (id) sender
1321{
1322    if ([[fInfoController window] isVisible])
1323        [fInfoController close];
1324    else
1325    {
1326        [fInfoController updateInfoStats];
1327        [[fInfoController window] orderFront: nil];
1328    }
1329}
1330
1331- (void) setInfoTab: (id) sender
1332{
1333    if (sender == fNextInfoTabItem)
1334        [fInfoController setNextTab];
1335    else
1336        [fInfoController setPreviousTab];
1337}
1338
1339- (void) showMessageWindow: (id) sender
1340{
1341    [fMessageController showWindow: nil];
1342}
1343
1344- (void) updateUI
1345{
1346    [fTorrents makeObjectsPerformSelector: @selector(update)];
1347
1348    //resort if necessary or just update the table
1349    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1350    if ([sortType isEqualToString: @"Progress"] || [sortType isEqualToString: @"State"])
1351        [self sortTorrents];
1352    else
1353        [fTableView reloadData];
1354   
1355    //update the global DL/UL rates
1356    float downloadRate, uploadRate;
1357    tr_torrentRates(fLib, & downloadRate, & uploadRate);
1358    if (![fStatusBar isHidden])
1359    {
1360        [fTotalDLField setStringValue: [NSLocalizedString(@"Total DL: ", "Status bar -> total download")
1361                                        stringByAppendingString: [NSString stringForSpeed: downloadRate]]];
1362        [fTotalULField setStringValue: [NSLocalizedString(@"Total UL: ", "Status bar -> total upload")
1363                                        stringByAppendingString: [NSString stringForSpeed: uploadRate]]];
1364    }
1365
1366    //update non-constant parts of info window
1367    if ([[fInfoController window] isVisible])
1368        [fInfoController updateInfoStats];
1369
1370    //badge dock
1371    [fBadger updateBadge];
1372}
1373
1374- (void) updateTorrentsInQueue
1375{
1376    BOOL download = [fDefaults boolForKey: @"Queue"],
1377        seed = [fDefaults boolForKey: @"QueueSeed"];
1378   
1379    int desiredDownloadActive = [self numToStartFromQueue: YES],
1380        desiredSeedActive = [self numToStartFromQueue: NO];
1381   
1382    //sort torrents by order value
1383    NSArray * sortedTorrents;
1384    if ([fTorrents count] > 1 && (desiredDownloadActive > 0 || desiredSeedActive > 0))
1385    {
1386        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1387                                                @"orderValue" ascending: YES] autorelease];
1388        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1389       
1390        sortedTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
1391        [descriptors release];
1392    }
1393    else
1394        sortedTorrents = fTorrents;
1395
1396    Torrent * torrent;
1397    NSEnumerator * enumerator = [sortedTorrents objectEnumerator];
1398    while ((torrent = [enumerator nextObject]))
1399    {
1400        if (![torrent isActive] && [torrent waitingToStart])
1401        {
1402            if (![torrent allDownloaded])
1403            {
1404                if (!download || desiredDownloadActive > 0)
1405                {
1406                    [torrent startTransfer];
1407                    if ([torrent isActive])
1408                        desiredDownloadActive--;
1409                    [torrent update];
1410                }
1411            }
1412            else
1413            {
1414                if (!seed || desiredSeedActive > 0)
1415                {
1416                    [torrent startTransfer];
1417                    if ([torrent isActive])
1418                        desiredSeedActive--;
1419                    [torrent update];
1420                }
1421            }
1422        }
1423    }
1424   
1425    [self updateUI];
1426    [self applyFilter: nil];
1427    [self updateTorrentHistory];
1428}
1429
1430- (int) numToStartFromQueue: (BOOL) downloadQueue
1431{
1432    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1433        return 0;
1434   
1435    int desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1436       
1437    Torrent * torrent;
1438    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1439    while ((torrent = [enumerator nextObject]))
1440        if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1441        {
1442            if ([torrent allDownloaded] != downloadQueue)
1443            {
1444                desired--;
1445                if (desired <= 0)
1446                    return 0;
1447            }
1448        }
1449   
1450    return desired;
1451}
1452
1453- (void) torrentFinishedDownloading: (NSNotification *) notification
1454{
1455    Torrent * torrent = [notification object];
1456   
1457    [fInfoController updateInfoStats];
1458   
1459    if ([fDefaults boolForKey: @"PlayDownloadSound"])
1460    {
1461        NSSound * sound;
1462        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1463            [sound play];
1464    }
1465   
1466    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1467                                    [torrent dataLocation] , @"Location", nil];
1468    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1469                                description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1470                                iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1471   
1472    if (![fWindow isKeyWindow])
1473        [fBadger incrementCompleted];
1474   
1475    if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1476    {
1477        [torrent stopTransfer];
1478        [torrent setWaitToStart: YES];
1479    }
1480   
1481    [self updateTorrentsInQueue];
1482}
1483
1484- (void) torrentRestartedDownloading: (NSNotification *) notification
1485{
1486    Torrent * torrent = [notification object];
1487   
1488    [fInfoController updateInfoStats];
1489   
1490    if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1491    {
1492        [torrent stopTransfer];
1493        [torrent setWaitToStart: YES];
1494    }
1495   
1496    [self updateTorrentsInQueue];
1497}
1498
1499- (void) updateTorrentHistory
1500{
1501    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1502
1503    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1504    Torrent * torrent;
1505    while ((torrent = [enumerator nextObject]))
1506        [history addObject: [torrent history]];
1507
1508    [history writeToFile: [[self applicationSupportFolder] stringByAppendingPathComponent: @"Transfers.plist"] atomically: YES];
1509}
1510
1511- (void) sortTorrents
1512{
1513    //remember selected rows if needed
1514    NSArray * selectedTorrents = nil;
1515    int numSelected = [fTableView numberOfSelectedRows];
1516    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1517        selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1518
1519    [self sortTorrentsIgnoreSelected]; //actually sort
1520   
1521    //set selected rows if needed
1522    if (selectedTorrents)
1523    {
1524        Torrent * torrent;
1525        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1526        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1527        while ((torrent = [enumerator nextObject]))
1528            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1529       
1530        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1531        [indexSet release];
1532    }
1533}
1534
1535//doesn't remember selected rows
1536- (void) sortTorrentsIgnoreSelected
1537{
1538    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1539    BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1540   
1541    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1542                            ascending: asc selector: @selector(caseInsensitiveCompare:)] autorelease],
1543                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1544                                            ascending: asc] autorelease];
1545   
1546    NSArray * descriptors;
1547    if ([sortType isEqualToString: @"Name"])
1548        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1549    else if ([sortType isEqualToString: @"State"])
1550    {
1551        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1552                                                @"stateSortKey" ascending: !asc] autorelease],
1553                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1554                                            @"progressSortKey" ascending: !asc] autorelease],
1555                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1556                                            @"ratioSortKey" ascending: !asc] autorelease];
1557       
1558        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1559                                                            nameDescriptor, orderDescriptor, nil];
1560    }
1561    else if ([sortType isEqualToString: @"Progress"])
1562    {
1563        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1564                                            @"progressSortKey" ascending: asc] autorelease],
1565                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1566                                            @"ratioSortKey" ascending: asc] autorelease];
1567       
1568        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioDescriptor,
1569                                                            nameDescriptor, orderDescriptor, nil];
1570    }
1571    else if ([sortType isEqualToString: @"Order"])
1572        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1573    else
1574    {
1575        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1576   
1577        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1578    }
1579
1580    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1581    [descriptors release];
1582   
1583    [fTableView reloadData];
1584}
1585
1586- (void) setSort: (id) sender
1587{
1588    NSString * oldSortType = [fDefaults stringForKey: @"Sort"];
1589   
1590    //get checked items
1591    NSMenuItem * prevSortItem, * prevSortActionItem;
1592    if ([oldSortType isEqualToString: @"Name"])
1593    {
1594        prevSortItem = fNameSortItem;
1595        prevSortActionItem = fNameSortActionItem;
1596    }
1597    else if ([oldSortType isEqualToString: @"State"])
1598    {
1599        prevSortItem = fStateSortItem;
1600        prevSortActionItem = fStateSortActionItem;
1601    }
1602    else if ([oldSortType isEqualToString: @"Progress"])
1603    {
1604        prevSortItem = fProgressSortItem;
1605        prevSortActionItem = fProgressSortActionItem;
1606    }
1607    else if ([oldSortType isEqualToString: @"Order"])
1608    {
1609        prevSortItem = fOrderSortItem;
1610        prevSortActionItem = fOrderSortActionItem;
1611    }
1612    else
1613    {
1614        prevSortItem = fDateSortItem;
1615        prevSortActionItem = fDateSortActionItem;
1616    }
1617   
1618    if (sender != prevSortItem && sender != prevSortActionItem)
1619    {
1620        //get new items to check
1621        NSMenuItem * currentSortItem, * currentSortActionItem;
1622        NSString * sortType;
1623        if (sender == fNameSortItem || sender == fNameSortActionItem)
1624        {
1625            currentSortItem = fNameSortItem;
1626            currentSortActionItem = fNameSortActionItem;
1627            sortType = @"Name";
1628        }
1629        else if (sender == fStateSortItem || sender == fStateSortActionItem)
1630        {
1631            currentSortItem = fStateSortItem;
1632            currentSortActionItem = fStateSortActionItem;
1633            sortType = @"State";
1634        }
1635        else if (sender == fProgressSortItem || sender == fProgressSortActionItem)
1636        {
1637            currentSortItem = fProgressSortItem;
1638            currentSortActionItem = fProgressSortActionItem;
1639            sortType = @"Progress";
1640        }
1641        else if (sender == fOrderSortItem || sender == fOrderSortActionItem)
1642        {
1643            currentSortItem = fOrderSortItem;
1644            currentSortActionItem = fOrderSortActionItem;
1645            sortType = @"Order";
1646           
1647            [fDefaults setBool: NO forKey: @"SortReverse"];
1648        }
1649        else
1650        {
1651            currentSortItem = fDateSortItem;
1652            currentSortActionItem = fDateSortActionItem;
1653            sortType = @"Date";
1654        }
1655       
1656        [fDefaults setObject: sortType forKey: @"Sort"];
1657   
1658        [prevSortItem setState: NSOffState];
1659        [prevSortActionItem setState: NSOffState];
1660        [currentSortItem setState: NSOnState];
1661        [currentSortActionItem setState: NSOnState];
1662    }
1663
1664    [self sortTorrents];
1665}
1666
1667- (void) setSortReverse: (id) sender
1668{
1669    [self sortTorrents];
1670}
1671
1672- (void) applyFilter: (id) sender
1673{
1674    //remember selected rows if needed
1675    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1676                ? [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1677
1678    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1679   
1680    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1681    BOOL filtering = ![filterType isEqualToString: @"None"];
1682   
1683    int downloading = 0, seeding = 0, paused = 0;
1684    BOOL isDownloading = [filterType isEqualToString: @"Download"],
1685            isSeeding = [filterType isEqualToString: @"Seed"],
1686            isPaused = [filterType isEqualToString: @"Pause"];
1687   
1688    //get count of each type
1689    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1690    Torrent * torrent;
1691    while ((torrent = [enumerator nextObject]))
1692    {
1693        if ([torrent isActive])
1694        {
1695            if ([torrent isSeeding])
1696            {
1697                seeding++;
1698                if (isSeeding)
1699                    [tempTorrents addObject: torrent];
1700            }
1701            else
1702            {
1703                downloading++;
1704                if (isDownloading)
1705                    [tempTorrents addObject: torrent];
1706            }
1707        }
1708        else
1709        {
1710            paused++;
1711            if (isPaused)
1712                [tempTorrents addObject: torrent];
1713        }
1714    }
1715   
1716    if (!filtering)
1717        [tempTorrents setArray: fTorrents];
1718   
1719    //set buttons with counts
1720    [fNoFilterButton setCount: [fTorrents count]];
1721    [fDownloadFilterButton setCount: downloading];
1722    [fSeedFilterButton setCount: seeding];
1723    [fPauseFilterButton setCount: paused];
1724   
1725    NSString * searchString = [fSearchFilterField stringValue];
1726    if ([searchString length] > 0)
1727    {
1728        filtering = YES;
1729       
1730        int i;
1731        for (i = [tempTorrents count] - 1; i >= 0; i--)
1732            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1733                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1734                [tempTorrents removeObjectAtIndex: i];
1735    }
1736   
1737    [fDisplayedTorrents setArray: tempTorrents];
1738    [tempTorrents release];
1739   
1740    [self sortTorrentsIgnoreSelected];
1741   
1742    //set selected rows if needed
1743    if (selectedTorrents)
1744    {
1745        Torrent * torrent;
1746        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1747        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1748        unsigned index;
1749        while ((torrent = [enumerator nextObject]))
1750            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1751                [indexSet addIndex: index];
1752       
1753        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1754        [indexSet release];
1755    }
1756   
1757    //set status bar torrent count text
1758    NSMutableString * totalTorrentsString = [[NSMutableString alloc] initWithString: @""];
1759    if (filtering)
1760        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1761   
1762    int totalCount = [fTorrents count];
1763    if (totalCount != 1)
1764        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfers", "Status bar transfer count"), totalCount];
1765    else
1766        [totalTorrentsString appendFormat: NSLocalizedString(@"1 Transfer", "Status bar transfer count")];
1767   
1768    [fTotalTorrentsField setStringValue: totalTorrentsString];
1769    [totalTorrentsString release];
1770
1771    [self setWindowSizeToFit];
1772}
1773
1774//resets filter and sorts torrents
1775- (void) setFilter: (id) sender
1776{
1777    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
1778   
1779    FilterBarButton * prevFilterButton;
1780    if ([oldFilterType isEqualToString: @"Pause"])
1781        prevFilterButton = fPauseFilterButton;
1782    else if ([oldFilterType isEqualToString: @"Seed"])
1783        prevFilterButton = fSeedFilterButton;
1784    else if ([oldFilterType isEqualToString: @"Download"])
1785        prevFilterButton = fDownloadFilterButton;
1786    else
1787        prevFilterButton = fNoFilterButton;
1788   
1789    if (sender != prevFilterButton)
1790    {
1791        [prevFilterButton setEnabled: NO];
1792        [sender setEnabled: YES];
1793
1794        NSString * filterType;
1795        if (sender == fDownloadFilterButton)
1796            filterType = @"Download";
1797        else if (sender == fPauseFilterButton)
1798            filterType = @"Pause";
1799        else if (sender == fSeedFilterButton)
1800            filterType = @"Seed";
1801        else
1802            filterType = @"None";
1803
1804        [fDefaults setObject: filterType forKey: @"Filter"];
1805    }
1806
1807    [self applyFilter: nil];
1808}
1809
1810- (void) switchFilter: (id) sender
1811{
1812    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1813   
1814    NSButton * button;
1815    if ([filterType isEqualToString: @"None"])
1816        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1817    else if ([filterType isEqualToString: @"Download"])
1818        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1819    else if ([filterType isEqualToString: @"Seed"])
1820        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1821    else if ([filterType isEqualToString: @"Pause"])
1822        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1823    else
1824        button = fNoFilterButton;
1825   
1826    [self setFilter: button];
1827}
1828
1829- (void) updateControlTint: (NSNotification *) notification
1830{
1831    if ([fDefaults boolForKey: @"SpeedLimit"])
1832        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
1833            ? [NSImage imageNamed: @"SpeedLimitButtonBlue.png"] : [NSImage imageNamed: @"SpeedLimitButtonGraphite.png"]];
1834}
1835
1836- (void) applySpeedLimit: (id) sender
1837{
1838    [fPrefsController applySpeedSettings: nil];
1839}
1840
1841- (void) toggleSpeedLimit: (id) sender
1842{
1843    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
1844    [self applySpeedLimit: nil];
1845}
1846
1847- (void) autoSpeedLimitChange: (NSNotification *) notification
1848{
1849    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1850        return;
1851 
1852    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1853                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
1854        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1855                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
1856        * nowDate = [NSCalendarDate calendarDate];
1857   
1858    //check if should be on if within range
1859    BOOL shouldBeOn;
1860   
1861    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
1862        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
1863        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
1864   
1865    if (onTime == offTime)
1866        shouldBeOn = NO;
1867    else if (onTime < offTime)
1868        shouldBeOn = onTime <= nowTime && nowTime < offTime;
1869    else
1870        shouldBeOn = onTime <= nowTime || nowTime < offTime;
1871   
1872    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
1873        [self toggleSpeedLimit: nil];
1874}
1875
1876- (void) autoSpeedLimit
1877{
1878    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1879        return;
1880   
1881    //only toggle if within first few seconds of minutes
1882    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
1883    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
1884        return;
1885   
1886    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1887                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
1888   
1889    BOOL toggle;
1890    if ([fDefaults boolForKey: @"SpeedLimit"])
1891        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
1892    else
1893    {
1894        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1895                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
1896        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
1897                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
1898    }
1899   
1900    if (toggle)
1901    {
1902        [self toggleSpeedLimit: nil];
1903       
1904        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
1905                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
1906                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
1907            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
1908            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1909    }
1910}
1911
1912- (void) setLimitGlobalEnabled: (id) sender
1913{
1914    [fPrefsController applySpeedSettings: nil];
1915}
1916
1917- (void) setQuickLimitGlobal: (id) sender
1918{
1919    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
1920    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
1921   
1922    [fPrefsController updateLimitFields];
1923    [fPrefsController applySpeedSettings: nil];
1924}
1925
1926- (void) setQuickRatioGlobal: (id) sender
1927{
1928    [fDefaults setBool: YES forKey: @"RatioCheck"];
1929    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
1930   
1931    [fPrefsController updateRatioStopField];
1932}
1933
1934- (void) torrentStoppedForRatio: (NSNotification *) notification
1935{
1936    Torrent * torrent = [notification object];
1937   
1938    [self updateTorrentsInQueue];
1939    [fInfoController updateInfoStats];
1940    [fInfoController updateRatioForTorrent: torrent];
1941   
1942    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1943    {
1944        NSSound * sound;
1945        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1946            [sound play];
1947    }
1948   
1949    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
1950                                    [torrent dataLocation], @"Location", nil];
1951    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1952                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1953                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1954}
1955
1956-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
1957{
1958    if ([notification isEqualToString: UKFileWatcherWriteNotification])
1959    {
1960        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
1961            return;
1962       
1963        if (fAutoImportTimer)
1964        {
1965            if ([fAutoImportTimer isValid])
1966                [fAutoImportTimer invalidate];
1967            [fAutoImportTimer release];
1968            fAutoImportTimer = nil;
1969        }
1970       
1971        //check again in 10 seconds in case torrent file wasn't complete
1972        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
1973            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
1974       
1975        [self checkAutoImportDirectory];
1976    }
1977}
1978
1979- (void) changeAutoImport
1980{
1981    if (fAutoImportTimer)
1982    {
1983        if ([fAutoImportTimer isValid])
1984            [fAutoImportTimer invalidate];
1985        [fAutoImportTimer release];
1986        fAutoImportTimer = nil;
1987    }
1988   
1989    [fAutoImportedNames removeAllObjects];
1990    [self checkAutoImportDirectory];
1991}
1992
1993- (void) checkAutoImportDirectory
1994{
1995    NSString * path;
1996    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
1997        return;
1998   
1999    path = [path stringByExpandingTildeInPath];
2000   
2001    NSArray * importedNames;
2002    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2003        return;
2004   
2005    //only check files that have not been checked yet
2006    NSMutableArray * newNames = [importedNames mutableCopy];
2007    [newNames removeObjectsInArray: fAutoImportedNames];
2008    [fAutoImportedNames setArray: importedNames];
2009   
2010    NSString * file;
2011    int i;
2012    for (i = [newNames count] - 1; i >= 0; i--)
2013    {
2014        file = [newNames objectAtIndex: i];
2015        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2016            [newNames removeObjectAtIndex: i];
2017        else
2018            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2019    }
2020   
2021    NSEnumerator * enumerator;
2022    if (![[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"])
2023    {
2024        enumerator = [newNames objectEnumerator];
2025        int count;
2026        while ((file = [enumerator nextObject]))
2027        {
2028            count = [fTorrents count];
2029            [self openFiles: [NSArray arrayWithObject: file]];
2030           
2031            //check if torrent was opened
2032            if ([fTorrents count] > count)
2033                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
2034                    "Growl notification title") description: [file lastPathComponent]
2035                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
2036        }
2037    }
2038    else
2039        [self openFiles: newNames];
2040   
2041    //create temporary torrents to check if an import fails because of an error
2042    enumerator = [newNames objectEnumerator];
2043    int error;
2044    while ((file = [enumerator nextObject]))
2045    {
2046        tr_torrent_t * tempTor = tr_torrentInit(fLib, [file UTF8String], NULL, 0, &error);
2047       
2048        if (tempTor)
2049            tr_torrentClose(tempTor);
2050        else if (error != TR_EUNSUPPORTED && error != TR_EDUPLICATE)
2051            [fAutoImportedNames removeObject: [file lastPathComponent]]; //can try to import later
2052        else;
2053    }
2054   
2055    [newNames release];
2056}
2057
2058- (int) numberOfRowsInTableView: (NSTableView *) tableview
2059{
2060    return [fDisplayedTorrents count];
2061}
2062
2063- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
2064{
2065    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
2066}
2067
2068- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
2069    toPasteboard: (NSPasteboard *) pasteboard
2070{
2071    //only allow reordering of rows if sorting by order with no filter
2072    if ([[fDefaults stringForKey: @"Sort"] isEqualToString: @"Order"]
2073        && [[fDefaults stringForKey: @"Filter"] isEqualToString: @"None"]
2074        && [[fSearchFilterField stringValue] length] == 0)
2075    {
2076        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2077        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
2078                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2079        return YES;
2080    }
2081    return NO;
2082}
2083
2084- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
2085    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
2086{
2087    NSPasteboard * pasteboard = [info draggingPasteboard];
2088    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2089    {
2090        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
2091        return NSDragOperationGeneric;
2092    }
2093    else;
2094   
2095    return NSDragOperationNone;
2096}
2097
2098- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
2099    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
2100{
2101    NSPasteboard * pasteboard = [info draggingPasteboard];
2102    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2103    {
2104        //remember selected rows if needed
2105        NSArray * selectedTorrents = nil;
2106        int numSelected = [fTableView numberOfSelectedRows];
2107        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
2108            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
2109   
2110        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
2111                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2112       
2113        //move torrent in array
2114        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
2115        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
2116       
2117        //determine the insertion index now that transfers to move have been removed
2118        int i, decrease = 0;
2119        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2120            decrease++;
2121       
2122        //insert objects at new location
2123        for (i = 0; i < [movingTorrents count]; i++)
2124            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
2125       
2126        [movingTorrents release];
2127       
2128        //redo order values
2129        int low = [indexes firstIndex], high = [indexes lastIndex];
2130        if (newRow < low)
2131            low = newRow;
2132        else if (newRow > high + 1)
2133            high = newRow - 1;
2134        else;
2135       
2136        for (i = low; i <= high; i++)
2137            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
2138       
2139        [fTableView reloadData];
2140       
2141        //set selected rows if needed
2142        if (selectedTorrents)
2143        {
2144            Torrent * torrent;
2145            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
2146            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
2147            while ((torrent = [enumerator nextObject]))
2148                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
2149           
2150            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
2151            [indexSet release];
2152        }
2153    }
2154    else;
2155   
2156    return YES;
2157}
2158
2159- (void) tableViewSelectionDidChange: (NSNotification *) notification
2160{
2161    [fInfoController updateInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
2162}
2163
2164- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2165{
2166    NSPasteboard * pasteboard = [info draggingPasteboard];
2167    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2168    {
2169        //check if any torrent files can be added
2170        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2171        NSEnumerator * enumerator = [files objectEnumerator];
2172        NSString * file;
2173        tr_torrent_t * tempTor;
2174        BOOL torrent = NO;
2175        while ((file = [enumerator nextObject]))
2176        {
2177            int error;
2178            if ((tempTor = tr_torrentInit(fLib, [file UTF8String], NULL, 0, &error)))
2179            {
2180                tr_torrentClose(tempTor);
2181               
2182                if (!fOverlayWindow)
2183                    fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2184                [fOverlayWindow setTorrents: files];
2185               
2186                return NSDragOperationCopy;
2187            }
2188            else
2189            {
2190                if (error == TR_EUNSUPPORTED || error == TR_EDUPLICATE)
2191                    torrent = YES;
2192            }
2193        }
2194       
2195        //create a torrent file if a single file
2196        if (!torrent && [files count] == 1)
2197        {
2198            if (!fOverlayWindow)
2199                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2200            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2201           
2202            return NSDragOperationCopy;
2203        }
2204    }
2205    else if ([[pasteboard types] containsObject: NSURLPboardType])
2206    {
2207        if (!fOverlayWindow)
2208            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2209        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2210       
2211        return NSDragOperationCopy;
2212    }
2213    else;
2214   
2215    return NSDragOperationNone;
2216}
2217
2218- (void) draggingExited: (id <NSDraggingInfo>) info
2219{
2220    if (fOverlayWindow)
2221        [fOverlayWindow fadeOut];
2222}
2223
2224- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2225{
2226    if (fOverlayWindow)
2227        [fOverlayWindow fadeOut];
2228   
2229    NSPasteboard * pasteboard = [info draggingPasteboard];
2230    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2231    {
2232        BOOL torrent = NO, accept = YES;
2233       
2234        //create an array of files that can be opened
2235        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2236        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2237        NSEnumerator * enumerator = [files objectEnumerator];
2238        NSString * file;
2239        tr_torrent_t * tempTor;
2240        while ((file = [enumerator nextObject]))
2241        {
2242            int error;
2243            if ((tempTor = tr_torrentInit(fLib, [file UTF8String], NULL, 0, &error)))
2244            {
2245                tr_torrentClose(tempTor);
2246                [filesToOpen addObject: file];
2247               
2248                torrent = YES;
2249            }
2250            else
2251            {
2252                if (error == TR_EUNSUPPORTED || error == TR_EDUPLICATE)
2253                    torrent = YES;
2254            }
2255        }
2256       
2257        if ([filesToOpen count] > 0)
2258            [self application: NSApp openFiles: filesToOpen];
2259        else
2260        {
2261            if (!torrent && [files count] == 1)
2262                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2263            else
2264                accept = NO;
2265        }
2266        [filesToOpen release];
2267       
2268        return accept;
2269    }
2270    else if ([[pasteboard types] containsObject: NSURLPboardType])
2271    {
2272        NSURL * url;
2273        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2274        {
2275            [self openURL: url];
2276            return YES;
2277        }
2278    }
2279    else;
2280   
2281    return NO;
2282}
2283
2284- (void) toggleSmallView: (id) sender
2285{
2286    BOOL makeSmall = [fDefaults boolForKey: @"SmallView"];
2287   
2288    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2289   
2290    //window min height
2291    NSSize contentMinSize = [fWindow contentMinSize],
2292            contentSize = [[fWindow contentView] frame].size;
2293    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
2294                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2295    [fWindow setContentMinSize: contentMinSize];
2296   
2297    //resize for larger min height if not set to auto size
2298    if (![fDefaults boolForKey: @"AutoSize"])
2299    {
2300        if (!makeSmall && contentSize.height < contentMinSize.height)
2301        {
2302            NSRect frame = [fWindow frame];
2303            float heightChange = contentMinSize.height - contentSize.height;
2304            frame.size.height += heightChange;
2305            frame.origin.y -= heightChange;
2306           
2307            [fWindow setFrame: frame display: YES];
2308            [fTableView reloadData];
2309        }
2310    }
2311    else
2312        [self setWindowSizeToFit];
2313}
2314
2315- (void) toggleStatusBar: (id) sender
2316{
2317    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2318    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2319}
2320
2321- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2322{
2323    //convert pixels to points
2324    NSRect windowFrame = [fWindow frame];
2325    NSSize windowSize = [fScrollView convertSize: windowFrame.size fromView: nil];
2326    windowSize.height += height;
2327   
2328    if (check)
2329    {
2330        NSSize minSize = [fScrollView convertSize: [fWindow minSize] fromView: nil];
2331       
2332        if (windowSize.height < minSize.height)
2333            windowSize.height = minSize.height;
2334        else
2335        {
2336            NSSize maxSize = [fScrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2337            if ([fStatusBar isHidden])
2338                maxSize.height -= [fStatusBar frame].size.height;
2339            if ([fFilterBar isHidden])
2340                maxSize.height -= [fFilterBar frame].size.height;
2341            if (windowSize.height > maxSize.height)
2342                windowSize.height = maxSize.height;
2343        }
2344    }
2345
2346    //convert points to pixels
2347    windowSize = [fScrollView convertSize: windowSize toView: nil];
2348
2349    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2350    windowFrame.size.height = windowSize.height;
2351    return windowFrame;
2352}
2353
2354- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2355{
2356    if (show != [fStatusBar isHidden])
2357        return;
2358
2359    if (show)
2360        [fStatusBar setHidden: NO];
2361
2362    NSRect frame;
2363    float heightChange = [fStatusBar frame].size.height;
2364    if (!show)
2365        heightChange *= -1;
2366   
2367    //allow bar to show even if not enough room
2368    if (show && ![fDefaults boolForKey: @"AutoSize"])
2369    {
2370        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2371        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2372        if (change < 0.0)
2373        {
2374            frame = [fWindow frame];
2375            frame.size.height += change;
2376            frame.origin.y -= change;
2377            [fWindow setFrame: frame display: NO animate: NO];
2378        }
2379    }
2380
2381    [self updateUI];
2382   
2383    //set views to not autoresize
2384    unsigned int statsMask = [fStatusBar autoresizingMask];
2385    unsigned int filterMask = [fFilterBar autoresizingMask];
2386    unsigned int scrollMask = [fScrollView autoresizingMask];
2387    [fStatusBar setAutoresizingMask: 0];
2388    [fFilterBar setAutoresizingMask: 0];
2389    [fScrollView setAutoresizingMask: 0];
2390   
2391    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2392    [fWindow setFrame: frame display: YES animate: animate];
2393   
2394    //re-enable autoresize
2395    [fStatusBar setAutoresizingMask: statsMask];
2396    [fFilterBar setAutoresizingMask: filterMask];
2397    [fScrollView setAutoresizingMask: scrollMask];
2398   
2399    //change min size
2400    NSSize minSize = [fWindow contentMinSize];
2401    minSize.height += heightChange;
2402    [fWindow setContentMinSize: minSize];
2403   
2404    if (!show)
2405        [fStatusBar setHidden: YES];
2406}
2407
2408- (void) toggleFilterBar: (id) sender
2409{
2410    //disable filtering when hiding
2411    if (![fFilterBar isHidden])
2412    {
2413        [fSearchFilterField setStringValue: @""];
2414        [self setFilter: fNoFilterButton];
2415    }
2416
2417    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2418    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2419}
2420
2421- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2422{
2423    if (show != [fFilterBar isHidden])
2424        return;
2425
2426    if (show)
2427        [fFilterBar setHidden: NO];
2428
2429    NSRect frame;
2430    float heightChange = [fFilterBar frame].size.height;
2431    if (!show)
2432        heightChange *= -1;
2433   
2434    //allow bar to show even if not enough room
2435    if (show && ![fDefaults boolForKey: @"AutoSize"])
2436    {
2437        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2438        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2439        if (change < 0.0)
2440        {
2441            frame = [fWindow frame];
2442            frame.size.height += change;
2443            frame.origin.y -= change;
2444            [fWindow setFrame: frame display: NO animate: NO];
2445        }
2446    }
2447
2448    //set views to not autoresize
2449    unsigned int filterMask = [fFilterBar autoresizingMask];
2450    unsigned int scrollMask = [fScrollView autoresizingMask];
2451    [fFilterBar setAutoresizingMask: 0];
2452    [fScrollView setAutoresizingMask: 0];
2453   
2454    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2455    [fWindow setFrame: frame display: YES animate: animate];
2456   
2457    //re-enable autoresize
2458    [fFilterBar setAutoresizingMask: filterMask];
2459    [fScrollView setAutoresizingMask: scrollMask];
2460   
2461    //change min size
2462    NSSize minSize = [fWindow contentMinSize];
2463    minSize.height += heightChange;
2464    [fWindow setContentMinSize: minSize];
2465   
2466    if (!show)
2467    {
2468        [fFilterBar setHidden: YES];
2469        [fWindow makeFirstResponder: fTableView];
2470    }
2471}
2472
2473- (void) toggleAdvancedBar: (id) sender
2474{
2475    [fTableView display];
2476}
2477
2478- (void) doNothing: (id) sender {}
2479
2480- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
2481    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2482{
2483    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
2484
2485    if ([ident isEqualToString: TOOLBAR_CREATE])
2486    {
2487        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
2488        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
2489        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
2490        [item setImage: [NSImage imageNamed: @"Create.png"]];
2491        [item setTarget: self];
2492        [item setAction: @selector(createFile:)];
2493        [item setAutovalidates: NO];
2494    }
2495    else if ([ident isEqualToString: TOOLBAR_OPEN])
2496    {
2497        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
2498        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
2499        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
2500        [item setImage: [NSImage imageNamed: @"Open.png"]];
2501        [item setTarget: self];
2502        [item setAction: @selector(openShowSheet:)];
2503        [item setAutovalidates: NO];
2504    }
2505    else if ([ident isEqualToString: TOOLBAR_REMOVE])
2506    {
2507        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
2508        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
2509        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
2510        [item setImage: [NSImage imageNamed: @"Remove.png"]];
2511        [item setTarget: self];
2512        [item setAction: @selector(removeNoDelete:)];
2513    }
2514    else if ([ident isEqualToString: TOOLBAR_INFO])
2515    {
2516        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
2517        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
2518        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
2519        [item setImage: [NSImage imageNamed: @"Info.png"]];
2520        [item setTarget: self];
2521        [item setAction: @selector(showInfo:)];
2522        [item setAutovalidates: NO];
2523    }
2524    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2525    {
2526        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
2527        [item setPaletteLabel: [item label]];
2528        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
2529        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
2530        [item setTarget: self];
2531        [item setAction: @selector(stopAllTorrents:)];
2532    }
2533    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2534    {
2535        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
2536        [item setPaletteLabel: [item label]];
2537        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
2538        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
2539        [item setTarget: self];
2540        [item setAction: @selector(resumeAllTorrents:)];
2541    }
2542    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2543    {
2544        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
2545        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
2546        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
2547        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
2548        [item setTarget: self];
2549        [item setAction: @selector(stopSelectedTorrents:)];
2550    }
2551    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2552    {
2553        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
2554        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
2555        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
2556        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
2557        [item setTarget: self];
2558        [item setAction: @selector(resumeSelectedTorrents:)];
2559    }
2560    else if ([ident isEqualToString: TOOLBAR_FILTER])
2561    {
2562        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
2563        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
2564        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
2565        [item setImage: [NSImage imageNamed: @"Filter.png"]];
2566        [item setTarget: self];
2567        [item setAction: @selector(toggleFilterBar:)];
2568        [item setAutovalidates: NO];
2569    }
2570    else
2571    {
2572        [item release];
2573        return nil;
2574    }
2575
2576    return item;
2577}
2578
2579- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
2580{
2581    return [NSArray arrayWithObjects:
2582            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2583            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
2584            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
2585            NSToolbarSeparatorItemIdentifier,
2586            NSToolbarSpaceItemIdentifier,
2587            NSToolbarFlexibleSpaceItemIdentifier,
2588            NSToolbarCustomizeToolbarItemIdentifier, nil];
2589}
2590
2591- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
2592{
2593    return [NSArray arrayWithObjects:
2594            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2595            NSToolbarSeparatorItemIdentifier,
2596            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2597            NSToolbarFlexibleSpaceItemIdentifier,
2598            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2599}
2600
2601- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2602{
2603    NSString * ident = [toolbarItem itemIdentifier];
2604
2605    //enable remove item
2606    if ([ident isEqualToString: TOOLBAR_REMOVE])
2607        return [fTableView numberOfSelectedRows] > 0;
2608
2609    //enable pause all item
2610    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2611    {
2612        Torrent * torrent;
2613        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2614        while ((torrent = [enumerator nextObject]))
2615            if ([torrent isActive] || [torrent waitingToStart])
2616                return YES;
2617        return NO;
2618    }
2619
2620    //enable resume all item
2621    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2622    {
2623        Torrent * torrent;
2624        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2625        while ((torrent = [enumerator nextObject]))
2626            if ([torrent isPaused] && ![torrent waitingToStart])
2627                return YES;
2628        return NO;
2629    }
2630
2631    //enable pause item
2632    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2633    {
2634        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2635        Torrent * torrent;
2636        while ((torrent = [enumerator nextObject]))
2637        {
2638            if ([torrent isActive] || [torrent waitingToStart])
2639                return YES;
2640        }
2641        return NO;
2642    }
2643   
2644    //enable resume item
2645    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2646    {
2647        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2648        Torrent * torrent;
2649        while ((torrent = [enumerator nextObject]))
2650        {
2651            if ([torrent isPaused] && ![torrent waitingToStart])
2652                return YES;
2653        }
2654        return NO;
2655    }
2656
2657    return YES;
2658}
2659
2660- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2661{
2662    SEL action = [menuItem action];
2663
2664    //only enable some items if it is in a context menu or the window is useable
2665    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
2666
2667    //enable open items
2668    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
2669        return [fWindow attachedSheet] == nil;
2670   
2671    //enable sort and advanced bar items
2672    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2673        return [fWindow isVisible];
2674
2675    //enable show info
2676    if (action == @selector(showInfo:))
2677    {
2678        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector",
2679                            "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2680        if (![[menuItem title] isEqualToString: title])
2681                [menuItem setTitle: title];
2682
2683        return YES;
2684    }
2685   
2686    //enable prev/next inspector tab
2687    if (action == @selector(setInfoTab:))
2688        return [[fInfoController window] isVisible];
2689   
2690    //enable toggle status bar
2691    if (action == @selector(toggleStatusBar:))
2692    {
2693        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2694                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2695        if (![[menuItem title] isEqualToString: title])
2696            [menuItem setTitle: title];
2697
2698        return [fWindow isVisible];
2699    }
2700   
2701    //enable toggle filter bar
2702    if (action == @selector(toggleFilterBar:))
2703    {
2704        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2705                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2706        if (![[menuItem title] isEqualToString: title])
2707            [menuItem setTitle: title];
2708
2709        return [fWindow isVisible];
2710    }
2711   
2712    //enable prev/next filter button
2713    if (action == @selector(switchFilter:))
2714        return [fWindow isVisible] && ![fFilterBar isHidden];
2715
2716    //enable reveal in finder
2717    if (action == @selector(revealFile:))
2718        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2719
2720    //enable remove items
2721    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2722        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2723    {
2724        BOOL warning = NO,
2725            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2726            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2727       
2728        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2729        Torrent * torrent;
2730        while ((torrent = [enumerator nextObject]))
2731        {
2732            if (!warning && [torrent isActive])
2733            {
2734                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2735                if (warning && canDelete)
2736                    break;
2737            }
2738            if (!canDelete && [torrent publicTorrent])
2739            {
2740                canDelete = YES;
2741                if (warning)
2742                    break;
2743            }
2744        }
2745   
2746        //append or remove ellipsis when needed
2747        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2748        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2749        {
2750            if (![title hasSuffix: ellipsis])
2751                [menuItem setTitle: [title stringByAppendingEllipsis]];
2752        }
2753        else
2754        {
2755            if ([title hasSuffix: ellipsis])
2756                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2757        }
2758       
2759        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2760    }
2761
2762    //enable pause all item
2763    if (action == @selector(stopAllTorrents:))
2764    {
2765        Torrent * torrent;
2766        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2767        while ((torrent = [enumerator nextObject]))
2768            if ([torrent isActive] || [torrent waitingToStart])
2769                return YES;
2770        return NO;
2771    }
2772   
2773    //enable resume all item
2774    if (action == @selector(resumeAllTorrents:))
2775    {
2776        Torrent * torrent;
2777        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2778        while ((torrent = [enumerator nextObject]))
2779            if ([torrent isPaused] && ![torrent waitingToStart])
2780                return YES;
2781        return NO;
2782    }
2783   
2784    //enable resume all waiting item
2785    if (action == @selector(resumeWaitingTorrents:))
2786    {
2787        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2788            return NO;
2789   
2790        Torrent * torrent;
2791        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2792        while ((torrent = [enumerator nextObject]))
2793            if ([torrent isPaused] && [torrent waitingToStart])
2794                return YES;
2795        return NO;
2796    }
2797   
2798    //enable resume selected waiting item
2799    if (action == @selector(resumeSelectedTorrentsNoWait:))
2800    {
2801        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2802            return NO;
2803   
2804        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2805        Torrent * torrent;
2806        while ((torrent = [enumerator nextObject]))
2807            if ([torrent isPaused])
2808                return YES;
2809        return NO;
2810    }
2811
2812    //enable pause item
2813    if (action == @selector(stopSelectedTorrents:))
2814    {
2815        if (!canUseTable)
2816            return NO;
2817   
2818        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2819        Torrent * torrent;
2820        while ((torrent = [enumerator nextObject]))
2821            if ([torrent isActive] || [torrent waitingToStart])
2822                return YES;
2823        return NO;
2824    }
2825   
2826    //enable resume item
2827    if (action == @selector(resumeSelectedTorrents:))
2828    {
2829        if (!canUseTable)
2830            return NO;
2831   
2832        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2833        Torrent * torrent;
2834        while ((torrent = [enumerator nextObject]))
2835            if ([torrent isPaused] && ![torrent waitingToStart])
2836                return YES;
2837        return NO;
2838    }
2839   
2840    //enable announce item
2841    if (action == @selector(announceSelectedTorrents:))
2842    {
2843        if (!canUseTable)
2844            return NO;
2845       
2846        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2847        Torrent * torrent;
2848        NSDate * date;
2849        while ((torrent = [enumerator nextObject]))
2850        {
2851            //time interval returned will be negative
2852            if ([torrent isActive] &&
2853                    (!(date = [torrent announceDate]) || [date timeIntervalSinceNow] <= ANNOUNCE_WAIT_INTERVAL_SECONDS))
2854                return YES;
2855        }
2856        return NO;
2857    }
2858   
2859    //enable reset cache item
2860    if (action == @selector(resetCacheForSelectedTorrents:))
2861    {
2862        if (!canUseTable)
2863            return NO;
2864       
2865        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2866        Torrent * torrent;
2867        while ((torrent = [enumerator nextObject]))
2868        {
2869            if (![torrent isActive])
2870                return YES;
2871        }
2872        return NO;
2873    }
2874   
2875    //enable move torrent file item
2876    if (action == @selector(moveDataFiles:))
2877        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2878   
2879    //enable copy torrent file item
2880    if (action == @selector(copyTorrentFiles:))
2881        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2882   
2883    //enable reverse sort item
2884    if (action == @selector(setSortReverse:))
2885        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: @"Order"];
2886
2887    return YES;
2888}
2889
2890- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2891{
2892    NSEnumerator * enumerator;
2893    Torrent * torrent;
2894    BOOL active;
2895
2896    switch (messageType)
2897    {
2898        case kIOMessageSystemWillSleep:
2899            //close all connections before going to sleep and remember we should resume when we wake up
2900            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2901
2902            //wait for running transfers to stop (5 second timeout)
2903            NSDate * start = [NSDate date];
2904            BOOL timeUp = NO;
2905           
2906            enumerator = [fTorrents objectEnumerator];
2907            while (!timeUp && (torrent = [enumerator nextObject]))
2908                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2909                {
2910                    usleep(100000);
2911                    [torrent update];
2912                }
2913
2914            IOAllowPowerChange(fRootPort, (long) messageArgument);
2915            break;
2916
2917        case kIOMessageCanSystemSleep:
2918            //pevent idle sleep unless all paused
2919            active = NO;
2920            enumerator = [fTorrents objectEnumerator];
2921            while ((torrent = [enumerator nextObject]))
2922                if ([torrent isActive])
2923                {
2924                    active = YES;
2925                    break;
2926                }
2927
2928            if (active)
2929                IOCancelPowerChange(fRootPort, (long) messageArgument);
2930            else
2931                IOAllowPowerChange(fRootPort, (long) messageArgument);
2932            break;
2933
2934        case kIOMessageSystemHasPoweredOn:
2935            //resume sleeping transfers after we wake up
2936            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2937            [self autoSpeedLimitChange: nil];
2938            break;
2939    }
2940}
2941
2942- (NSMenu *) applicationDockMenu: (NSApplication *) sender
2943{
2944    int seeding = 0, downloading = 0;
2945    NSEnumerator * enumerator = [fTorrents objectEnumerator];
2946    Torrent * torrent;
2947    while ((torrent = [enumerator nextObject]))
2948    {
2949        if ([torrent isSeeding])
2950            seeding++;
2951        else if ([torrent isActive])
2952            downloading++;
2953        else;
2954    }
2955   
2956    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
2957            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
2958   
2959    BOOL hasSeparator = seedingItem || downloadingItem;
2960   
2961    if (seeding > 0)
2962    {
2963        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding",
2964                                                        "Dock item - Seeding"), seeding];
2965        if (!seedingItem)
2966        {
2967            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
2968            [seedingItem setTag: DOCK_SEEDING_TAG];
2969            [fDockMenu insertItem: seedingItem atIndex: 0];
2970        }
2971        else
2972            [seedingItem setTitle: title];
2973    }
2974    else
2975    {
2976        if (seedingItem)
2977            [fDockMenu removeItem: seedingItem];
2978    }
2979   
2980    if (downloading > 0)
2981    {
2982        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading",
2983                                                        "Dock item - Downloading"), downloading];
2984        if (!downloadingItem)
2985        {
2986            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
2987            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
2988            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
2989        }
2990        else
2991            [downloadingItem setTitle: title];
2992    }
2993    else
2994    {
2995        if (downloadingItem)
2996            [fDockMenu removeItem: downloadingItem];
2997    }
2998   
2999    if (seeding > 0 || downloading > 0)
3000    {
3001        if (!hasSeparator)
3002            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3003    }
3004    else
3005    {
3006        if (hasSeparator)
3007            [fDockMenu removeItemAtIndex: 0];
3008    }
3009   
3010    return fDockMenu;
3011}
3012
3013- (void) updateDockBadge: (NSNotification *) notification
3014{
3015    [fBadger updateBadge];
3016}
3017
3018- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3019{
3020    //if auto size is enabled, the current frame shouldn't need to change
3021    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3022   
3023    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3024    return frame;
3025}
3026
3027- (void) setWindowSizeToFit
3028{
3029    if ([fDefaults boolForKey: @"AutoSize"])
3030    {
3031        [fScrollView setHasVerticalScroller: NO];
3032        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3033        [fScrollView setHasVerticalScroller: YES];
3034    }
3035}
3036
3037- (NSRect) sizedWindowFrame
3038{
3039    float heightChange = [fDisplayedTorrents count] * ([fTableView rowHeight] +
3040            [fTableView intercellSpacing].height) - [fScrollView frame].size.height;
3041    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3042}
3043
3044- (void) showMainWindow: (id) sender
3045{
3046    [fWindow makeKeyAndOrderFront: nil];
3047}
3048
3049- (void) windowDidBecomeKey: (NSNotification *) notification
3050{
3051    [fBadger clearCompleted];
3052}
3053
3054- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3055{
3056    //only resize horizontally if autosize is enabled
3057    if ([fDefaults boolForKey: @"AutoSize"])
3058        proposedFrameSize.height = [fWindow frame].size.height;
3059    return proposedFrameSize;
3060}
3061
3062- (void) windowDidResize: (NSNotification *) notification
3063{
3064    //size search filter to not overlap buttons
3065    float pointX = NSMaxX([fPauseFilterButton frame]) + 5.0;
3066    NSRect oldFrame = [fSearchFilterField frame],
3067            frame = NSMakeRect(pointX, oldFrame.origin.y, NSMaxX(oldFrame) - pointX, oldFrame.size.height);
3068   
3069    BOOL show;
3070    if (show = (frame.size.width >= SEARCH_FILTER_MIN_WIDTH))
3071    {
3072        //make sure it is not too long
3073        if (frame.size.width > SEARCH_FILTER_MAX_WIDTH)
3074        {
3075            float different = frame.size.width - SEARCH_FILTER_MAX_WIDTH;
3076            frame.origin.x += different;
3077            frame.size.width -= different;
3078        }
3079        [fSearchFilterField setFrame: frame];
3080    }
3081   
3082    //hide search filter if it overlaps filter buttons
3083    [fSearchFilterField setHidden: !show];
3084}
3085
3086- (void) linkHomepage: (id) sender
3087{
3088    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
3089}
3090
3091- (void) linkForums: (id) sender
3092{
3093    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
3094}
3095
3096- (void) prepareForUpdate: (NSNotification *) notification
3097{
3098    fUpdateInProgress = YES;
3099}
3100
3101- (NSDictionary *) registrationDictionaryForGrowl
3102{
3103    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
3104                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
3105    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
3106                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
3107}
3108
3109- (void) growlNotificationWasClicked: (id) clickContext
3110{
3111    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
3112        return;
3113   
3114    NSString * type = [clickContext objectForKey: @"Type"], * location;
3115    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
3116            && (location = [clickContext objectForKey: @"Location"]))
3117        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
3118}
3119
3120#warning move to additions
3121- (NSString *) applicationSupportFolder
3122{
3123    return [[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex: 0]
3124                stringByAppendingPathComponent: [[NSProcessInfo processInfo] processName]];
3125}
3126
3127- (void) ipcQuit
3128{
3129    fRemoteQuit = YES;
3130    [NSApp terminate: self];
3131}
3132
3133- (NSArray *) ipcGetTorrentsByID: (NSArray *) idlist
3134{
3135    if (!idlist)
3136        return fTorrents;
3137   
3138    NSMutableArray * torrents = [NSMutableArray array];
3139   
3140    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * idEnum;
3141    int torId;
3142    Torrent * torrent;
3143    NSNumber * tempId;
3144    while ((torrent = [torrentEnum nextObject]))
3145    {
3146        torId = [torrent torrentID];
3147       
3148        idEnum = [idlist objectEnumerator];
3149        while ((tempId = [idEnum nextObject]))
3150        {
3151            if ([tempId intValue] == torId)
3152            {
3153                [torrents addObject: torrent];
3154                break;
3155            }
3156        }
3157    }
3158
3159    return torrents;
3160}
3161
3162- (NSArray *) ipcGetTorrentsByHash: (NSArray *) hashlist
3163{
3164    if (!hashlist)
3165        return fTorrents;
3166   
3167    NSMutableArray * torrents = [NSMutableArray array];
3168   
3169    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * hashEnum;
3170    NSString * torHash, * tempHash;
3171    Torrent * torrent;
3172    while ((torrent = [torrentEnum nextObject]))
3173    {
3174        torHash = [torrent hashString];
3175       
3176        hashEnum = [hashlist objectEnumerator];
3177        while ((tempHash = [hashEnum nextObject]))
3178        {
3179            if ([torHash caseInsensitiveCompare: tempHash] == NSOrderedSame)
3180            {
3181                [torrents addObject: torrent];
3182                break;
3183            }
3184        }
3185    }
3186   
3187    return torrents;
3188}
3189
3190- (BOOL) ipcAddTorrents: (NSArray *) torrents
3191{
3192    /* 'torrents' is NSArray of NSString torrent file paths, should
3193       return NO if torrent fails to load */
3194    return NO;
3195}
3196
3197- (BOOL) ipcAddTorrentFile: (NSString *) path
3198                 directory: (NSString *) dir
3199{
3200    /* 'path' is path to torrent file, 'dir' is the directory it
3201       should download it's files to and may be nil, should return NO
3202       if torrent fails to load */
3203    return NO;
3204}
3205
3206- (BOOL) ipcAddTorrentFileAutostart: (NSString *) path
3207                          directory: (NSString *) dir
3208                          autostart: (BOOL) autostart
3209{
3210    /* 'path' is path to torrent file, 'dir' is the directory it
3211       should download it's files to and may be nil, 'autostart' is a
3212       boolean indicating if the torrent should be automatically
3213       started (or queued to start, I guess), should return NO if
3214       torrent fails to load */
3215    return NO;
3216}
3217
3218- (BOOL) ipcAddTorrentData: (NSData *) data
3219                 directory: (NSString *) dir
3220{
3221    /* 'data' is the contents of a torrent file, 'dir' is the
3222       directory it should download it's files to and may be nil,
3223       should return NO if torrent fails to load */
3224    return NO;
3225}
3226
3227- (BOOL) ipcAddTorrentDataAutostart: (NSData *) path
3228                          directory: (NSString *) dir
3229                          autostart: (BOOL) autostart
3230{
3231    /* 'data' is the contents of a torrent file, 'dir' is the
3232       directory it should download it's files to and may be nil,
3233       'autostart' is a boolean indicating if the torrent should be
3234       automatically started (or queued to start, I guess), should
3235       return NO if torrent fails to load */
3236    return NO;
3237}
3238
3239- (BOOL) ipcStartTorrents: (NSArray *) torrents
3240{
3241    if (!torrents)
3242        [self resumeAllTorrents: self];
3243    else
3244        [self resumeTorrents: torrents];
3245
3246    return YES;
3247}
3248
3249- (BOOL) ipcStopTorrents: (NSArray *) torrents
3250{
3251    if (!torrents)
3252        [self stopAllTorrents: self];
3253    else
3254        [self stopTorrents: torrents];
3255
3256    return YES;
3257}
3258
3259- (BOOL) ipcRemoveTorrents: (NSArray *) torrents
3260{
3261    if (!torrents)
3262        torrents = [NSArray arrayWithArray: fTorrents];
3263
3264    [self confirmRemoveTorrents: torrents deleteData: NO deleteTorrent: NO];
3265
3266    return YES;
3267}
3268
3269@end
Note: See TracBrowser for help on using the repository browser.