source: trunk/macosx/Controller.m @ 1336

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

less reliance on title

  • Property svn:keywords set to Date Rev Author Id
File size: 94.8 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 1336 2007-01-09 17:09:21Z 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    //determine the number of downloads needed to start
1144    int desiredDownloadActive = download ? [fDefaults integerForKey: @"QueueDownloadNumber"] : 0,
1145        desiredSeedActive = seed ? [fDefaults integerForKey: @"QueueSeedNumber"] : 0;
1146   
1147    Torrent * torrent;
1148    NSEnumerator * enumerator;
1149    if (download || seed)
1150    {
1151        enumerator = [fTorrents objectEnumerator];
1152        while ((torrent = [enumerator nextObject]))
1153            if ([torrent isActive] && ![torrent isError])
1154            {
1155                if ([torrent progress] < 1.0)
1156                    desiredDownloadActive--;
1157                else
1158                    desiredSeedActive--;
1159               
1160                if (desiredDownloadActive <= 0 && desiredSeedActive <= 0)
1161                    break;
1162            }
1163    }
1164   
1165    //sort torrents by order value
1166    NSArray * sortedTorrents;
1167    if ([fTorrents count] > 1 && (desiredDownloadActive > 0 || desiredSeedActive > 0))
1168    {
1169        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1170                                                @"orderValue" ascending: YES] autorelease];
1171        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1172       
1173        sortedTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
1174        [descriptors release];
1175    }
1176    else
1177        sortedTorrents = fTorrents;
1178
1179    enumerator = [sortedTorrents objectEnumerator];
1180    while ((torrent = [enumerator nextObject]))
1181    {
1182        if (![torrent isActive] && [torrent waitingToStart])
1183        {
1184            if ([torrent progress] < 1.0)
1185            {
1186                if (!download || desiredDownloadActive > 0)
1187                {
1188                    [torrent startTransfer];
1189                    if ([torrent isActive])
1190                        desiredDownloadActive--;
1191                    [torrent update];
1192                }
1193            }
1194            else
1195            {
1196                if (!seed || desiredSeedActive > 0)
1197                {
1198                    [torrent startTransfer];
1199                    if ([torrent isActive])
1200                        desiredSeedActive--;
1201                    [torrent update];
1202                }
1203            }
1204        }
1205    }
1206   
1207    [self updateUI: nil];
1208    [self applyFilter: nil];
1209    [self updateTorrentHistory];
1210}
1211
1212- (void) torrentFinishedDownloading: (NSNotification *) notification
1213{
1214    Torrent * torrent = [notification object];
1215   
1216    [fInfoController updateInfoStats];
1217   
1218    if ([fDefaults boolForKey: @"PlayDownloadSound"])
1219    {
1220        NSSound * sound;
1221        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1222            [sound play];
1223    }
1224   
1225    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1226        description: [torrent name]
1227        notificationName: GROWL_DOWNLOAD_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1228   
1229    if (![fWindow isKeyWindow])
1230        fCompleted++;
1231   
1232    //update queue if there is a seeding queue
1233    if ([fDefaults boolForKey: @"QueueSeed"])
1234    {
1235        int desiredSeedActive = [fDefaults integerForKey: @"QueueSeedNumber"];
1236           
1237        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1238        Torrent * otherTorrent;
1239        while ((otherTorrent = [enumerator nextObject]))
1240            if (otherTorrent != torrent && [otherTorrent isSeeding] && ![otherTorrent isError])
1241            {
1242                desiredSeedActive--;
1243                if (desiredSeedActive <= 0)
1244                    break;
1245            }
1246
1247        if (desiredSeedActive <= 0)
1248        {
1249            [torrent stopTransfer];
1250            [torrent setWaitToStart: YES];
1251        }
1252    }
1253   
1254    [self updateUI: nil];
1255    [self applyFilter: nil];
1256    [self updateTorrentHistory];
1257}
1258
1259- (void) updateTorrentHistory
1260{
1261    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1262
1263    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1264    Torrent * torrent;
1265    while ((torrent = [enumerator nextObject]))
1266        [history addObject: [torrent history]];
1267
1268    [fDefaults setObject: history forKey: @"History"];
1269    [fDefaults synchronize];
1270}
1271
1272- (void) sortTorrents
1273{
1274    //remember selected rows if needed
1275    NSArray * selectedTorrents = nil;
1276    int numSelected = [fTableView numberOfSelectedRows];
1277    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1278        selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1279
1280    [self sortTorrentsIgnoreSelected]; //actually sort
1281   
1282    //set selected rows if needed
1283    if (selectedTorrents)
1284    {
1285        Torrent * torrent;
1286        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1287        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1288        while ((torrent = [enumerator nextObject]))
1289            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1290       
1291        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1292        [indexSet release];
1293    }
1294}
1295
1296//doesn't remember selected rows
1297- (void) sortTorrentsIgnoreSelected
1298{
1299    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1300                            ascending: YES selector: @selector(caseInsensitiveCompare:)] autorelease],
1301                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1302                                            ascending: YES] autorelease];
1303
1304    NSArray * descriptors;
1305    if ([fSortType isEqualToString: @"Name"])
1306        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1307    else if ([fSortType isEqualToString: @"State"])
1308    {
1309        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1310                                                @"stateSortKey" ascending: NO] autorelease],
1311                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1312                                            @"progressSortKey" ascending: NO] autorelease];
1313       
1314        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
1315                                                            nameDescriptor, orderDescriptor, nil];
1316    }
1317    else if ([fSortType isEqualToString: @"Progress"])
1318    {
1319        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1320                                            @"progressSortKey" ascending: YES] autorelease];
1321       
1322        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
1323    }
1324    else if ([fSortType isEqualToString: @"Date"])
1325    {
1326        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"date" ascending: YES] autorelease];
1327   
1328        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1329    }
1330    else
1331        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1332
1333    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1334    [descriptors release];
1335   
1336    [fTableView reloadData];
1337}
1338
1339- (void) setSort: (id) sender
1340{
1341    //get checked items
1342    NSMenuItem * prevSortItem, * prevSortActionItem;
1343    if ([fSortType isEqualToString: @"Name"])
1344    {
1345        prevSortItem = fNameSortItem;
1346        prevSortActionItem = fNameSortActionItem;
1347    }
1348    else if ([fSortType isEqualToString: @"State"])
1349    {
1350        prevSortItem = fStateSortItem;
1351        prevSortActionItem = fStateSortActionItem;
1352    }
1353    else if ([fSortType isEqualToString: @"Progress"])
1354    {
1355        prevSortItem = fProgressSortItem;
1356        prevSortActionItem = fProgressSortActionItem;
1357    }
1358    else if ([fSortType isEqualToString: @"Date"])
1359    {
1360        prevSortItem = fDateSortItem;
1361        prevSortActionItem = fDateSortActionItem;
1362    }
1363    else
1364    {
1365        prevSortItem = fOrderSortItem;
1366        prevSortActionItem = fOrderSortActionItem;
1367    }
1368   
1369    if (sender != prevSortItem && sender != prevSortActionItem)
1370    {
1371        [fSortType release];
1372       
1373        //get new items to check
1374        NSMenuItem * currentSortItem, * currentSortActionItem;
1375        if (sender == fNameSortItem || sender == fNameSortActionItem)
1376        {
1377            currentSortItem = fNameSortItem;
1378            currentSortActionItem = fNameSortActionItem;
1379            fSortType = [[NSString alloc] initWithString: @"Name"];
1380        }
1381        else if (sender == fStateSortItem || sender == fStateSortActionItem)
1382        {
1383            currentSortItem = fStateSortItem;
1384            currentSortActionItem = fStateSortActionItem;
1385            fSortType = [[NSString alloc] initWithString: @"State"];
1386        }
1387        else if (sender == fProgressSortItem || sender == fProgressSortActionItem)
1388        {
1389            currentSortItem = fProgressSortItem;
1390            currentSortActionItem = fProgressSortActionItem;
1391            fSortType = [[NSString alloc] initWithString: @"Progress"];
1392        }
1393        else if (sender == fDateSortItem || sender == fDateSortActionItem)
1394        {
1395            currentSortItem = fDateSortItem;
1396            currentSortActionItem = fDateSortActionItem;
1397            fSortType = [[NSString alloc] initWithString: @"Date"];
1398        }
1399        else
1400        {
1401            currentSortItem = fOrderSortItem;
1402            currentSortActionItem = fOrderSortActionItem;
1403            fSortType = [[NSString alloc] initWithString: @"Order"];
1404        }
1405   
1406        [prevSortItem setState: NSOffState];
1407        [prevSortActionItem setState: NSOffState];
1408        [currentSortItem setState: NSOnState];
1409        [currentSortActionItem setState: NSOnState];
1410       
1411        [fDefaults setObject: fSortType forKey: @"Sort"];
1412    }
1413
1414    [self sortTorrents];
1415}
1416
1417- (void) applyFilter: (id) sender
1418{
1419    //remember selected rows if needed
1420    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1421                ? [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1422
1423    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1424
1425    BOOL filtering = YES;
1426    if ([fFilterType isEqualToString: @"Pause"])
1427    {
1428        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1429        Torrent * torrent;
1430        while ((torrent = [enumerator nextObject]))
1431            if (![torrent isActive])
1432                [tempTorrents addObject: torrent];
1433    }
1434    else if ([fFilterType isEqualToString: @"Seed"])
1435    {
1436        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1437        Torrent * torrent;
1438        while ((torrent = [enumerator nextObject]))
1439            if ([torrent isActive] && [torrent progress] >= 1.0)
1440                [tempTorrents addObject: torrent];
1441    }
1442    else if ([fFilterType isEqualToString: @"Download"])
1443    {
1444        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1445        Torrent * torrent;
1446        while ((torrent = [enumerator nextObject]))
1447            if ([torrent isActive] && [torrent progress] < 1.0)
1448                [tempTorrents addObject: torrent];
1449    }
1450    else
1451    {
1452        filtering = NO;
1453        [tempTorrents setArray: fTorrents];
1454    }
1455   
1456    NSString * searchString = [fSearchFilterField stringValue];
1457    if ([searchString length] > 0)
1458    {
1459        filtering = YES;
1460       
1461        int i;
1462        for (i = [tempTorrents count] - 1; i >= 0; i--)
1463            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1464                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1465                [tempTorrents removeObjectAtIndex: i];
1466    }
1467   
1468    [fDisplayedTorrents setArray: tempTorrents];
1469    [tempTorrents release];
1470   
1471    [self sortTorrentsIgnoreSelected];
1472   
1473    //set selected rows if needed
1474    if (selectedTorrents)
1475    {
1476        Torrent * torrent;
1477        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1478        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1479        unsigned index;
1480        while ((torrent = [enumerator nextObject]))
1481            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1482                [indexSet addIndex: index];
1483       
1484        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1485        [indexSet release];
1486    }
1487   
1488    //set status bar torrent count text
1489    NSMutableString * totalTorrentsString = [NSMutableString stringWithString: @""];
1490    if (filtering)
1491        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1492   
1493    int totalCount = [fTorrents count];
1494    if (totalCount != 1)
1495        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfers", "Status bar transfer count"), totalCount];
1496    else
1497        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfer", "Status bar transfer count"), totalCount];
1498   
1499    [fTotalTorrentsField setStringValue: totalTorrentsString];
1500
1501    [self setWindowSizeToFit];
1502}
1503
1504//resets filter and sorts torrents
1505- (void) setFilter: (id) sender
1506{
1507    BarButton * prevFilterButton;
1508    if ([fFilterType isEqualToString: @"Pause"])
1509        prevFilterButton = fPauseFilterButton;
1510    else if ([fFilterType isEqualToString: @"Seed"])
1511        prevFilterButton = fSeedFilterButton;
1512    else if ([fFilterType isEqualToString: @"Download"])
1513        prevFilterButton = fDownloadFilterButton;
1514    else
1515        prevFilterButton = fNoFilterButton;
1516   
1517    if (sender != prevFilterButton)
1518    {
1519        [prevFilterButton setEnabled: NO];
1520        [sender setEnabled: YES];
1521
1522        [fFilterType release];
1523        if (sender == fDownloadFilterButton)
1524            fFilterType = [[NSString alloc] initWithString: @"Download"];
1525        else if (sender == fPauseFilterButton)
1526            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1527        else if (sender == fSeedFilterButton)
1528            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1529        else
1530            fFilterType = [[NSString alloc] initWithString: @"None"];
1531
1532        [fDefaults setObject: fFilterType forKey: @"Filter"];
1533    }
1534
1535    [self applyFilter: nil];
1536}
1537
1538- (void) switchFilter: (id) sender
1539{
1540    NSButton * button;
1541    if ([fFilterType isEqualToString: @"None"])
1542        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1543    else if ([fFilterType isEqualToString: @"Download"])
1544        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1545    else if ([fFilterType isEqualToString: @"Seed"])
1546        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1547    else if ([fFilterType isEqualToString: @"Pause"])
1548        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1549    else
1550        button = fNoFilterButton;
1551   
1552    [self setFilter: button];
1553}
1554
1555- (void) updateControlTint: (NSNotification *) notification
1556{
1557    if ([fDefaults boolForKey: @"SpeedLimit"])
1558        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
1559            ? [NSImage imageNamed: @"SpeedLimitButtonBlue.png"] : [NSImage imageNamed: @"SpeedLimitButtonGraphite.png"]];
1560}
1561
1562- (void) applySpeedLimit: (id) sender
1563{
1564    [fPrefsController applySpeedSettings: nil];
1565}
1566
1567- (void) toggleSpeedLimit: (id) sender
1568{
1569    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
1570    [self applySpeedLimit: nil];
1571}
1572
1573- (void) autoSpeedLimitChange: (NSNotification *) notification
1574{
1575    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1576        return;
1577 
1578    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1579                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
1580        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1581                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
1582        * nowDate = [NSCalendarDate calendarDate];
1583   
1584    //check if should be on if within range
1585    BOOL shouldBeOn;
1586   
1587    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
1588        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
1589        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
1590   
1591    if (onTime == offTime)
1592        shouldBeOn = NO;
1593    else if (onTime < offTime)
1594        shouldBeOn = onTime <= nowTime && nowTime < offTime;
1595    else
1596        shouldBeOn = onTime <= nowTime || nowTime < offTime;
1597   
1598    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
1599        [self toggleSpeedLimit: nil];
1600}
1601
1602- (void) autoSpeedLimit: (NSTimer *) timer
1603{
1604    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1605        return;
1606   
1607    //only toggle if within first few seconds of minutes
1608    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
1609    if ([nowDate secondOfMinute] < AUTO_SPEED_LIMIT_SECONDS)
1610        return;
1611   
1612    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1613                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
1614   
1615    BOOL toggle;
1616    if ([fDefaults boolForKey: @"SpeedLimit"])
1617        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
1618    else
1619    {
1620        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1621                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
1622        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
1623                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
1624    }
1625   
1626    if (toggle)
1627    {
1628        [self toggleSpeedLimit: nil];
1629       
1630        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
1631                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
1632                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
1633            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
1634            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1635    }
1636}
1637
1638- (void) setLimitGlobalEnabled: (id) sender
1639{
1640    [fPrefsController applySpeedSettings: nil];
1641}
1642
1643- (void) setQuickLimitGlobal: (id) sender
1644{
1645    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
1646    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
1647   
1648    [fPrefsController updateLimitFields];
1649    [fPrefsController applySpeedSettings: nil];
1650}
1651
1652- (void) setQuickRatioGlobal: (id) sender
1653{
1654    [fDefaults setBool: YES forKey: @"RatioCheck"];
1655    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
1656   
1657    [fPrefsController updateRatioStopField];
1658}
1659
1660- (void) torrentStoppedForRatio: (NSNotification *) notification
1661{
1662    [self updateTorrentsInQueue];
1663    [fInfoController updateInfoStats];
1664   
1665    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1666    {
1667        NSSound * sound;
1668        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1669            [sound play];
1670    }
1671   
1672    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1673        description: [[notification object] name]
1674        notificationName: GROWL_SEEDING_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1675}
1676
1677-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
1678{
1679    if ([notification isEqualToString: UKFileWatcherWriteNotification])
1680        [self checkAutoImportDirectory];
1681}
1682
1683- (void) changeAutoImport
1684{
1685    [fAutoImportedNames removeAllObjects];
1686    [self checkAutoImportDirectory];
1687}
1688
1689- (void) checkAutoImportDirectory
1690{
1691    if (![fDefaults boolForKey: @"AutoImport"])
1692        return;
1693       
1694    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1695   
1696    NSArray * importedNames;
1697    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
1698        return;
1699   
1700    //only import those that have not been imported yet
1701    NSMutableArray * newNames = [importedNames mutableCopy];
1702    [newNames removeObjectsInArray: fAutoImportedNames];
1703    [fAutoImportedNames setArray: importedNames];
1704   
1705    NSString * file;
1706    int i;
1707    for (i = [newNames count] - 1; i >= 0; i--)
1708    {
1709        file = [newNames objectAtIndex: i];
1710        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
1711            [newNames removeObjectAtIndex: i];
1712        else
1713            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
1714    }
1715   
1716    NSEnumerator * enumerator;
1717    if (![[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"])
1718    {
1719        enumerator = [newNames objectEnumerator];
1720        int count;
1721        while ((file = [enumerator nextObject]))
1722        {
1723            count = [fTorrents count];
1724            [self openFiles: [NSArray arrayWithObject: file]];
1725           
1726            //check if torrent was opened
1727            if ([fTorrents count] > count)
1728                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
1729                    "Growl notification title") description: [file lastPathComponent]
1730                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1731        }
1732    }
1733    else
1734        [self openFiles: newNames];
1735   
1736    //create temporary torrents to check if an import fails because of an error
1737    enumerator = [newNames objectEnumerator];
1738    int error;
1739    while ((file = [enumerator nextObject]))
1740    {
1741        tr_torrent_t * tempTor = tr_torrentInit(fLib, [file UTF8String], 0, & error);
1742       
1743        if (tempTor)
1744            tr_torrentClose(fLib, tempTor);
1745        else if (error != TR_EUNSUPPORTED && error != TR_EDUPLICATE)
1746            [fAutoImportedNames removeObjectIdenticalTo: [file lastPathComponent]]; //can try to import later
1747        else;
1748    }
1749   
1750    [newNames release];
1751}
1752
1753- (int) numberOfRowsInTableView: (NSTableView *) tableview
1754{
1755    return [fDisplayedTorrents count];
1756}
1757
1758- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
1759{
1760    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
1761}
1762
1763- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1764    toPasteboard: (NSPasteboard *) pasteboard
1765{
1766    //only allow reordering of rows if sorting by order with no filter
1767    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1768            && [[fSearchFilterField stringValue] length] == 0)
1769    {
1770        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1771        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1772                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1773        return YES;
1774    }
1775    return NO;
1776}
1777
1778- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1779    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1780{
1781    NSPasteboard * pasteboard = [info draggingPasteboard];
1782    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1783    {
1784        //check if any files to add have "torrent" as an extension
1785        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1786        NSString * file;
1787        while ((file = [enumerator nextObject]))
1788            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1789            {
1790                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1791                return NSDragOperationGeneric;
1792            }
1793    }
1794    else if ([[pasteboard types] containsObject: NSURLPboardType])
1795    {
1796        [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1797        return NSDragOperationGeneric;
1798    }
1799    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1800    {
1801        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1802        return NSDragOperationGeneric;
1803    }
1804    else;
1805   
1806    return NSDragOperationNone;
1807}
1808
1809- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1810    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1811{
1812    NSPasteboard * pasteboard = [info draggingPasteboard];
1813    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1814    {
1815        //create an array of files with the "torrent" extension
1816        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1817        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1818        NSString * file;
1819        while ((file = [enumerator nextObject]))
1820            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1821                [filesToOpen addObject: file];
1822   
1823        [self application: NSApp openFiles: filesToOpen];
1824        [filesToOpen release];
1825    }
1826    else if ([[pasteboard types] containsObject: NSURLPboardType])
1827    {
1828        NSURL * url;
1829        if ((url = [NSURL URLFromPasteboard: pasteboard]))
1830            [self openURL: url];
1831    }
1832    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1833    {
1834        //remember selected rows if needed
1835        NSArray * selectedTorrents = nil;
1836        int numSelected = [fTableView numberOfSelectedRows];
1837        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1838            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1839   
1840        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1841                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1842       
1843        //move torrent in array
1844        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
1845        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1846       
1847        //determine the insertion index now that transfers to move have been removed
1848        int i, decrease = 0;
1849        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1850            decrease++;
1851       
1852        //insert objects at new location
1853        for (i = 0; i < [movingTorrents count]; i++)
1854            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1855       
1856        [movingTorrents release];
1857       
1858        //redo order values
1859        int low = [indexes firstIndex], high = [indexes lastIndex];
1860        if (newRow < low)
1861            low = newRow;
1862        else if (newRow > high + 1)
1863            high = newRow - 1;
1864        else;
1865       
1866        for (i = low; i <= high; i++)
1867            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1868       
1869        [fTableView reloadData];
1870       
1871        //set selected rows if needed
1872        if (selectedTorrents)
1873        {
1874            Torrent * torrent;
1875            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1876            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1877            while ((torrent = [enumerator nextObject]))
1878                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1879           
1880            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1881            [indexSet release];
1882        }
1883    }
1884    else;
1885   
1886    return YES;
1887}
1888
1889- (void) tableViewSelectionDidChange: (NSNotification *) notification
1890{
1891    [fInfoController updateInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
1892}
1893
1894- (void) toggleSmallView: (id) sender
1895{
1896    BOOL makeSmall = [fDefaults boolForKey: @"SmallView"];
1897   
1898    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1899   
1900    //window min height
1901    NSSize contentMinSize = [fWindow contentMinSize],
1902            contentSize = [[fWindow contentView] frame].size;
1903    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1904                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1905    [fWindow setContentMinSize: contentMinSize];
1906   
1907    //resize for larger min height if not set to auto size
1908    if (![fDefaults boolForKey: @"AutoSize"])
1909    {
1910        if (!makeSmall && contentSize.height < contentMinSize.height)
1911        {
1912            NSRect frame = [fWindow frame];
1913            float heightChange = contentMinSize.height - contentSize.height;
1914            frame.size.height += heightChange;
1915            frame.origin.y -= heightChange;
1916           
1917            [fWindow setFrame: frame display: YES];
1918            [fTableView reloadData];
1919        }
1920    }
1921    else
1922        [self setWindowSizeToFit];
1923}
1924
1925- (void) toggleStatusBar: (id) sender
1926{
1927    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1928    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1929}
1930
1931- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1932{
1933    if (show != [fStatusBar isHidden])
1934        return;
1935
1936    if (show)
1937        [fStatusBar setHidden: NO];
1938
1939    NSRect frame = [fWindow frame];
1940    float heightChange = [fStatusBar frame].size.height;
1941    if (!show)
1942        heightChange *= -1;
1943   
1944    //allow bar to show even if not enough room
1945    if (show && ![fDefaults boolForKey: @"AutoSize"])
1946    {
1947        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1948        if (frame.size.height > maxHeight)
1949        {
1950            float change = maxHeight - frame.size.height;
1951            frame.size.height += change;
1952            frame.origin.y -= change;
1953           
1954            [fWindow setFrame: frame display: NO animate: NO];
1955        }
1956    }
1957
1958    frame.size.height += heightChange;
1959    frame.origin.y -= heightChange;
1960   
1961    [self updateUI: nil];
1962   
1963    //set views to not autoresize
1964    unsigned int statsMask = [fStatusBar autoresizingMask];
1965    unsigned int filterMask = [fFilterBar autoresizingMask];
1966    unsigned int scrollMask = [fScrollView autoresizingMask];
1967    [fStatusBar setAutoresizingMask: 0];
1968    [fFilterBar setAutoresizingMask: 0];
1969    [fScrollView setAutoresizingMask: 0];
1970   
1971    [fWindow setFrame: frame display: YES animate: animate];
1972   
1973    //re-enable autoresize
1974    [fStatusBar setAutoresizingMask: statsMask];
1975    [fFilterBar setAutoresizingMask: filterMask];
1976    [fScrollView setAutoresizingMask: scrollMask];
1977   
1978    //change min size
1979    NSSize minSize = [fWindow contentMinSize];
1980    minSize.height += heightChange;
1981    [fWindow setContentMinSize: minSize];
1982   
1983    if (!show)
1984        [fStatusBar setHidden: YES];
1985}
1986
1987- (void) toggleFilterBar: (id) sender
1988{
1989    //disable filtering when hiding
1990    if (![fFilterBar isHidden])
1991    {
1992        [fSearchFilterField setStringValue: @""];
1993        [self setFilter: fNoFilterButton];
1994    }
1995
1996    [self showFilterBar: [fFilterBar isHidden] animate: YES];
1997    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
1998}
1999
2000- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2001{
2002    if (show != [fFilterBar isHidden])
2003        return;
2004
2005    if (show)
2006        [fFilterBar setHidden: NO];
2007
2008    NSRect frame = [fWindow frame];
2009    float heightChange = [fFilterBar frame].size.height;
2010    if (!show)
2011        heightChange *= -1;
2012   
2013    //allow bar to show even if not enough room
2014    if (show && ![fDefaults boolForKey: @"AutoSize"])
2015    {
2016        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
2017        if (frame.size.height > maxHeight)
2018        {
2019            float change = maxHeight - frame.size.height;
2020            frame.size.height += change;
2021            frame.origin.y -= change;
2022           
2023            [fWindow setFrame: frame display: NO animate: NO];
2024        }
2025    }
2026
2027    frame.size.height += heightChange;
2028    frame.origin.y -= heightChange;
2029   
2030    //set views to not autoresize
2031    unsigned int filterMask = [fFilterBar autoresizingMask];
2032    unsigned int scrollMask = [fScrollView autoresizingMask];
2033    [fFilterBar setAutoresizingMask: 0];
2034    [fScrollView setAutoresizingMask: 0];
2035   
2036    [fWindow setFrame: frame display: YES animate: animate];
2037   
2038    //re-enable autoresize
2039    [fFilterBar setAutoresizingMask: filterMask];
2040    [fScrollView setAutoresizingMask: scrollMask];
2041   
2042    //change min size
2043    NSSize minSize = [fWindow contentMinSize];
2044    minSize.height += heightChange;
2045    [fWindow setContentMinSize: minSize];
2046   
2047    if (!show)
2048    {
2049        [fFilterBar setHidden: YES];
2050        [fWindow makeFirstResponder: fTableView];
2051    }
2052}
2053
2054- (void) toggleAdvancedBar: (id) sender
2055{
2056    [fTableView display];
2057}
2058
2059- (void) doNothing: (id) sender {}
2060
2061- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
2062    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2063{
2064    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
2065
2066    if ([ident isEqualToString: TOOLBAR_OPEN])
2067    {
2068        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
2069        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
2070        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
2071        [item setImage: [NSImage imageNamed: @"Open.png"]];
2072        [item setTarget: self];
2073        [item setAction: @selector(openShowSheet:)];
2074        [item setAutovalidates: NO];
2075    }
2076    else if ([ident isEqualToString: TOOLBAR_REMOVE])
2077    {
2078        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
2079        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
2080        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
2081        [item setImage: [NSImage imageNamed: @"Remove.png"]];
2082        [item setTarget: self];
2083        [item setAction: @selector(removeNoDelete:)];
2084    }
2085    else if ([ident isEqualToString: TOOLBAR_INFO])
2086    {
2087        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
2088        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
2089        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
2090        [item setImage: [NSImage imageNamed: @"Info.png"]];
2091        [item setTarget: self];
2092        [item setAction: @selector(showInfo:)];
2093        [item setAutovalidates: NO];
2094    }
2095    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2096    {
2097        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
2098        [item setPaletteLabel: [item label]];
2099        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
2100        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
2101        [item setTarget: self];
2102        [item setAction: @selector(stopAllTorrents:)];
2103    }
2104    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2105    {
2106        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
2107        [item setPaletteLabel: [item label]];
2108        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
2109        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
2110        [item setTarget: self];
2111        [item setAction: @selector(resumeAllTorrents:)];
2112    }
2113    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2114    {
2115        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
2116        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
2117        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
2118        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
2119        [item setTarget: self];
2120        [item setAction: @selector(stopSelectedTorrents:)];
2121    }
2122    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2123    {
2124        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
2125        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
2126        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
2127        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
2128        [item setTarget: self];
2129        [item setAction: @selector(resumeSelectedTorrents:)];
2130    }
2131    else if ([ident isEqualToString: TOOLBAR_FILTER])
2132    {
2133        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
2134        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
2135        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
2136        [item setImage: [NSImage imageNamed: @"Filter.png"]];
2137        [item setTarget: self];
2138        [item setAction: @selector(toggleFilterBar:)];
2139        [item setAutovalidates: NO];
2140    }
2141    else
2142    {
2143        [item release];
2144        return nil;
2145    }
2146
2147    return item;
2148}
2149
2150- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
2151{
2152    return [NSArray arrayWithObjects:
2153            TOOLBAR_OPEN, TOOLBAR_REMOVE,
2154            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
2155            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
2156            NSToolbarSeparatorItemIdentifier,
2157            NSToolbarSpaceItemIdentifier,
2158            NSToolbarFlexibleSpaceItemIdentifier,
2159            NSToolbarCustomizeToolbarItemIdentifier, nil];
2160}
2161
2162- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
2163{
2164    return [NSArray arrayWithObjects:
2165            TOOLBAR_OPEN, TOOLBAR_REMOVE,
2166            NSToolbarSeparatorItemIdentifier,
2167            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2168            NSToolbarFlexibleSpaceItemIdentifier,
2169            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2170}
2171
2172- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2173{
2174    NSString * ident = [toolbarItem itemIdentifier];
2175
2176    //enable remove item
2177    if ([ident isEqualToString: TOOLBAR_REMOVE])
2178        return [fTableView numberOfSelectedRows] > 0;
2179
2180    //enable pause all item
2181    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2182    {
2183        Torrent * torrent;
2184        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2185        while ((torrent = [enumerator nextObject]))
2186            if ([torrent isActive] || [torrent waitingToStart])
2187                return YES;
2188        return NO;
2189    }
2190
2191    //enable resume all item
2192    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2193    {
2194        Torrent * torrent;
2195        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2196        while ((torrent = [enumerator nextObject]))
2197            if ([torrent isPaused] && ![torrent waitingToStart])
2198                return YES;
2199        return NO;
2200    }
2201
2202    //enable pause item
2203    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2204    {
2205        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2206        Torrent * torrent;
2207        while ((torrent = [enumerator nextObject]))
2208        {
2209            if ([torrent isActive] || [torrent waitingToStart])
2210                return YES;
2211        }
2212        return NO;
2213    }
2214   
2215    //enable resume item
2216    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2217    {
2218        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2219        Torrent * torrent;
2220        while ((torrent = [enumerator nextObject]))
2221        {
2222            if ([torrent isPaused] && ![torrent waitingToStart])
2223                return YES;
2224        }
2225        return NO;
2226    }
2227
2228    return YES;
2229}
2230
2231- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2232{
2233    SEL action = [menuItem action];
2234
2235    //only enable some items if it is in a context menu or the window is useable
2236    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
2237
2238    //enable open items
2239    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
2240        return [fWindow attachedSheet] == nil;
2241   
2242    //enable sort and advanced bar items
2243    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2244        return [fWindow isVisible];
2245
2246    //enable show info
2247    if (action == @selector(showInfo:))
2248    {
2249        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector",
2250                            "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2251        if (![[menuItem title] isEqualToString: title])
2252                [menuItem setTitle: title];
2253
2254        return YES;
2255    }
2256   
2257    //enable prev/next inspector tab
2258    if (action == @selector(setInfoTab:))
2259        return [[fInfoController window] isVisible];
2260   
2261    //enable toggle status bar
2262    if (action == @selector(toggleStatusBar:))
2263    {
2264        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2265                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2266        if (![[menuItem title] isEqualToString: title])
2267            [menuItem setTitle: title];
2268
2269        return [fWindow isVisible];
2270    }
2271   
2272    //enable toggle filter bar
2273    if (action == @selector(toggleFilterBar:))
2274    {
2275        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2276                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2277        if (![[menuItem title] isEqualToString: title])
2278            [menuItem setTitle: title];
2279
2280        return [fWindow isVisible];
2281    }
2282   
2283    //enable prev/next filter button
2284    if (action == @selector(switchFilter:))
2285        return [fWindow isVisible] && ![fFilterBar isHidden];
2286
2287    //enable reveal in finder
2288    if (action == @selector(revealFile:))
2289        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2290
2291    //enable remove items
2292    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2293        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2294    {
2295        BOOL warning = NO,
2296            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2297            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2298       
2299        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2300        Torrent * torrent;
2301        while ((torrent = [enumerator nextObject]))
2302        {
2303            if (!warning && [torrent isActive])
2304            {
2305                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2306                if (warning && canDelete)
2307                    break;
2308            }
2309            if (!canDelete && [torrent publicTorrent])
2310            {
2311                canDelete = YES;
2312                if (warning)
2313                    break;
2314            }
2315        }
2316   
2317        //append or remove ellipsis when needed
2318        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2319        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2320        {
2321            if (![title hasSuffix: ellipsis])
2322                [menuItem setTitle: [title stringByAppendingEllipsis]];
2323        }
2324        else
2325        {
2326            if ([title hasSuffix: ellipsis])
2327                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2328        }
2329       
2330        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2331    }
2332
2333    //enable pause all item
2334    if (action == @selector(stopAllTorrents:))
2335    {
2336        Torrent * torrent;
2337        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2338        while ((torrent = [enumerator nextObject]))
2339            if ([torrent isActive] || [torrent waitingToStart])
2340                return YES;
2341        return NO;
2342    }
2343   
2344    //enable resume all item
2345    if (action == @selector(resumeAllTorrents:))
2346    {
2347        Torrent * torrent;
2348        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2349        while ((torrent = [enumerator nextObject]))
2350            if ([torrent isPaused] && ![torrent waitingToStart])
2351                return YES;
2352        return NO;
2353    }
2354   
2355    //enable resume all waiting item
2356    if (action == @selector(resumeWaitingTorrents:))
2357    {
2358        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2359            return NO;
2360   
2361        Torrent * torrent;
2362        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2363        while ((torrent = [enumerator nextObject]))
2364            if ([torrent isPaused] && [torrent waitingToStart])
2365                return YES;
2366        return NO;
2367    }
2368   
2369    //enable resume selected waiting item
2370    if (action == @selector(resumeSelectedTorrentsNoWait:))
2371    {
2372        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2373            return NO;
2374   
2375        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2376        Torrent * torrent;
2377        while ((torrent = [enumerator nextObject]))
2378            if ([torrent isPaused])
2379                return YES;
2380        return NO;
2381    }
2382
2383    //enable pause item
2384    if (action == @selector(stopSelectedTorrents:))
2385    {
2386        if (!canUseTable)
2387            return NO;
2388   
2389        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2390        Torrent * torrent;
2391        while ((torrent = [enumerator nextObject]))
2392            if ([torrent isActive] || [torrent waitingToStart])
2393                return YES;
2394        return NO;
2395    }
2396   
2397    //enable resume item
2398    if (action == @selector(resumeSelectedTorrents:))
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            if ([torrent isPaused] && ![torrent waitingToStart])
2407                return YES;
2408        return NO;
2409    }
2410   
2411    //enable announce item
2412    if (action == @selector(announceSelectedTorrents:))
2413    {
2414        if (!canUseTable)
2415            return NO;
2416       
2417        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2418        Torrent * torrent;
2419        NSDate * date;
2420        while ((torrent = [enumerator nextObject]))
2421        {
2422            //time interval returned will be negative
2423            if ([torrent isActive] &&
2424                    (!(date = [torrent announceDate]) || [date timeIntervalSinceNow] <= ANNOUNCE_WAIT_INTERVAL_SECONDS))
2425                return YES;
2426        }
2427        return NO;
2428    }
2429   
2430    //enable copy torrent file item
2431    if (action == @selector(copyTorrentFile:))
2432        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2433
2434    return YES;
2435}
2436
2437- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2438{
2439    NSEnumerator * enumerator;
2440    Torrent * torrent;
2441    BOOL active;
2442
2443    switch (messageType)
2444    {
2445        case kIOMessageSystemWillSleep:
2446            //close all connections before going to sleep and remember we should resume when we wake up
2447            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2448
2449            //wait for running transfers to stop (5 second timeout)
2450            NSDate * start = [NSDate date];
2451            BOOL timeUp = NO;
2452           
2453            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2454            Torrent * torrent;
2455            while (!timeUp && (torrent = [enumerator nextObject]))
2456                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2457                {
2458                    usleep(100000);
2459                    [torrent update];
2460                }
2461
2462            IOAllowPowerChange(fRootPort, (long) messageArgument);
2463            break;
2464
2465        case kIOMessageCanSystemSleep:
2466            //pevent idle sleep unless all paused
2467            active = NO;
2468            enumerator = [fTorrents objectEnumerator];
2469            while ((torrent = [enumerator nextObject]))
2470                if ([torrent isActive])
2471                {
2472                    active = YES;
2473                    break;
2474                }
2475
2476            if (active)
2477                IOCancelPowerChange(fRootPort, (long) messageArgument);
2478            else
2479                IOAllowPowerChange(fRootPort, (long) messageArgument);
2480            break;
2481
2482        case kIOMessageSystemHasPoweredOn:
2483            //resume sleeping transfers after we wake up
2484            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2485            break;
2486    }
2487}
2488
2489- (void) resetDockBadge: (NSNotification *) notification
2490{
2491    float downloadRate, uploadRate;
2492    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2493   
2494    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2495}
2496
2497- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2498{
2499    //if auto size is enabled, the current frame shouldn't need to change
2500    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2501   
2502    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2503    return frame;
2504}
2505
2506- (void) setWindowSizeToFit
2507{
2508    if ([fDefaults boolForKey: @"AutoSize"])
2509    {
2510        [fScrollView setHasVerticalScroller: NO];
2511        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2512        [fScrollView setHasVerticalScroller: YES];
2513    }
2514}
2515
2516- (NSRect) sizedWindowFrame
2517{
2518    NSRect frame = [fWindow frame];
2519    float newHeight = frame.size.height - [fScrollView frame].size.height
2520        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2521
2522    float minHeight = [fWindow minSize].height;
2523    if (newHeight < minHeight)
2524        newHeight = minHeight;
2525    else
2526    {
2527        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2528        if ([fStatusBar isHidden])
2529            maxHeight -= [fStatusBar frame].size.height;
2530        if ([fFilterBar isHidden])
2531            maxHeight -= [fFilterBar frame].size.height;
2532       
2533        if (newHeight > maxHeight)
2534            newHeight = maxHeight;
2535    }
2536
2537    frame.origin.y -= (newHeight - frame.size.height);
2538    frame.size.height = newHeight;
2539    return frame;
2540}
2541
2542- (void) showMainWindow: (id) sender
2543{
2544    [fWindow makeKeyAndOrderFront: nil];
2545}
2546
2547- (void) windowDidBecomeKey: (NSNotification *) notification
2548{
2549    //reset dock badge for completed
2550    if (fCompleted > 0)
2551    {
2552        fCompleted = 0;
2553        [self resetDockBadge: nil];
2554    }
2555}
2556
2557- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2558{
2559    //only resize horizontally if autosize is enabled
2560    if ([fDefaults boolForKey: @"AutoSize"])
2561        proposedFrameSize.height = [fWindow frame].size.height;
2562    return proposedFrameSize;
2563}
2564
2565- (void) windowDidResize: (NSNotification *) notification
2566{
2567    //hide search filter if it overlaps filter buttons
2568    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2569}
2570
2571- (void) linkHomepage: (id) sender
2572{
2573    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2574}
2575
2576- (void) linkForums: (id) sender
2577{
2578    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2579}
2580
2581- (void) prepareForUpdate: (NSNotification *) notification
2582{
2583    fUpdateInProgress = YES;
2584}
2585
2586- (NSDictionary *) registrationDictionaryForGrowl
2587{
2588    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2589                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2590    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2591                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2592}
2593
2594@end
Note: See TracBrowser for help on using the repository browser.