source: trunk/macosx/Controller.m @ 1305

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

remove bindings from the rest of the text fields, added back glue code

  • Property svn:keywords set to Date Rev Author Id
File size: 96.3 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 1305 2006-12-31 23:24:23Z 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 updateLimitFields];
1567    [fPrefsController applySpeedSettings: nil];
1568}
1569
1570- (void) setQuickRatioGlobal: (id) sender
1571{
1572    [fDefaults setBool: YES forKey: @"RatioCheck"];
1573    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
1574   
1575    [fPrefsController updateRatioStopField];
1576}
1577
1578- (void) checkWaitingForStopped: (NSNotification *) notification
1579{
1580    [self checkToStartWaiting: [notification object]];
1581   
1582    [self updateUI: nil];
1583    [self applyFilter: nil];
1584    [self updateTorrentHistory];
1585}
1586
1587- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1588{
1589    //don't try to start a transfer if there should be none waiting
1590    if (![fDefaults boolForKey: @"Queue"])
1591        return;
1592
1593    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1594   
1595    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1596    Torrent * torrent, * torrentToStart = nil;
1597    while ((torrent = [enumerator nextObject]))
1598    {
1599        //ignore the torrent just stopped
1600        if (torrent == finishedTorrent)
1601            continue;
1602   
1603        if ([torrent isActive])
1604        {
1605            if (![torrent isSeeding] && ![torrent isError])
1606            {
1607                desiredActive--;
1608                if (desiredActive <= 0)
1609                    return;
1610            }
1611        }
1612        else
1613        {
1614            //use as next if it is waiting to start and either no previous or order value is lower
1615            if ([torrent waitingToStart] && (!torrentToStart
1616                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1617                torrentToStart = torrent;
1618        }
1619    }
1620   
1621    //since it hasn't returned, the queue amount has not been met
1622    if (torrentToStart)
1623    {
1624        [torrentToStart startTransfer];
1625       
1626        [self updateUI: nil];
1627        [self applyFilter: nil];
1628        [self updateTorrentHistory];
1629    }
1630}
1631
1632- (void) torrentStartSettingChange: (NSNotification *) notification
1633{
1634    [self attemptToStartMultipleAuto: [notification object]];
1635
1636    [self updateUI: nil];
1637    [self applyFilter: nil];
1638    [self updateTorrentHistory];
1639}
1640
1641- (void) globalStartSettingChange: (NSNotification *) notification
1642{
1643    [self attemptToStartMultipleAuto: fTorrents];
1644   
1645    [self updateUI: nil];
1646    [self applyFilter: nil];
1647    [self updateTorrentHistory];
1648}
1649
1650- (void) torrentStoppedForRatio: (NSNotification *) notification
1651{
1652    [self applyFilter: nil];
1653    [fInfoController updateInfoStats];
1654   
1655    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1656    {
1657        NSSound * sound;
1658        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1659            [sound play];
1660    }
1661   
1662    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1663        description: [[notification object] name]
1664        notificationName: GROWL_SEEDING_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1665}
1666
1667- (void) attemptToStartAuto: (Torrent *) torrent
1668{
1669    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1670}
1671
1672//will try to start, taking into consideration the start preference
1673- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1674{
1675    if (![fDefaults boolForKey: @"Queue"])
1676    {
1677        NSEnumerator * enumerator = [torrents objectEnumerator];
1678        Torrent * torrent;
1679        while ((torrent = [enumerator nextObject]))
1680            if ([torrent waitingToStart])
1681                [torrent startTransfer];
1682       
1683        return;
1684    }
1685   
1686    //determine the number of downloads needed to start
1687    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1688           
1689    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1690    Torrent * torrent;
1691    while ((torrent = [enumerator nextObject]))
1692        if ([torrent isActive] && ![torrent isSeeding] && ![torrent isError])
1693        {
1694            desiredActive--;
1695            if (desiredActive <= 0)
1696                break;
1697        }
1698   
1699    //sort torrents by order value
1700    NSArray * sortedTorrents;
1701    if ([torrents count] > 1 && desiredActive > 0)
1702    {
1703        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1704                                                    @"orderValue" ascending: YES] autorelease];
1705        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1706       
1707        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1708        [descriptors release];
1709    }
1710    else
1711        sortedTorrents = torrents;
1712
1713    enumerator = [sortedTorrents objectEnumerator];
1714    while ((torrent = [enumerator nextObject]))
1715    {
1716        if ([torrent waitingToStart])
1717        {
1718            if ([torrent progress] >= 1.0)
1719                [torrent startTransfer];
1720            else if (desiredActive > 0)
1721            {
1722                [torrent startTransfer];
1723                desiredActive--;
1724            }
1725            else
1726                continue;
1727           
1728            [torrent update];
1729        }
1730    }
1731}
1732
1733-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
1734{
1735    if ([notification isEqualToString: UKFileWatcherWriteNotification])
1736        [self checkAutoImportDirectory];
1737}
1738
1739- (void) changeAutoImport
1740{
1741    [fAutoImportedNames removeAllObjects];
1742    [self checkAutoImportDirectory];
1743}
1744
1745- (void) checkAutoImportDirectory
1746{
1747    if (![fDefaults boolForKey: @"AutoImport"])
1748        return;
1749       
1750    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1751   
1752    NSArray * importedNames;
1753    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
1754        return;
1755   
1756    //only import those that have not been imported yet
1757    NSMutableArray * newNames = [importedNames mutableCopy];
1758    [newNames removeObjectsInArray: fAutoImportedNames];
1759    [fAutoImportedNames setArray: importedNames];
1760   
1761    NSString * file;
1762    int i;
1763    for (i = [newNames count] - 1; i >= 0; i--)
1764    {
1765        file = [newNames objectAtIndex: i];
1766        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
1767            [newNames removeObjectAtIndex: i];
1768        else
1769            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
1770    }
1771   
1772    NSEnumerator * enumerator;
1773    if (![[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"])
1774    {
1775        enumerator = [newNames objectEnumerator];
1776        int count;
1777        while ((file = [enumerator nextObject]))
1778        {
1779            count = [fTorrents count];
1780            [self openFiles: [NSArray arrayWithObject: file]];
1781           
1782            //check if torrent was opened
1783            if ([fTorrents count] > count)
1784                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
1785                    "Growl notification title") description: [file lastPathComponent]
1786                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1787        }
1788    }
1789    else
1790        [self openFiles: newNames];
1791   
1792    //create temporary torrents to check if an import fails because of an error
1793    enumerator = [newNames objectEnumerator];
1794    int error;
1795    while ((file = [enumerator nextObject]))
1796    {
1797        tr_torrent_t * tempTor = tr_torrentInit(fLib, [file UTF8String], 0, & error);
1798       
1799        if (tempTor)
1800            tr_torrentClose(fLib, tempTor);
1801        else if (error != TR_EUNSUPPORTED && error != TR_EDUPLICATE)
1802            [fAutoImportedNames removeObjectIdenticalTo: [file lastPathComponent]]; //can try to import later
1803        else;
1804    }
1805   
1806    [newNames release];
1807}
1808
1809- (int) numberOfRowsInTableView: (NSTableView *) tableview
1810{
1811    return [fDisplayedTorrents count];
1812}
1813
1814- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
1815{
1816    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
1817}
1818
1819- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1820    toPasteboard: (NSPasteboard *) pasteboard
1821{
1822    //only allow reordering of rows if sorting by order with no filter
1823    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1824            && [[fSearchFilterField stringValue] length] == 0)
1825    {
1826        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1827        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1828                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1829        return YES;
1830    }
1831    return NO;
1832}
1833
1834- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1835    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1836{
1837    NSPasteboard * pasteboard = [info draggingPasteboard];
1838    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1839    {
1840        //check if any files to add have "torrent" as an extension
1841        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1842        NSString * file;
1843        while ((file = [enumerator nextObject]))
1844            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1845            {
1846                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1847                return NSDragOperationGeneric;
1848            }
1849    }
1850    else if ([[pasteboard types] containsObject: NSURLPboardType])
1851    {
1852        [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1853        return NSDragOperationGeneric;
1854    }
1855    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1856    {
1857        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1858        return NSDragOperationGeneric;
1859    }
1860    else;
1861   
1862    return NSDragOperationNone;
1863}
1864
1865- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1866    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1867{
1868    NSPasteboard * pasteboard = [info draggingPasteboard];
1869    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1870    {
1871        //create an array of files with the "torrent" extension
1872        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1873        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1874        NSString * file;
1875        while ((file = [enumerator nextObject]))
1876            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1877                [filesToOpen addObject: file];
1878   
1879        [self application: NSApp openFiles: filesToOpen];
1880        [filesToOpen release];
1881    }
1882    else if ([[pasteboard types] containsObject: NSURLPboardType])
1883    {
1884        NSURL * url;
1885        if ((url = [NSURL URLFromPasteboard: pasteboard]))
1886            [self openURL: url];
1887    }
1888    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1889    {
1890        //remember selected rows if needed
1891        NSArray * selectedTorrents = nil;
1892        int numSelected = [fTableView numberOfSelectedRows];
1893        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1894            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1895   
1896        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1897                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1898       
1899        //move torrent in array
1900        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
1901        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1902       
1903        //determine the insertion index now that transfers to move have been removed
1904        int i, decrease = 0;
1905        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1906            decrease++;
1907       
1908        //insert objects at new location
1909        for (i = 0; i < [movingTorrents count]; i++)
1910            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1911       
1912        [movingTorrents release];
1913       
1914        //redo order values
1915        int low = [indexes firstIndex], high = [indexes lastIndex];
1916        if (newRow < low)
1917            low = newRow;
1918        else if (newRow > high + 1)
1919            high = newRow - 1;
1920        else;
1921       
1922        for (i = low; i <= high; i++)
1923            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1924       
1925        [fTableView reloadData];
1926       
1927        //set selected rows if needed
1928        if (selectedTorrents)
1929        {
1930            Torrent * torrent;
1931            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1932            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1933            while ((torrent = [enumerator nextObject]))
1934                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1935           
1936            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1937            [indexSet release];
1938        }
1939    }
1940    else;
1941   
1942    return YES;
1943}
1944
1945- (void) tableViewSelectionDidChange: (NSNotification *) notification
1946{
1947    [fInfoController updateInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
1948}
1949
1950- (void) toggleSmallView: (id) sender
1951{
1952    BOOL makeSmall = [fDefaults boolForKey: @"SmallView"];
1953   
1954    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1955   
1956    //window min height
1957    NSSize contentMinSize = [fWindow contentMinSize],
1958            contentSize = [[fWindow contentView] frame].size;
1959    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1960                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1961    [fWindow setContentMinSize: contentMinSize];
1962   
1963    //resize for larger min height if not set to auto size
1964    if (![fDefaults boolForKey: @"AutoSize"])
1965    {
1966        if (!makeSmall && contentSize.height < contentMinSize.height)
1967        {
1968            NSRect frame = [fWindow frame];
1969            float heightChange = contentMinSize.height - contentSize.height;
1970            frame.size.height += heightChange;
1971            frame.origin.y -= heightChange;
1972           
1973            [fWindow setFrame: frame display: YES];
1974            [fTableView reloadData];
1975        }
1976    }
1977    else
1978        [self setWindowSizeToFit];
1979}
1980
1981- (void) toggleStatusBar: (id) sender
1982{
1983    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1984    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1985}
1986
1987- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1988{
1989    if (show != [fStatusBar isHidden])
1990        return;
1991
1992    if (show)
1993        [fStatusBar setHidden: NO];
1994
1995    NSRect frame = [fWindow frame];
1996    float heightChange = [fStatusBar frame].size.height;
1997    if (!show)
1998        heightChange *= -1;
1999   
2000    //allow bar to show even if not enough room
2001    if (show && ![fDefaults boolForKey: @"AutoSize"])
2002    {
2003        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
2004        if (frame.size.height > maxHeight)
2005        {
2006            float change = maxHeight - frame.size.height;
2007            frame.size.height += change;
2008            frame.origin.y -= change;
2009           
2010            [fWindow setFrame: frame display: NO animate: NO];
2011        }
2012    }
2013
2014    frame.size.height += heightChange;
2015    frame.origin.y -= heightChange;
2016   
2017    [self updateUI: nil];
2018   
2019    //set views to not autoresize
2020    unsigned int statsMask = [fStatusBar autoresizingMask];
2021    unsigned int filterMask = [fFilterBar autoresizingMask];
2022    unsigned int scrollMask = [fScrollView autoresizingMask];
2023    [fStatusBar setAutoresizingMask: 0];
2024    [fFilterBar setAutoresizingMask: 0];
2025    [fScrollView setAutoresizingMask: 0];
2026   
2027    [fWindow setFrame: frame display: YES animate: animate];
2028   
2029    //re-enable autoresize
2030    [fStatusBar setAutoresizingMask: statsMask];
2031    [fFilterBar setAutoresizingMask: filterMask];
2032    [fScrollView setAutoresizingMask: scrollMask];
2033   
2034    //change min size
2035    NSSize minSize = [fWindow contentMinSize];
2036    minSize.height += heightChange;
2037    [fWindow setContentMinSize: minSize];
2038   
2039    if (!show)
2040        [fStatusBar setHidden: YES];
2041}
2042
2043- (void) toggleFilterBar: (id) sender
2044{
2045    //disable filtering when hiding
2046    if (![fFilterBar isHidden])
2047    {
2048        [fSearchFilterField setStringValue: @""];
2049        [self setFilter: fNoFilterButton];
2050    }
2051
2052    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2053    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2054}
2055
2056- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2057{
2058    if (show != [fFilterBar isHidden])
2059        return;
2060
2061    if (show)
2062        [fFilterBar setHidden: NO];
2063
2064    NSRect frame = [fWindow frame];
2065    float heightChange = [fFilterBar frame].size.height;
2066    if (!show)
2067        heightChange *= -1;
2068   
2069    //allow bar to show even if not enough room
2070    if (show && ![fDefaults boolForKey: @"AutoSize"])
2071    {
2072        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
2073        if (frame.size.height > maxHeight)
2074        {
2075            float change = maxHeight - frame.size.height;
2076            frame.size.height += change;
2077            frame.origin.y -= change;
2078           
2079            [fWindow setFrame: frame display: NO animate: NO];
2080        }
2081    }
2082
2083    frame.size.height += heightChange;
2084    frame.origin.y -= heightChange;
2085   
2086    //set views to not autoresize
2087    unsigned int filterMask = [fFilterBar autoresizingMask];
2088    unsigned int scrollMask = [fScrollView autoresizingMask];
2089    [fFilterBar setAutoresizingMask: 0];
2090    [fScrollView setAutoresizingMask: 0];
2091   
2092    [fWindow setFrame: frame display: YES animate: animate];
2093   
2094    //re-enable autoresize
2095    [fFilterBar setAutoresizingMask: filterMask];
2096    [fScrollView setAutoresizingMask: scrollMask];
2097   
2098    //change min size
2099    NSSize minSize = [fWindow contentMinSize];
2100    minSize.height += heightChange;
2101    [fWindow setContentMinSize: minSize];
2102   
2103    if (!show)
2104    {
2105        [fFilterBar setHidden: YES];
2106        [fWindow makeFirstResponder: fTableView];
2107    }
2108}
2109
2110- (void) toggleAdvancedBar: (id) sender
2111{
2112    [fTableView display];
2113}
2114
2115- (void) doNothing: (id) sender {}
2116
2117- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
2118    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2119{
2120    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
2121
2122    if ([ident isEqualToString: TOOLBAR_OPEN])
2123    {
2124        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
2125        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
2126        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
2127        [item setImage: [NSImage imageNamed: @"Open.png"]];
2128        [item setTarget: self];
2129        [item setAction: @selector(openShowSheet:)];
2130        [item setAutovalidates: NO];
2131    }
2132    else if ([ident isEqualToString: TOOLBAR_REMOVE])
2133    {
2134        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
2135        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
2136        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
2137        [item setImage: [NSImage imageNamed: @"Remove.png"]];
2138        [item setTarget: self];
2139        [item setAction: @selector(removeNoDelete:)];
2140    }
2141    else if ([ident isEqualToString: TOOLBAR_INFO])
2142    {
2143        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
2144        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
2145        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
2146        [item setImage: [NSImage imageNamed: @"Info.png"]];
2147        [item setTarget: self];
2148        [item setAction: @selector(showInfo:)];
2149        [item setAutovalidates: NO];
2150    }
2151    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2152    {
2153        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
2154        [item setPaletteLabel: [item label]];
2155        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
2156        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
2157        [item setTarget: self];
2158        [item setAction: @selector(stopAllTorrents:)];
2159    }
2160    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2161    {
2162        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
2163        [item setPaletteLabel: [item label]];
2164        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
2165        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
2166        [item setTarget: self];
2167        [item setAction: @selector(resumeAllTorrents:)];
2168    }
2169    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2170    {
2171        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
2172        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
2173        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
2174        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
2175        [item setTarget: self];
2176        [item setAction: @selector(stopSelectedTorrents:)];
2177    }
2178    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2179    {
2180        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
2181        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
2182        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
2183        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
2184        [item setTarget: self];
2185        [item setAction: @selector(resumeSelectedTorrents:)];
2186    }
2187    else if ([ident isEqualToString: TOOLBAR_FILTER])
2188    {
2189        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
2190        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
2191        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
2192        [item setImage: [NSImage imageNamed: @"Filter.png"]];
2193        [item setTarget: self];
2194        [item setAction: @selector(toggleFilterBar:)];
2195        [item setAutovalidates: NO];
2196    }
2197    else
2198    {
2199        [item release];
2200        return nil;
2201    }
2202
2203    return item;
2204}
2205
2206- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
2207{
2208    return [NSArray arrayWithObjects:
2209            TOOLBAR_OPEN, TOOLBAR_REMOVE,
2210            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
2211            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
2212            NSToolbarSeparatorItemIdentifier,
2213            NSToolbarSpaceItemIdentifier,
2214            NSToolbarFlexibleSpaceItemIdentifier,
2215            NSToolbarCustomizeToolbarItemIdentifier, nil];
2216}
2217
2218- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
2219{
2220    return [NSArray arrayWithObjects:
2221            TOOLBAR_OPEN, TOOLBAR_REMOVE,
2222            NSToolbarSeparatorItemIdentifier,
2223            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2224            NSToolbarFlexibleSpaceItemIdentifier,
2225            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2226}
2227
2228- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2229{
2230    NSString * ident = [toolbarItem itemIdentifier];
2231
2232    //enable remove item
2233    if ([ident isEqualToString: TOOLBAR_REMOVE])
2234        return [fTableView numberOfSelectedRows] > 0;
2235
2236    //enable pause all item
2237    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2238    {
2239        Torrent * torrent;
2240        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2241        while ((torrent = [enumerator nextObject]))
2242            if ([torrent isActive] || [torrent waitingToStart])
2243                return YES;
2244        return NO;
2245    }
2246
2247    //enable resume all item
2248    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2249    {
2250        Torrent * torrent;
2251        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2252        while ((torrent = [enumerator nextObject]))
2253            if ([torrent isPaused] && ![torrent waitingToStart])
2254                return YES;
2255        return NO;
2256    }
2257
2258    //enable pause item
2259    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2260    {
2261        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2262        Torrent * torrent;
2263        while ((torrent = [enumerator nextObject]))
2264        {
2265            if ([torrent isActive] || [torrent waitingToStart])
2266                return YES;
2267        }
2268        return NO;
2269    }
2270   
2271    //enable resume item
2272    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2273    {
2274        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2275        Torrent * torrent;
2276        while ((torrent = [enumerator nextObject]))
2277        {
2278            if ([torrent isPaused] && ![torrent waitingToStart])
2279                return YES;
2280        }
2281        return NO;
2282    }
2283
2284    return YES;
2285}
2286
2287- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2288{
2289    SEL action = [menuItem action];
2290
2291    //only enable some items if it is in a context menu or the window is useable
2292    BOOL canUseTable = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
2293
2294    //enable open items
2295    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
2296        return [fWindow attachedSheet] == nil;
2297   
2298    //enable sort and advanced bar items
2299    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2300        return [fWindow isVisible];
2301
2302    //enable show info
2303    if (action == @selector(showInfo:))
2304    {
2305        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector",
2306                            "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2307        if (![[menuItem title] isEqualToString: title])
2308                [menuItem setTitle: title];
2309
2310        return YES;
2311    }
2312   
2313    //enable prev/next inspector tab
2314    if (action == @selector(setInfoTab:))
2315        return [[fInfoController window] isVisible];
2316   
2317    //enable toggle status bar
2318    if (action == @selector(toggleStatusBar:))
2319    {
2320        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2321                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2322        if (![[menuItem title] isEqualToString: title])
2323            [menuItem setTitle: title];
2324
2325        return [fWindow isVisible];
2326    }
2327   
2328    //enable toggle filter bar
2329    if (action == @selector(toggleFilterBar:))
2330    {
2331        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2332                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2333        if (![[menuItem title] isEqualToString: title])
2334            [menuItem setTitle: title];
2335
2336        return [fWindow isVisible];
2337    }
2338   
2339    //enable prev/next filter button
2340    if (action == @selector(switchFilter:))
2341        return [fWindow isVisible] && ![fFilterBar isHidden];
2342
2343    //enable reveal in finder
2344    if (action == @selector(revealFile:))
2345        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2346
2347    //enable remove items
2348    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2349        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2350    {
2351        BOOL warning = NO,
2352            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2353            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2354       
2355        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2356        Torrent * torrent;
2357        while ((torrent = [enumerator nextObject]))
2358        {
2359            if (!warning && [torrent isActive])
2360            {
2361                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2362                if (warning && canDelete)
2363                    break;
2364            }
2365            if (!canDelete && [torrent publicTorrent])
2366            {
2367                canDelete = YES;
2368                if (warning)
2369                    break;
2370            }
2371        }
2372   
2373        //append or remove ellipsis when needed
2374        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2375        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2376        {
2377            if (![title hasSuffix: ellipsis])
2378                [menuItem setTitle: [title stringByAppendingEllipsis]];
2379        }
2380        else
2381        {
2382            if ([title hasSuffix: ellipsis])
2383                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2384        }
2385       
2386        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2387    }
2388
2389    //enable pause all item
2390    if (action == @selector(stopAllTorrents:))
2391    {
2392        Torrent * torrent;
2393        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2394        while ((torrent = [enumerator nextObject]))
2395            if ([torrent isActive] || [torrent waitingToStart])
2396                return YES;
2397        return NO;
2398    }
2399   
2400    //enable resume all item
2401    if (action == @selector(resumeAllTorrents:))
2402    {
2403        Torrent * torrent;
2404        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2405        while ((torrent = [enumerator nextObject]))
2406            if ([torrent isPaused] && ![torrent waitingToStart])
2407                return YES;
2408        return NO;
2409    }
2410   
2411    //enable resume all waiting item
2412    if (action == @selector(resumeWaitingTorrents:))
2413    {
2414        if (![fDefaults boolForKey: @"Queue"])
2415            return NO;
2416   
2417        Torrent * torrent;
2418        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2419        while ((torrent = [enumerator nextObject]))
2420            if ([torrent waitingToStart])
2421                return YES;
2422        return NO;
2423    }
2424   
2425    //enable resume selected waiting item
2426    if (action == @selector(resumeSelectedTorrentsNoWait:))
2427    {
2428        if (![fDefaults boolForKey: @"Queue"])
2429            return NO;
2430   
2431        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2432        Torrent * torrent;
2433        while ((torrent = [enumerator nextObject]))
2434        {
2435            if ([torrent isPaused] && [torrent progress] < 1.0)
2436                return YES;
2437        }
2438        return NO;
2439    }
2440
2441    //enable pause item
2442    if (action == @selector(stopSelectedTorrents:))
2443    {
2444        if (!canUseTable)
2445            return NO;
2446   
2447        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2448        Torrent * torrent;
2449        while ((torrent = [enumerator nextObject]))
2450        {
2451            if ([torrent isActive] || [torrent waitingToStart])
2452                return YES;
2453        }
2454        return NO;
2455    }
2456   
2457    //enable resume item
2458    if (action == @selector(resumeSelectedTorrents:))
2459    {
2460        if (!canUseTable)
2461            return NO;
2462   
2463        Torrent * torrent;
2464        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2465        unsigned int i;
2466       
2467        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2468        {
2469            torrent = [fDisplayedTorrents objectAtIndex: i];
2470            if ([torrent isPaused] && ![torrent waitingToStart])
2471                return YES;
2472        }
2473        return NO;
2474    }
2475   
2476    //enable announce item
2477    if (action == @selector(announceSelectedTorrents:))
2478    {
2479        if (!canUseTable)
2480            return NO;
2481       
2482        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2483        Torrent * torrent;
2484        NSDate * date;
2485        while ((torrent = [enumerator nextObject]))
2486        {
2487            //time interval returned will be negative
2488            if ([torrent isActive] &&
2489                    (!(date = [torrent announceDate]) || [date timeIntervalSinceNow] <= ANNOUNCE_WAIT_INTERVAL_SECONDS))
2490                return YES;
2491        }
2492        return NO;
2493    }
2494   
2495    //enable copy torrent file item
2496    if (action == @selector(copyTorrentFile:))
2497        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2498
2499    return YES;
2500}
2501
2502- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2503{
2504    NSEnumerator * enumerator;
2505    Torrent * torrent;
2506    BOOL active;
2507
2508    switch (messageType)
2509    {
2510        case kIOMessageSystemWillSleep:
2511            //close all connections before going to sleep and remember we should resume when we wake up
2512            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2513
2514            //wait for running transfers to stop (5 second timeout)
2515            NSDate * start = [NSDate date];
2516            BOOL timeUp = NO;
2517           
2518            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2519            Torrent * torrent;
2520            while (!timeUp && (torrent = [enumerator nextObject]))
2521                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2522                {
2523                    usleep(100000);
2524                    [torrent update];
2525                }
2526
2527            IOAllowPowerChange(fRootPort, (long) messageArgument);
2528            break;
2529
2530        case kIOMessageCanSystemSleep:
2531            //pevent idle sleep unless all paused
2532            active = NO;
2533            enumerator = [fTorrents objectEnumerator];
2534            while ((torrent = [enumerator nextObject]))
2535                if ([torrent isActive])
2536                {
2537                    active = YES;
2538                    break;
2539                }
2540
2541            if (active)
2542                IOCancelPowerChange(fRootPort, (long) messageArgument);
2543            else
2544                IOAllowPowerChange(fRootPort, (long) messageArgument);
2545            break;
2546
2547        case kIOMessageSystemHasPoweredOn:
2548            //resume sleeping transfers after we wake up
2549            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2550            break;
2551    }
2552}
2553
2554- (void) resetDockBadge: (NSNotification *) notification
2555{
2556    float downloadRate, uploadRate;
2557    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2558   
2559    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2560}
2561
2562- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2563{
2564    //if auto size is enabled, the current frame shouldn't need to change
2565    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2566   
2567    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2568    return frame;
2569}
2570
2571- (void) setWindowSizeToFit
2572{
2573    if ([fDefaults boolForKey: @"AutoSize"])
2574    {
2575        [fScrollView setHasVerticalScroller: NO];
2576        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2577        [fScrollView setHasVerticalScroller: YES];
2578    }
2579}
2580
2581- (NSRect) sizedWindowFrame
2582{
2583    NSRect frame = [fWindow frame];
2584    float newHeight = frame.size.height - [fScrollView frame].size.height
2585        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2586
2587    float minHeight = [fWindow minSize].height;
2588    if (newHeight < minHeight)
2589        newHeight = minHeight;
2590    else
2591    {
2592        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2593        if ([fStatusBar isHidden])
2594            maxHeight -= [fStatusBar frame].size.height;
2595        if ([fFilterBar isHidden])
2596            maxHeight -= [fFilterBar frame].size.height;
2597       
2598        if (newHeight > maxHeight)
2599            newHeight = maxHeight;
2600    }
2601
2602    frame.origin.y -= (newHeight - frame.size.height);
2603    frame.size.height = newHeight;
2604    return frame;
2605}
2606
2607- (void) showMainWindow: (id) sender
2608{
2609    [fWindow makeKeyAndOrderFront: nil];
2610}
2611
2612- (void) windowDidBecomeKey: (NSNotification *) notification
2613{
2614    //reset dock badge for completed
2615    if (fCompleted > 0)
2616    {
2617        fCompleted = 0;
2618        [self resetDockBadge: nil];
2619    }
2620}
2621
2622- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2623{
2624    //only resize horizontally if autosize is enabled
2625    if ([fDefaults boolForKey: @"AutoSize"])
2626        proposedFrameSize.height = [fWindow frame].size.height;
2627    return proposedFrameSize;
2628}
2629
2630- (void) windowDidResize: (NSNotification *) notification
2631{
2632    //hide search filter if it overlaps filter buttons
2633    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2634}
2635
2636- (void) linkHomepage: (id) sender
2637{
2638    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2639}
2640
2641- (void) linkForums: (id) sender
2642{
2643    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2644}
2645
2646- (void) prepareForUpdate: (NSNotification *) notification
2647{
2648    fUpdateInProgress = YES;
2649}
2650
2651- (NSDictionary *) registrationDictionaryForGrowl
2652{
2653    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2654                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2655    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2656                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2657}
2658
2659@end
Note: See TracBrowser for help on using the repository browser.