source: trunk/macosx/Controller.m @ 1094

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

warning if move folder doesn't exist, and a few releases

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