source: trunk/macosx/Controller.m @ 2167

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

store the values of the tracker address, private check, and open check

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