source: trunk/macosx/Controller.m @ 2225

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

hopefully fix a nasty memory leak and a bunch of redundant code

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