source: trunk/macosx/Controller.m @ 1257

Last change on this file since 1257 was 1257, checked in by livings124, 16 years ago

dragging a url now hilights the whole table

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