source: trunk/macosx/Controller.m @ 2168

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

if a torrent switches from seeding to downloading still apply this to the queue

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