source: trunk/macosx/Controller.m @ 1125

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

a little Controller cleaning

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