source: trunk/macosx/Controller.m @ 2239

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

add an option in the duplicate alert to not prompt again

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