source: trunk/macosx/Controller.m @ 2249

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

if a transfer is checking decrease the queue count for both queues but don't start the transfer

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