source: trunk/macosx/Controller.m @ 1576

Last change on this file since 1576 was 1576, checked in by joshe, 15 years ago

Optionally return the info hash after attempting to load a duplicate torrent.

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