source: trunk/macosx/Controller.m @ 2209

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

commit my current work...still doesn't compile (calls some non-existent functions :))

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