source: trunk/macosx/Controller.m @ 2226

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

remove some nslogs

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