source: trunk/macosx/Controller.m @ 1577

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

update progress bar when seeding immediately when the stop ratio setting is changed

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