source: trunk/macosx/Controller.m @ 1329

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

a little more queueing cleanup

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