source: trunk/macosx/Controller.m @ 1113

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

die nslog!

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