source: trunk/macosx/Controller.m @ 1579

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

Merge PEX branch, I hope this works.

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