source: trunk/macosx/Controller.m @ 1103

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

change to the url sheet sizing

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