source: trunk/macosx/Controller.m @ 1289

Last change on this file since 1289 was 1289, checked in by livings124, 16 years ago

individual download/upload speed caps accessible under options in the inspector

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