source: trunk/macosx/Controller.m @ 1093

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

Choose a new volume for downloading if the current isn't available. I still need feedback on this.

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