source: trunk/macosx/Controller.m @ 2238

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

show a warning when trying to open a duplicate torrent

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