source: trunk/macosx/Controller.m @ 2188

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