source: trunk/macosx/Controller.m @ 3852

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

readd the custom FilterButton? subclass to simplify setting the tooltip

  • Property svn:keywords set to Date Rev Author Id
File size: 125.2 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 3852 2007-11-17 15:55:23Z livings124 $
3 *
4 * Copyright (c) 2005-2007 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 "CreatorWindowController.h"
32#import "AboutWindowController.h"
33#import "NSApplicationAdditions.h"
34#import "NSStringAdditions.h"
35#import "UKKQueue.h"
36#import "ActionMenuSpeedToDisplayLimitTransformer.h"
37#import "ActionMenuRatioToDisplayRatioTransformer.h"
38#import "ExpandedPathToPathTransformer.h"
39#import "ExpandedPathToIconTransformer.h"
40#import "SpeedLimitToTurtleIconTransformer.h"
41
42#import <Sparkle/Sparkle.h>
43
44#define TOOLBAR_CREATE          @"Toolbar Create"
45#define TOOLBAR_OPEN            @"Toolbar Open"
46#define TOOLBAR_REMOVE          @"Toolbar Remove"
47#define TOOLBAR_INFO            @"Toolbar Info"
48#define TOOLBAR_PAUSE_ALL       @"Toolbar Pause All"
49#define TOOLBAR_RESUME_ALL      @"Toolbar Resume All"
50#define TOOLBAR_PAUSE_SELECTED  @"Toolbar Pause Selected"
51#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected"
52#define TOOLBAR_FILTER          @"Toolbar Toggle Filter"
53
54#define SORT_DATE       @"Date"
55#define SORT_NAME       @"Name"
56#define SORT_STATE      @"State"
57#define SORT_PROGRESS   @"Progress"
58#define SORT_TRACKER    @"Tracker"
59#define SORT_ORDER      @"Order"
60
61typedef enum
62{
63    SORT_ORDER_TAG = 0,
64    SORT_DATE_TAG = 1,
65    SORT_NAME_TAG = 2,
66    SORT_PROGRESS_TAG = 3,
67    SORT_STATE_TAG = 4,
68    SORT_TRACKER_TAG = 5
69} sortTag;
70
71#define FILTER_NONE     @"None"
72#define FILTER_DOWNLOAD @"Download"
73#define FILTER_SEED     @"Seed"
74#define FILTER_PAUSE    @"Pause"
75
76#define FILTER_TYPE_NAME    @"Name"
77#define FILTER_TYPE_TRACKER @"Tracker"
78
79#define FILTER_TYPE_TAG_NAME    401
80#define FILTER_TYPE_TAG_TRACKER 402
81
82#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
83#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
84#define GROWL_AUTO_ADD          @"Torrent Auto Added"
85#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
86
87#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
88
89#define ROW_HEIGHT_REGULAR      65.0
90#define ROW_HEIGHT_SMALL        40.0
91#define WINDOW_REGULAR_WIDTH    468.0
92
93#define SEARCH_FILTER_MIN_WIDTH 55.0
94#define SEARCH_FILTER_MAX_WIDTH 115.0
95
96#define UPDATE_UI_SECONDS           1.0
97#define AUTO_SPEED_LIMIT_SECONDS    5.0
98
99#define DOCK_SEEDING_TAG        101
100#define DOCK_DOWNLOADING_TAG    102
101
102#define SUPPORT_FOLDER  @"/Library/Application Support/Transmission/Transfers.plist"
103
104#define WEBSITE_URL @"http://transmission.m0k.org/"
105#define FORUM_URL   @"http://transmission.m0k.org/forum/"
106#define DONATE_URL  @"http://transmission.m0k.org/donate.php"
107
108void sleepCallBack(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
109{
110    [(Controller *)controller sleepCallBack: messageType argument: messageArgument];
111}
112
113@implementation Controller
114
115+ (void) initialize
116{
117    //make sure another Transmission.app isn't running already
118    NSString * bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
119    int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
120
121    NSDictionary * dic;
122    NSEnumerator * enumerator = [[[NSWorkspace sharedWorkspace] launchedApplications] objectEnumerator];
123    while ((dic = [enumerator nextObject]))
124    {
125        if ([[dic objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]
126            && [[dic objectForKey: @"NSApplicationProcessIdentifier"] intValue] != processIdentifier)
127        {
128            NSAlert * alert = [[NSAlert alloc] init];
129            [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Transmission already running alert -> button")];
130            [alert setMessageText: NSLocalizedString(@"Transmission is already running.",
131                                                    "Transmission already running alert -> title")];
132            [alert setInformativeText: NSLocalizedString(@"There is already a copy of Transmission running. "
133                "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message")];
134            [alert setAlertStyle: NSWarningAlertStyle];
135           
136            [alert runModal];
137            [alert release];
138           
139            //kill ourselves right away
140            exit(0);
141        }
142    }
143   
144    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
145        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
146   
147    //set custom value transformers
148    ActionMenuSpeedToDisplayLimitTransformer * limitTransformer =
149                        [[[ActionMenuSpeedToDisplayLimitTransformer alloc] init] autorelease];
150    [NSValueTransformer setValueTransformer: limitTransformer forName: @"ActionMenuSpeedToDisplayLimitTransformer"];
151   
152    ActionMenuRatioToDisplayRatioTransformer * ratioTransformer =
153                        [[[ActionMenuRatioToDisplayRatioTransformer alloc] init] autorelease];
154    [NSValueTransformer setValueTransformer: ratioTransformer forName: @"ActionMenuRatioToDisplayRatioTransformer"];
155   
156    ExpandedPathToPathTransformer * pathTransformer =
157                        [[[ExpandedPathToPathTransformer alloc] init] autorelease];
158    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
159   
160    ExpandedPathToIconTransformer * iconTransformer =
161                        [[[ExpandedPathToIconTransformer alloc] init] autorelease];
162    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
163   
164    SpeedLimitToTurtleIconTransformer * speedLimitIconTransformer =
165                        [[[SpeedLimitToTurtleIconTransformer alloc] init] autorelease];
166    [NSValueTransformer setValueTransformer: speedLimitIconTransformer forName: @"SpeedLimitToTurtleIconTransformer"];
167}
168
169- (id) init
170{
171    if ((self = [super init]))
172    {
173        fLib = tr_init("macosx");
174       
175        [NSApp setDelegate: self];
176       
177        fTorrents = [[NSMutableArray alloc] init];
178        fDisplayedTorrents = [[NSMutableArray alloc] init];
179       
180        fDefaults = [NSUserDefaults standardUserDefaults];
181       
182        fMessageController = [[MessageWindowController alloc] init];
183        fInfoController = [[InfoWindowController alloc] init];
184        fPrefsController = [[PrefsController alloc] initWithHandle: fLib];
185       
186        fBadger = [[Badger alloc] initWithLib: fLib];
187       
188        fIPCController = [[IPCController alloc] init];
189        [fIPCController setDelegate: self];
190        fRemoteQuit = NO;
191       
192        [GrowlApplicationBridge setGrowlDelegate: self];
193        [[UKKQueue sharedFileWatcher] setDelegate: self];
194    }
195    return self;
196}
197
198- (void) awakeFromNib
199{
200    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"Transmission Toolbar"];
201    [toolbar setDelegate: self];
202    [toolbar setAllowsUserCustomization: YES];
203    [toolbar setAutosavesConfiguration: YES];
204    [fWindow setToolbar: toolbar];
205    [toolbar release];
206   
207    [fWindow setDelegate: self]; //do manually to avoid placement issue
208   
209    [fWindow makeFirstResponder: fTableView];
210    [fWindow setExcludedFromWindowsMenu: YES];
211   
212    //set table size
213    if ([fDefaults boolForKey: @"SmallView"])
214        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
215   
216    //window min height
217    NSSize contentMinSize = [fWindow contentMinSize];
218    contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
219                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
220    [fWindow setContentMinSize: contentMinSize];
221   
222    //set info and filter keyboard shortcuts
223    unichar rightChar = NSRightArrowFunctionKey, leftChar = NSLeftArrowFunctionKey;
224    [fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & rightChar length: 1]];
225    [fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & leftChar length: 1]];
226   
227    [fNextFilterItem setKeyEquivalent: [NSString stringWithCharacters: & rightChar length: 1]];
228    [fNextFilterItem setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
229    [fPrevFilterItem setKeyEquivalent: [NSString stringWithCharacters: & leftChar length: 1]];
230    [fPrevFilterItem setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
231   
232    //set up filter bar
233    NSView * contentView = [fWindow contentView];
234    NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
235    [fFilterBar setHidden: YES];
236   
237    NSRect filterBarFrame = [fFilterBar frame];
238    filterBarFrame.size.width = windowSize.width;
239    [fFilterBar setFrame: filterBarFrame];
240   
241    [contentView addSubview: fFilterBar];
242    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
243
244    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
245   
246    //set up status bar
247    [fStatusBar setHidden: YES];
248   
249    NSRect statusBarFrame = [fStatusBar frame];
250    statusBarFrame.size.width = windowSize.width;
251    [fStatusBar setFrame: statusBarFrame];
252
253    [contentView addSubview: fStatusBar];
254    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
255    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
256
257    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
258                                "Main window -> 1st bottom left button (action) tooltip")];
259    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
260                                "Main window -> 2nd bottom left button (turtle) tooltip")];
261   
262    [fPrefsController setUpdater: fUpdater];
263   
264    [fTableView setTorrents: fDisplayedTorrents];
265    [[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell: [[TorrentCell alloc] init]];
266   
267    [fTableView registerForDraggedTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE]];
268    [fWindow registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType, NSURLPboardType, nil]];
269
270    //register for sleep notifications
271    IONotificationPortRef notify;
272    io_object_t iterator;
273    if ((fRootPort = IORegisterForSystemPower(self, & notify, sleepCallBack, & iterator)) != 0)
274        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
275    else
276        NSLog(@"Could not IORegisterForSystemPower");
277   
278    //load previous transfers
279    NSArray * history = [[NSArray alloc] initWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER]];
280   
281    //old version saved transfer info in prefs file
282    if (!history)
283    {
284        if ((history = [fDefaults arrayForKey: @"History"]))
285            [history retain];
286        [fDefaults removeObjectForKey: @"History"];
287    }
288   
289    if (history)
290    {
291        Torrent * torrent;
292        NSDictionary * historyItem;
293        NSEnumerator * enumerator = [history objectEnumerator];
294        while ((historyItem = [enumerator nextObject]))
295            if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
296            {
297                [fTorrents addObject: torrent];
298                [torrent release];
299            }
300       
301        [history release];
302    }
303   
304    //set filter
305    NSString * filterType = [fDefaults stringForKey: @"Filter"];
306   
307    NSButton * currentFilterButton;
308    if ([filterType isEqualToString: FILTER_PAUSE])
309        currentFilterButton = fPauseFilterButton;
310    else if ([filterType isEqualToString: FILTER_SEED])
311        currentFilterButton = fSeedFilterButton;
312    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
313        currentFilterButton = fDownloadFilterButton;
314    else
315    {
316        //safety
317        if (![filterType isEqualToString: FILTER_NONE])
318            [fDefaults setObject: FILTER_NONE forKey: @"Filter"];
319        currentFilterButton = fNoFilterButton;
320    }
321    [currentFilterButton setState: NSOnState];
322   
323    //set filter search type
324    NSString * filterSearchType = [fDefaults stringForKey: @"FilterSearchType"];
325   
326    NSMenu * filterSearchMenu = [[fSearchFilterField cell] searchMenuTemplate];
327    NSString * filterSearchTypeTitle;
328    if ([filterSearchType isEqualToString: FILTER_TYPE_TRACKER])
329        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_TRACKER] title];
330    else
331    {
332        //safety
333        if (![filterType isEqualToString: FILTER_TYPE_NAME])
334            [fDefaults setObject: FILTER_TYPE_NAME forKey: @"FilterSearchType"];
335        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_NAME] title];
336    }
337    [[fSearchFilterField cell] setPlaceholderString: filterSearchTypeTitle];
338   
339    //observe notifications
340    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
341   
342    [nc addObserver: self selector: @selector(updateUI)
343                    name: @"UpdateUI" object: nil];
344   
345    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
346                    name: @"TorrentFinishedDownloading" object: nil];
347   
348    [nc addObserver: self selector: @selector(torrentRestartedDownloading:)
349                    name: @"TorrentRestartedDownloading" object: nil];
350   
351    //avoids need of setting delegate
352    [nc addObserver: self selector: @selector(torrentTableViewSelectionDidChange:)
353                    name: NSTableViewSelectionDidChangeNotification object: fTableView];
354   
355    [nc addObserver: self selector: @selector(updateControlTint:)
356                    name: NSControlTintDidChangeNotification object: nil];
357   
358    [nc addObserver: self selector: @selector(prepareForUpdate:)
359                    name: SUUpdaterWillRestartNotification object: nil];
360    fUpdateInProgress = NO;
361   
362    [nc addObserver: self selector: @selector(autoSpeedLimitChange:)
363                    name: @"AutoSpeedLimitChange" object: nil];
364   
365    [nc addObserver: self selector: @selector(changeAutoImport)
366                    name: @"AutoImportSettingChange" object: nil];
367   
368    [nc addObserver: self selector: @selector(setWindowSizeToFit)
369                    name: @"AutoSizeSettingChange" object: nil];
370   
371    [nc addObserver: fWindow selector: @selector(makeKeyWindow)
372                    name: @"MakeWindowKey" object: nil];
373   
374    //check if torrent should now start
375    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
376                    name: @"TorrentStoppedForRatio" object: nil];
377   
378    [nc addObserver: self selector: @selector(updateTorrentsInQueue)
379                    name: @"UpdateQueue" object: nil];
380   
381    //open newly created torrent file
382    [nc addObserver: self selector: @selector(beginCreateFile:)
383                    name: @"BeginCreateTorrentFile" object: nil];
384   
385    //open newly created torrent file
386    [nc addObserver: self selector: @selector(openCreatedFile:)
387                    name: @"OpenCreatedTorrentFile" object: nil];
388
389    //timer to update the interface every second
390    [self updateUI];
391    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
392        selector: @selector(updateUI) userInfo: nil repeats: YES];
393    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
394    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
395   
396    [self applyFilter: nil];
397   
398    [fWindow makeKeyAndOrderFront: nil];
399   
400    if ([fDefaults boolForKey: @"InfoVisible"])
401        [self showInfo: nil];
402   
403    //timer to auto toggle speed limit
404    [self autoSpeedLimitChange: nil];
405    fSpeedLimitTimer = [NSTimer scheduledTimerWithTimeInterval: AUTO_SPEED_LIMIT_SECONDS target: self
406        selector: @selector(autoSpeedLimit) userInfo: nil repeats: YES];
407    [[NSRunLoop currentRunLoop] addTimer: fSpeedLimitTimer forMode: NSModalPanelRunLoopMode];
408    [[NSRunLoop currentRunLoop] addTimer: fSpeedLimitTimer forMode: NSEventTrackingRunLoopMode];
409}
410
411- (void) applicationDidFinishLaunching: (NSNotification *) notification
412{
413    [NSApp setServicesProvider: self];
414   
415    //register for dock icon drags
416    [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self
417        andSelector: @selector(handleOpenContentsEvent:replyEvent:)
418        forEventClass: kCoreEventClass andEventID: kAEOpenContents];
419   
420    //auto importing
421    [self checkAutoImportDirectory];
422   
423    //debug warning
424    if ([fDefaults boolForKey: @"WarningDebug"] && [fDefaults integerForKey: @"MessageLevel"] == TR_MSG_DBG)
425    {
426        NSAlert * alert = [[NSAlert alloc] init];
427        [alert setMessageText: NSLocalizedString(@"The Message Log is set to \"Debug\"", "Debug log alert -> message")];
428        [alert setInformativeText: NSLocalizedString(@"Continuous use at this level might increase memory usage."
429                                    " This setting can be changed in the Message Log window (accessible from the Window menu).",
430                                    "Debug log alert -> informative message")];
431        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Debug log alert -> button")];
432       
433        BOOL onLeopard = [NSApp isOnLeopardOrBetter];
434        if (onLeopard)
435            [alert setShowsSuppressionButton: YES];
436        else
437            [alert addButtonWithTitle: NSLocalizedString(@"Don't Alert Again", "Debug log alert -> button")];
438       
439        NSInteger result = [alert runModal];
440        if ((onLeopard ? [[alert suppressionButton] state] == NSOnState : result == NSAlertSecondButtonReturn))
441            [fDefaults setBool: NO forKey: @"WarningDebug"];
442        [alert release];
443    }
444}
445
446- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
447{
448    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
449        [fWindow makeKeyAndOrderFront: nil];
450    return NO;
451}
452
453- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
454{
455    if (!fUpdateInProgress && !fRemoteQuit && [fDefaults boolForKey: @"CheckQuit"])
456    {
457        int active = 0, downloading = 0;
458        Torrent * torrent;
459        NSEnumerator * enumerator = [fTorrents objectEnumerator];
460        while ((torrent = [enumerator nextObject]))
461            if ([torrent isActive])
462            {
463                active++;
464                if (![torrent allDownloaded])
465                    downloading++;
466            }
467       
468        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
469        {
470            NSString * message = active == 1
471                ? NSLocalizedString(@"There is an active transfer. Do you really want to quit?",
472                    "Confirm Quit panel -> message")
473                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers. Do you really want to quit?",
474                    "Confirm Quit panel -> message"), active];
475
476            NSBeginAlertSheet(NSLocalizedString(@"Confirm Quit", "Confirm Quit panel -> title"),
477                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
478                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
479                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
480            return NSTerminateLater;
481        }
482    }
483
484    return NSTerminateNow;
485}
486
487- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
488{
489    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
490}
491
492- (void) applicationWillTerminate: (NSNotification *) notification
493{
494    //stop timers and notification checking
495    [[NSNotificationCenter defaultCenter] removeObserver: self];
496   
497    [fTimer invalidate];
498    [fSpeedLimitTimer invalidate];
499    if (fAutoImportTimer)
500    {   
501        if ([fAutoImportTimer isValid])
502            [fAutoImportTimer invalidate];
503        [fAutoImportTimer release];
504    }
505   
506    //remove all torrent downloads
507    if (fPendingTorrentDownloads)
508    {
509        NSEnumerator * downloadEnumerator = [[fPendingTorrentDownloads allValues] objectEnumerator];
510        NSDictionary * downloadDict;
511        NSURLDownload * download;
512        while ((downloadDict = [downloadEnumerator nextObject]))
513        {
514            download = [downloadDict objectForKey: @"Download"];
515            [download cancel];
516            [download release];
517        }
518        [fPendingTorrentDownloads removeAllObjects];
519    }
520   
521    //remove all remaining torrent files in the temporary directory
522    if (fTempTorrentFiles)
523    {
524        NSEnumerator * torrentEnumerator = [fTempTorrentFiles objectEnumerator];
525        NSString * path;
526        while ((path = [torrentEnumerator nextObject]))
527            [[NSFileManager defaultManager] removeFileAtPath: path handler: nil];
528    }
529   
530    //remember window states and close all windows
531    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
532    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
533    [self showStatusBar: NO animate: NO];
534    [self showFilterBar: NO animate: NO];
535   
536    //save history
537    [self updateTorrentHistory];
538   
539    [fDisplayedTorrents removeAllObjects];
540    [fTorrents removeAllObjects];
541   
542    //clear badge
543    [fBadger clearBadge];
544   
545    //remaining calls the same as dealloc
546    [fInfoController release];
547    [fMessageController release];
548    [fPrefsController release];
549   
550    [fTorrents release];
551    [fDisplayedTorrents release];
552   
553    [fBadger release];
554    [fOverlayWindow release];
555    [fIPCController release];
556   
557    [fAutoImportedNames release];
558    [fPendingTorrentDownloads release];
559    [fTempTorrentFiles release];
560   
561    //complete cleanup
562    tr_close(fLib);
563}
564
565- (void) handleOpenContentsEvent: (NSAppleEventDescriptor *) event replyEvent: (NSAppleEventDescriptor *) replyEvent
566{
567    NSString * urlString = nil;
568
569    NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject];
570    if ([directObject descriptorType] == typeAEList)
571    {
572        unsigned i;
573        for (i = 1; i <= [directObject numberOfItems]; i++)
574            if ((urlString = [[directObject descriptorAtIndex: i] stringValue]))
575                break;
576    }
577    else
578        urlString = [directObject stringValue];
579   
580    if (urlString)
581        [self openURL: [[[NSURL alloc] initWithString: urlString] autorelease]];
582}
583
584- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) suggestedName
585{
586    if ([[suggestedName pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
587    {
588        [download cancel];
589       
590        NSRunAlertPanel(NSLocalizedString(@"Torrent download failed",
591            @"Download not a torrent -> title"), [NSString stringWithFormat:
592            NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.",
593            @"Download not a torrent -> message"), suggestedName,
594            [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]],
595            NSLocalizedString(@"OK", @"Download not a torrent -> button"), nil, nil);
596       
597        [download release];
598    }
599    else
600        [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: [suggestedName lastPathComponent]]
601                    allowOverwrite: NO];
602}
603
604-(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path
605{
606    if (!fPendingTorrentDownloads)
607        fPendingTorrentDownloads = [[NSMutableDictionary alloc] init];
608   
609    [fPendingTorrentDownloads setObject: [NSDictionary dictionaryWithObjectsAndKeys:
610                    path, @"Path", download, @"Download", nil] forKey: [[download request] URL]];
611}
612
613- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error
614{
615    NSRunAlertPanel(NSLocalizedString(@"Torrent download failed",
616        @"Torrent download error -> title"), [NSString stringWithFormat:
617        NSLocalizedString(@"The torrent could not be downloaded from %@ because an error occurred (%@).",
618        @"Torrent download failed -> message"),
619        [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
620        [error localizedDescription]], NSLocalizedString(@"OK", @"Torrent download failed -> button"), nil, nil);
621   
622    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
623    [download release];
624}
625
626- (void) downloadDidFinish: (NSURLDownload *) download
627{
628    NSString * path = [[fPendingTorrentDownloads objectForKey: [[download request] URL]] objectForKey: @"Path"];
629   
630    [self openFiles: [NSArray arrayWithObject: path] forcePath: nil ignoreDownloadFolder:
631        ![[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Constant"] deleteTorrentFile: TORRENT_FILE_DELETE];
632   
633    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
634    [download release];
635   
636    //delete temp torrent file on quit
637    if (!fTempTorrentFiles)
638        fTempTorrentFiles = [[NSMutableArray alloc] init];
639    [fTempTorrentFiles addObject: path];
640}
641
642- (void) application: (NSApplication *) app openFiles: (NSArray *) filenames
643{
644    [self openFiles: filenames forcePath: nil ignoreDownloadFolder: NO deleteTorrentFile: TORRENT_FILE_DEFAULT];
645}
646
647- (void) openFiles: (NSArray *) filenames forcePath: (NSString *) path ignoreDownloadFolder: (BOOL) ignore
648        deleteTorrentFile: (torrentFileState) deleteTorrent
649{
650    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"];
651    if (ignore || (!path && [downloadChoice isEqualToString: @"Ask"]))
652    {
653        [self openFilesAsk: [filenames mutableCopy] deleteTorrentFile: deleteTorrent];
654        return;
655    }
656   
657    #warning make submethod
658    if (!path && [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]
659        && access([[[fDefaults stringForKey: @"IncompleteDownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
660    {
661        NSOpenPanel * panel = [NSOpenPanel openPanel];
662       
663        [panel setPrompt: NSLocalizedString(@"Select", "Default incomplete folder cannot be used alert -> prompt")];
664        [panel setAllowsMultipleSelection: NO];
665        [panel setCanChooseFiles: NO];
666        [panel setCanChooseDirectories: YES];
667        [panel setCanCreateDirectories: YES];
668
669        [panel setMessage: NSLocalizedString(@"The incomplete folder cannot be used. Choose a new location or cancel for none.",
670                                        "Default incomplete folder cannot be used alert -> message")];
671       
672        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
673                                        filenames, @"Filenames",
674                                        [NSNumber numberWithBool: ignore], @"Ignore",
675                                        [NSNumber numberWithInt: deleteTorrent], @"DeleteTorrent", nil];
676       
677        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
678                didEndSelector: @selector(incompleteChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
679        return;
680    }
681    if (!path && [downloadChoice isEqualToString: @"Constant"]
682        && access([[[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
683    {
684        NSOpenPanel * panel = [NSOpenPanel openPanel];
685       
686        [panel setPrompt: NSLocalizedString(@"Select", "Default folder cannot be used alert -> prompt")];
687        [panel setAllowsMultipleSelection: NO];
688        [panel setCanChooseFiles: NO];
689        [panel setCanChooseDirectories: YES];
690        [panel setCanCreateDirectories: YES];
691
692        [panel setMessage: NSLocalizedString(@"The download folder cannot be used. Choose a new location.",
693                                        "Default folder cannot be used alert -> message")];
694       
695        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
696                                        filenames, @"Filenames",
697                                        [NSNumber numberWithBool: ignore], @"Ignore",
698                                        [NSNumber numberWithInt: deleteTorrent], @"DeleteTorrent", nil];
699       
700        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
701                didEndSelector: @selector(downloadChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
702        return;
703    }
704   
705    Torrent * torrent;
706    NSString * torrentPath;
707    tr_info info;
708    NSEnumerator * enumerator = [filenames objectEnumerator];
709    while ((torrentPath = [enumerator nextObject]))
710    {
711        NSString * location;
712        if (path)
713            location = path;
714        else if ([downloadChoice isEqualToString: @"Constant"])
715            location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
716        else
717            location = [torrentPath stringByDeletingLastPathComponent];
718       
719        if (tr_torrentParse(fLib, [torrentPath UTF8String], NULL, &info) == TR_EDUPLICATE)
720        {
721            [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
722            tr_metainfoFree(&info);
723            continue;
724        }
725        tr_metainfoFree(&info);
726       
727        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath location: location deleteTorrentFile: deleteTorrent lib: fLib]))
728            continue;
729       
730        //add it to the "File > Open Recent" menu
731        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
732       
733        [torrent update];
734        [fTorrents addObject: torrent];
735        [torrent release];
736    }
737
738    [self updateTorrentsInQueue];
739}
740
741- (void) openCreatedFile: (NSNotification *) notification
742{
743    NSDictionary * dict = [notification userInfo];
744    [self openFiles: [NSArray arrayWithObject: [dict objectForKey: @"File"]] forcePath: [dict objectForKey: @"Path"]
745            ignoreDownloadFolder: NO deleteTorrentFile: TORRENT_FILE_SAVE];
746    [dict release];
747}
748
749- (void) incompleteChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (NSDictionary *) dictionary
750{
751    if (code == NSOKButton)
752        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
753    else
754        [fDefaults setBool: NO forKey: @"UseIncompleteDownloadFolder"];
755   
756    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
757}
758
759- (void) downloadChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (NSDictionary *) dictionary
760{
761    if (code == NSOKButton)
762    {
763        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"DownloadFolder"];
764        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
765    }
766    else
767        [dictionary release];
768}
769
770- (void) openFilesWithDict: (NSDictionary *) dictionary
771{
772    [self openFiles: [dictionary objectForKey: @"Filenames"] forcePath: nil
773        ignoreDownloadFolder: [[dictionary objectForKey: @"Ignore"] boolValue]
774        deleteTorrentFile: [[dictionary objectForKey: @"DeleteTorrent"] intValue]];
775   
776    [dictionary release];
777}
778
779//called by the main open method to show sheet for choosing download location
780- (void) openFilesAsk: (NSMutableArray *) files deleteTorrentFile: (torrentFileState) deleteTorrent
781{
782    //determine the next file that can be opened
783    NSString * torrentPath;
784    int canAdd;
785    tr_info info;
786    while ([files count] > 0)
787    {
788        torrentPath = [[files objectAtIndex: 0] retain];
789        canAdd = tr_torrentParse(fLib, [torrentPath UTF8String], NULL, &info);
790        if (canAdd == TR_OK)
791            break;
792        else if (canAdd == TR_EDUPLICATE)
793            [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
794        else;
795       
796        tr_metainfoFree(&info);
797        [files removeObjectAtIndex: 0];
798    }
799   
800    //no files left to open
801    if ([files count] <= 0)
802    {
803        [files release];
804        [self updateTorrentHistory];
805        return;
806    }
807   
808    [files removeObjectAtIndex: 0];
809   
810    NSOpenPanel * panel = [NSOpenPanel openPanel];
811
812    [panel setPrompt: NSLocalizedString(@"Select", "Open torrent -> prompt")];
813    [panel setAllowsMultipleSelection: NO];
814    [panel setCanChooseFiles: NO];
815    [panel setCanChooseDirectories: YES];
816    [panel setCanCreateDirectories: YES];
817   
818    [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
819                        "Open torrent -> select destination folder"), [NSString stringWithUTF8String: info.name]]];
820    tr_metainfoFree(&info);
821   
822    NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: torrentPath, @"Path",
823                                    files, @"Files", [NSNumber numberWithInt: deleteTorrent], @"DeleteTorrent", nil];
824    [torrentPath release];
825   
826    [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
827            didEndSelector: @selector(folderChoiceClosed:returnCode:contextInfo:) contextInfo: dictionary];
828}
829
830- (void) folderChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (NSDictionary *) dictionary
831{
832    if (code == NSOKButton)
833    {
834        NSString * torrentPath = [dictionary objectForKey: @"Path"];
835        Torrent * torrent = [[Torrent alloc] initWithPath: torrentPath location: [[openPanel filenames] objectAtIndex: 0]
836                            deleteTorrentFile: [[dictionary objectForKey: @"DeleteTorrent"] intValue] lib: fLib];
837       
838        //add it to the "File > Open Recent" menu
839        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
840       
841        [torrent update];
842        [fTorrents addObject: torrent];
843        [torrent release];
844       
845        [self updateTorrentsInQueue];
846    }
847   
848    [self performSelectorOnMainThread: @selector(openFilesAskWithDict:) withObject: dictionary waitUntilDone: NO];
849}
850
851- (void) openFilesAskWithDict: (NSDictionary *) dictionary
852{
853    [self openFilesAsk: [dictionary objectForKey: @"Files"]
854            deleteTorrentFile: [[dictionary objectForKey: @"DeleteTorrent"] intValue]];
855    [dictionary release];
856}
857
858//called on by applescript
859- (void) open: (NSArray *) files
860{
861    [self performSelectorOnMainThread: @selector(openFiles:) withObject: files waitUntilDone: NO];
862}
863
864- (void) openFiles: (NSArray *) filenames
865{
866    [self openFiles: filenames forcePath: nil ignoreDownloadFolder: NO deleteTorrentFile: TORRENT_FILE_DEFAULT];
867}
868
869- (void) openShowSheet: (id) sender
870{
871    NSOpenPanel * panel = [NSOpenPanel openPanel];
872
873    [panel setAllowsMultipleSelection: YES];
874    [panel setCanChooseFiles: YES];
875    [panel setCanChooseDirectories: NO];
876
877    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
878        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
879        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
880}
881
882- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSNumber *) ignore
883{
884    if (code == NSOKButton)
885    {
886        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
887                                        [panel filenames], @"Files", ignore, @"Ignore", nil];
888        [self performSelectorOnMainThread: @selector(openFromSheet:) withObject: dictionary waitUntilDone: NO];
889    }
890}
891
892- (void) openFromSheet: (NSDictionary *) dictionary
893{
894    [self openFiles: [dictionary objectForKey: @"Files"] forcePath: nil
895        ignoreDownloadFolder: [[dictionary objectForKey: @"Ignore"] boolValue] deleteTorrentFile: TORRENT_FILE_DEFAULT];
896   
897    [dictionary release];
898}
899
900- (void) duplicateOpenAlert: (NSString *) name
901{
902    if (![fDefaults boolForKey: @"WarningDuplicate"])
903        return;
904   
905    NSAlert * alert = [[NSAlert alloc] init];
906    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" is already running.",
907                            "Open duplicate alert -> title"), name]];
908    [alert setInformativeText:
909            NSLocalizedString(@"The torrent file cannot be opened because it is a duplicate of an already running transfer.",
910                            "Open duplicate alert -> message")];
911    [alert setAlertStyle: NSWarningAlertStyle];
912    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate alert -> button")];
913   
914    BOOL onLeopard = [NSApp isOnLeopardOrBetter];
915    if (onLeopard)
916        [alert setShowsSuppressionButton: YES];
917    else
918        [alert addButtonWithTitle: NSLocalizedString(@"Don't Alert Again", "Open duplicate alert -> button")];
919   
920    NSInteger result = [alert runModal];
921    if ((onLeopard ? [[alert suppressionButton] state] == NSOnState : result == NSAlertSecondButtonReturn))
922        [fDefaults setBool: NO forKey: @"WarningDuplicate"];
923    [alert release];
924}
925
926- (void) openURL: (NSURL *) url
927{
928    [[NSURLDownload alloc] initWithRequest: [NSURLRequest requestWithURL: url] delegate: self];
929}
930
931- (void) openURLShowSheet: (id) sender
932{
933    [NSApp beginSheet: fURLSheetWindow modalForWindow: fWindow modalDelegate: self
934            didEndSelector: @selector(urlSheetDidEnd:returnCode:contextInfo:) contextInfo: nil];
935}
936
937- (void) openURLEndSheet: (id) sender
938{
939    [fURLSheetWindow orderOut: sender];
940    [NSApp endSheet: fURLSheetWindow returnCode: 1];
941}
942
943- (void) openURLCancelEndSheet: (id) sender
944{
945    [fURLSheetWindow orderOut: sender];
946    [NSApp endSheet: fURLSheetWindow returnCode: 0];
947}
948
949- (void) urlSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
950{
951    [fURLSheetTextField selectText: self];
952    if (returnCode != 1)
953        return;
954   
955    NSString * urlString = [fURLSheetTextField stringValue];
956    if (![urlString isEqualToString: @""])
957    {
958        if ([urlString rangeOfString: @"://"].location == NSNotFound)
959        {
960            if ([urlString rangeOfString: @"."].location == NSNotFound)
961            {
962                int beforeCom;
963                if ((beforeCom = [urlString rangeOfString: @"/"].location) != NSNotFound)
964                    urlString = [NSString stringWithFormat: @"http://www.%@.com/%@",
965                                    [urlString substringToIndex: beforeCom],
966                                    [urlString substringFromIndex: beforeCom + 1]];
967                else
968                    urlString = [NSString stringWithFormat: @"http://www.%@.com", urlString];
969            }
970            else
971                urlString = [@"http://" stringByAppendingString: urlString];
972        }
973       
974        NSURL * url = [NSURL URLWithString: urlString];
975        [self performSelectorOnMainThread: @selector(openURL:) withObject: url waitUntilDone: NO];
976    }
977}
978
979- (void) createFile: (id) sender
980{
981    [CreatorWindowController createTorrentFile: fLib];
982}
983
984- (void) resumeSelectedTorrents: (id) sender
985{
986    [self resumeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
987}
988
989- (void) resumeAllTorrents: (id) sender
990{
991    [self resumeTorrents: fTorrents];
992}
993
994- (void) resumeTorrents: (NSArray *) torrents
995{
996    NSEnumerator * enumerator = [torrents objectEnumerator];
997    Torrent * torrent;
998    while ((torrent = [enumerator nextObject]))
999        [torrent setWaitToStart: YES];
1000   
1001    [self updateTorrentsInQueue];
1002}
1003
1004- (void) resumeSelectedTorrentsNoWait:  (id) sender
1005{
1006    [self resumeTorrentsNoWait: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
1007}
1008
1009- (void) resumeWaitingTorrents: (id) sender
1010{
1011    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1012   
1013    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1014    Torrent * torrent;
1015    while ((torrent = [enumerator nextObject]))
1016        if (![torrent isActive] && [torrent waitingToStart])
1017            [torrents addObject: torrent];
1018   
1019    [self resumeTorrentsNoWait: torrents];
1020}
1021
1022- (void) resumeTorrentsNoWait: (NSArray *) torrents
1023{
1024    //iterate through instead of all at once to ensure no conflicts
1025    NSEnumerator * enumerator = [torrents objectEnumerator];
1026    Torrent * torrent;
1027    while ((torrent = [enumerator nextObject]))
1028        [torrent startTransfer];
1029   
1030    [self updateUI];
1031    [self applyFilter: nil];
1032    [self updateTorrentHistory];
1033}
1034
1035- (void) stopSelectedTorrents: (id) sender
1036{
1037    [self stopTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
1038}
1039
1040- (void) stopAllTorrents: (id) sender
1041{
1042    [self stopTorrents: fTorrents];
1043}
1044
1045- (void) stopTorrents: (NSArray *) torrents
1046{
1047    //don't want any of these starting then stopping
1048    NSEnumerator * enumerator = [torrents objectEnumerator];
1049    Torrent * torrent;
1050    while ((torrent = [enumerator nextObject]))
1051        [torrent setWaitToStart: NO];
1052
1053    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
1054   
1055    [self updateUI];
1056    [self applyFilter: nil];
1057    [self updateTorrentHistory];
1058}
1059
1060- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
1061{
1062    [torrents retain];
1063    int active = 0, downloading = 0;
1064
1065    if ([fDefaults boolForKey: @"CheckRemove"])
1066    {
1067        Torrent * torrent;
1068        NSEnumerator * enumerator = [torrents objectEnumerator];
1069        while ((torrent = [enumerator nextObject]))
1070            if ([torrent isActive])
1071            {
1072                active++;
1073                if (![torrent isSeeding])
1074                    downloading++;
1075            }
1076
1077        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
1078        {
1079            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
1080                torrents, @"Torrents",
1081                [NSNumber numberWithBool: deleteData], @"DeleteData",
1082                [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
1083
1084            NSString * title, * message;
1085           
1086            int selected = [fTableView numberOfSelectedRows];
1087            if (selected == 1)
1088            {
1089                NSString * torrentName = [[fDisplayedTorrents objectAtIndex: [fTableView selectedRow]] name];
1090               
1091                if (!deleteData && !deleteTorrent)
1092                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of \"%@\" from the transfer list.",
1093                                "Removal confirm panel -> title"), torrentName];
1094                else if (deleteData && !deleteTorrent)
1095                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of \"%@\" from the transfer list"
1096                                " and trash data file.", "Removal confirm panel -> title"), torrentName];
1097                else if (!deleteData && deleteTorrent)
1098                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of \"%@\" from the transfer list"
1099                                " and trash torrent file.", "Removal confirm panel -> title"), torrentName];
1100                else
1101                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of \"%@\" from the transfer list"
1102                            " and trash both data and torrent files.", "Removal confirm panel -> title"), torrentName];
1103               
1104                message = NSLocalizedString(@"This transfer is active."
1105                            " Once removed, continuing the transfer will require the torrent file.",
1106                            "Removal confirm panel -> message");
1107            }
1108            else
1109            {
1110                if (!deleteData && !deleteTorrent)
1111                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of %d transfers"
1112                                " from the transfer list.", "Removal confirm panel -> title"), selected];
1113                else if (deleteData && !deleteTorrent)
1114                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of %d transfers"
1115                                " from the transfer list and trash data file.", "Removal confirm panel -> title"), selected];
1116                else if (!deleteData && deleteTorrent)
1117                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of %d transfers"
1118                                " from the transfer list and trash torrent file.", "Removal confirm panel -> title"), selected];
1119                else
1120                    title = [NSString stringWithFormat: NSLocalizedString(@"Confirm removal of %d transfers"
1121                                " from the transfer list and trash both data and torrent files.",
1122                                "Removal confirm panel -> title"), selected];
1123               
1124                if (selected == active)
1125                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
1126                                "Removal confirm panel -> message part 1"), active];
1127                else
1128                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
1129                                "Removal confirm panel -> message part 1"), selected, active];
1130                message = [message stringByAppendingString:
1131                    NSLocalizedString(@" Once removed, continuing the transfers will require the torrent files.",
1132                                "Removal confirm panel -> message part 2")];
1133            }
1134
1135            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
1136                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
1137                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
1138            return;
1139        }
1140    }
1141   
1142    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
1143}
1144
1145- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (NSDictionary *) dict
1146{
1147    NSArray * torrents = [dict objectForKey: @"Torrents"];
1148    BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue],
1149        deleteTorrent = [[dict objectForKey: @"DeleteTorrent"] boolValue];
1150    [dict release];
1151   
1152    if (returnCode == NSAlertDefaultReturn)
1153        [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
1154    else
1155        [torrents release];
1156}
1157
1158- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
1159{
1160    //don't want any of these starting then stopping
1161    NSEnumerator * enumerator = [torrents objectEnumerator];
1162    Torrent * torrent;
1163    while ((torrent = [enumerator nextObject]))
1164        [torrent setWaitToStart: NO];
1165
1166    NSNumber * lowestOrderValue = nil, * currentOrderValue;
1167
1168    enumerator = [torrents objectEnumerator];
1169    while ((torrent = [enumerator nextObject]))
1170    {
1171        [torrent stopTransfer];
1172
1173        if (deleteData)
1174            [torrent trashData];
1175        if (deleteTorrent)
1176            [torrent trashTorrent];
1177       
1178        //determine lowest order value
1179        currentOrderValue = [torrent orderValue];
1180        if (!lowestOrderValue || [lowestOrderValue compare: currentOrderValue] == NSOrderedDescending)
1181            lowestOrderValue = currentOrderValue;
1182       
1183        [torrent closeRemoveTorrent];
1184        [fTorrents removeObject: torrent];
1185        [fDisplayedTorrents removeObject: torrent];
1186    }
1187    [torrents release];
1188
1189    //reset the order values if necessary
1190    if ([lowestOrderValue intValue] < [fTorrents count])
1191    {
1192        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1193                                                @"orderValue" ascending: YES] autorelease];
1194        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1195
1196        NSArray * tempTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
1197        [descriptors release];
1198
1199        int i;
1200        for (i = [lowestOrderValue intValue]; i < [tempTorrents count]; i++)
1201            [[tempTorrents objectAtIndex: i] setOrderValue: i];
1202    }
1203   
1204    [fTableView deselectAll: nil];
1205   
1206    [self updateUI];
1207    [self applyFilter: nil];
1208    [self updateTorrentHistory];
1209}
1210
1211- (void) removeNoDelete: (id) sender
1212{
1213    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
1214                deleteData: NO deleteTorrent: NO];
1215}
1216
1217- (void) removeDeleteData: (id) sender
1218{
1219    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
1220                deleteData: YES deleteTorrent: NO];
1221}
1222
1223- (void) removeDeleteTorrent: (id) sender
1224{
1225    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
1226                deleteData: NO deleteTorrent: YES];
1227}
1228
1229- (void) removeDeleteDataAndTorrent: (id) sender
1230{
1231    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
1232                deleteData: YES deleteTorrent: YES];
1233}
1234
1235- (void) moveDataFiles: (id) sender
1236{
1237    NSOpenPanel * panel = [NSOpenPanel openPanel];
1238    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1239    [panel setAllowsMultipleSelection: NO];
1240    [panel setCanChooseFiles: NO];
1241    [panel setCanChooseDirectories: YES];
1242    [panel setCanCreateDirectories: YES];
1243   
1244    NSArray * torrents = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] retain];
1245    int count = [torrents count];
1246    if (count == 1)
1247        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1248                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1249    else
1250        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1251                            "Move torrent -> select destination folder"), count]];
1252       
1253    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1254        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1255}
1256
1257- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSArray *) torrents
1258{
1259    if (code == NSOKButton)
1260    {
1261        NSEnumerator * enumerator = [torrents objectEnumerator];
1262        Torrent * torrent;
1263        while ((torrent = [enumerator nextObject]))
1264            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1265    }
1266   
1267    [torrents release];
1268}
1269
1270- (void) copyTorrentFiles: (id) sender
1271{
1272    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
1273            [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]]];
1274}
1275
1276- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1277{
1278    if ([torrents count] <= 0)
1279    {
1280        [torrents release];
1281        return;
1282    }
1283
1284    Torrent * torrent = [torrents objectAtIndex: 0];
1285
1286    //warn user if torrent file can't be found
1287    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1288    {
1289        NSAlert * alert = [[NSAlert alloc] init];
1290        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1291        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1292                                "Torrent file copy alert -> title"), [torrent name]]];
1293        [alert setInformativeText: [NSString stringWithFormat:
1294                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1295                                    [torrent torrentLocation]]];
1296        [alert setAlertStyle: NSWarningAlertStyle];
1297       
1298        [alert runModal];
1299        [alert release];
1300       
1301        [torrents removeObjectAtIndex: 0];
1302        [self copyTorrentFileForTorrents: torrents];
1303    }
1304    else
1305    {
1306        NSSavePanel * panel = [NSSavePanel savePanel];
1307        [panel setRequiredFileType: @"torrent"];
1308        [panel setCanSelectHiddenExtension: YES];
1309       
1310        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1311            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1312    }
1313}
1314
1315- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (NSMutableArray *) torrents
1316{
1317    //copy torrent to new location with name of data file
1318    if (code == NSOKButton)
1319        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1320   
1321    [torrents removeObjectAtIndex: 0];
1322    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1323}
1324
1325- (void) revealFile: (id) sender
1326{
1327    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
1328    Torrent * torrent;
1329    while ((torrent = [enumerator nextObject]))
1330        [torrent revealData];
1331}
1332
1333- (void) announceSelectedTorrents: (id) sender
1334{
1335    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
1336    Torrent * torrent;
1337    while ((torrent = [enumerator nextObject]))
1338    {
1339        if ([torrent canManualAnnounce])
1340            [torrent manualAnnounce];
1341    }
1342}
1343
1344- (void) resetCacheForSelectedTorrents: (id) sender
1345{
1346    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
1347    Torrent * torrent;
1348    while ((torrent = [enumerator nextObject]))
1349        [torrent resetCache];
1350   
1351    [self applyFilter: nil];
1352}
1353
1354- (void) showPreferenceWindow: (id) sender
1355{
1356    NSWindow * window = [fPrefsController window];
1357    if (![window isVisible])
1358        [window center];
1359
1360    [window makeKeyAndOrderFront: nil];
1361}
1362
1363- (void) showAboutWindow: (id) sender
1364{
1365    [[AboutWindowController aboutController] showWindow: nil];
1366}
1367
1368- (void) showInfo: (id) sender
1369{
1370    if ([[fInfoController window] isVisible])
1371        [fInfoController close];
1372    else
1373    {
1374        [fInfoController updateInfoStats];
1375        [[fInfoController window] orderFront: nil];
1376    }
1377}
1378
1379- (void) setInfoTab: (id) sender
1380{
1381    if (sender == fNextInfoTabItem)
1382        [fInfoController setNextTab];
1383    else
1384        [fInfoController setPreviousTab];
1385}
1386
1387- (void) showMessageWindow: (id) sender
1388{
1389    [fMessageController showWindow: nil];
1390}
1391
1392- (void) updateUI
1393{
1394    [fTorrents makeObjectsPerformSelector: @selector(update)];
1395   
1396    if (![NSApp isHidden])
1397    {
1398        if ([fWindow isVisible])
1399        {
1400            //resort if necessary or just update the table
1401            NSString * sortType = [fDefaults stringForKey: @"Sort"];
1402            if ([sortType isEqualToString: SORT_PROGRESS] || [sortType isEqualToString: SORT_STATE]
1403                    || [sortType isEqualToString: SORT_TRACKER])
1404                [self sortTorrents];
1405            else
1406                [fTableView reloadData];
1407           
1408            //update the global DL/UL rates
1409            if (![fStatusBar isHidden])
1410            {
1411                float downloadRate, uploadRate;
1412                tr_torrentRates(fLib, & downloadRate, & uploadRate);
1413               
1414                [fTotalDLField setStringValue: [NSLocalizedString(@"Total DL: ", "Status bar -> total download")
1415                                                stringByAppendingString: [NSString stringForSpeed: downloadRate]]];
1416                [fTotalULField setStringValue: [NSLocalizedString(@"Total UL: ", "Status bar -> total upload")
1417                                                stringByAppendingString: [NSString stringForSpeed: uploadRate]]];
1418            }
1419        }
1420
1421        //update non-constant parts of info window
1422        if ([[fInfoController window] isVisible])
1423            [fInfoController updateInfoStats];
1424    }
1425   
1426    //badge dock
1427    [fBadger updateBadge];
1428}
1429
1430- (void) updateTorrentsInQueue
1431{
1432    BOOL download = [fDefaults boolForKey: @"Queue"],
1433        seed = [fDefaults boolForKey: @"QueueSeed"];
1434   
1435    int desiredDownloadActive = [self numToStartFromQueue: YES],
1436        desiredSeedActive = [self numToStartFromQueue: NO];
1437   
1438    //sort torrents by order value
1439    NSArray * sortedTorrents;
1440    if ([fTorrents count] > 1 && (desiredDownloadActive > 0 || desiredSeedActive > 0))
1441    {
1442        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1443                                                @"orderValue" ascending: YES] autorelease];
1444        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1445       
1446        sortedTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
1447        [descriptors release];
1448    }
1449    else
1450        sortedTorrents = fTorrents;
1451
1452    Torrent * torrent;
1453    NSEnumerator * enumerator = [sortedTorrents objectEnumerator];
1454    while ((torrent = [enumerator nextObject]))
1455    {
1456        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1457        {
1458            if (![torrent allDownloaded])
1459            {
1460                if (!download || desiredDownloadActive > 0)
1461                {
1462                    [torrent startTransfer];
1463                    if ([torrent isActive])
1464                        desiredDownloadActive--;
1465                    [torrent update];
1466                }
1467            }
1468            else
1469            {
1470                if (!seed || desiredSeedActive > 0)
1471                {
1472                    [torrent startTransfer];
1473                    if ([torrent isActive])
1474                        desiredSeedActive--;
1475                    [torrent update];
1476                }
1477            }
1478        }
1479    }
1480   
1481    [self updateUI];
1482    [self applyFilter: nil];
1483    [self updateTorrentHistory];
1484}
1485
1486- (int) numToStartFromQueue: (BOOL) downloadQueue
1487{
1488    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1489        return 0;
1490   
1491    int desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1492       
1493    Torrent * torrent;
1494    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1495    while ((torrent = [enumerator nextObject]))
1496    {
1497        if ([torrent isChecking])
1498        {
1499            desired--;
1500            if (desired <= 0)
1501                return 0;
1502        }
1503        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1504        {
1505            if ([torrent allDownloaded] != downloadQueue)
1506            {
1507                desired--;
1508                if (desired <= 0)
1509                    return 0;
1510            }
1511        }
1512        else;
1513    }
1514   
1515    return desired;
1516}
1517
1518- (void) torrentFinishedDownloading: (NSNotification *) notification
1519{
1520    Torrent * torrent = [notification object];
1521    if ([torrent isActive])
1522    {
1523        if ([fDefaults boolForKey: @"PlayDownloadSound"])
1524        {
1525            NSSound * sound;
1526            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1527                [sound play];
1528        }
1529       
1530        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1531                                        [torrent dataLocation] , @"Location", nil];
1532        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1533                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1534                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1535       
1536        if (![fWindow isMainWindow])
1537            [fBadger incrementCompleted];
1538       
1539        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1540        {
1541            [torrent stopTransfer];
1542            [torrent setWaitToStart: YES];
1543        }
1544    }
1545   
1546    [self updateTorrentsInQueue];
1547}
1548
1549- (void) torrentRestartedDownloading: (NSNotification *) notification
1550{
1551    Torrent * torrent = [notification object];
1552    if ([torrent isActive])
1553    {
1554        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1555        {
1556            [torrent stopTransfer];
1557            [torrent setWaitToStart: YES];
1558        }
1559    }
1560   
1561    [self updateTorrentsInQueue];
1562}
1563
1564- (void) updateTorrentHistory
1565{
1566    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1567
1568    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1569    Torrent * torrent;
1570    while ((torrent = [enumerator nextObject]))
1571        [history addObject: [torrent history]];
1572
1573    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER] atomically: YES];
1574}
1575
1576- (void) sortTorrents
1577{
1578    //remember selected rows if needed
1579    NSArray * selectedTorrents = nil;
1580    int numSelected = [fTableView numberOfSelectedRows];
1581    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1582        selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1583
1584    [self sortTorrentsIgnoreSelected]; //actually sort
1585   
1586    //set selected rows if needed
1587    if (selectedTorrents)
1588    {
1589        Torrent * torrent;
1590        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1591        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1592        while ((torrent = [enumerator nextObject]))
1593            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1594       
1595        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1596        [indexSet release];
1597    }
1598}
1599
1600//doesn't remember selected rows
1601- (void) sortTorrentsIgnoreSelected
1602{
1603    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1604    BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1605   
1606    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1607                                            ascending: asc selector: @selector(caseInsensitiveCompare:)] autorelease],
1608                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1609                                            ascending: asc] autorelease];
1610   
1611    NSArray * descriptors;
1612    if ([sortType isEqualToString: SORT_NAME])
1613        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1614    else if ([sortType isEqualToString: SORT_STATE])
1615    {
1616        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1617                                                @"stateSortKey" ascending: !asc] autorelease],
1618                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1619                                            @"progressSortKey" ascending: !asc] autorelease],
1620                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1621                                            @"ratioSortKey" ascending: !asc] autorelease];
1622       
1623        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1624                                                            nameDescriptor, orderDescriptor, nil];
1625    }
1626    else if ([sortType isEqualToString: SORT_PROGRESS])
1627    {
1628        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1629                                            @"progressSortKey" ascending: asc] autorelease],
1630                        * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1631                                            @"ratioProgressSortKey" ascending: asc] autorelease],
1632                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1633                                            @"ratioSortKey" ascending: asc] autorelease];
1634       
1635        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1636                                                            nameDescriptor, orderDescriptor, nil];
1637    }
1638    else if ([sortType isEqualToString: SORT_TRACKER])
1639    {
1640        NSSortDescriptor * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddress"
1641                                                ascending: asc selector: @selector(caseInsensitiveCompare:)] autorelease];
1642       
1643        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, orderDescriptor, nil];
1644    }
1645    else if ([sortType isEqualToString: SORT_ORDER])
1646        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1647    else
1648    {
1649        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1650   
1651        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1652    }
1653
1654    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1655    [descriptors release];
1656   
1657    [fTableView reloadData];
1658}
1659
1660- (void) setSort: (id) sender
1661{
1662    NSString * sortType;
1663    switch ([sender tag])
1664    {
1665        case SORT_ORDER_TAG:
1666            sortType = SORT_ORDER;
1667            [fDefaults setBool: NO forKey: @"SortReverse"];
1668            break;
1669           
1670        case SORT_DATE_TAG:
1671            sortType = SORT_DATE;
1672            break;
1673       
1674        case SORT_NAME_TAG:
1675            sortType = SORT_NAME;
1676            break;
1677       
1678        case SORT_PROGRESS_TAG:
1679            sortType = SORT_PROGRESS;
1680            break;
1681       
1682        case SORT_STATE_TAG:
1683            sortType = SORT_STATE;
1684            break;
1685       
1686        case SORT_TRACKER_TAG:
1687            sortType = SORT_TRACKER;
1688            break;
1689       
1690        default:
1691            return;
1692    }
1693   
1694    [fDefaults setObject: sortType forKey: @"Sort"];
1695    [self sortTorrents];
1696}
1697
1698- (void) setSortReverse: (id) sender
1699{
1700    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1701    [self sortTorrents];
1702}
1703
1704- (void) applyFilter: (id) sender
1705{
1706    //remember selected rows if needed
1707    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1708                ? [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1709
1710    NSMutableArray * tempTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1711   
1712    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1713   
1714    int downloading = 0, seeding = 0, paused = 0;
1715    BOOL isDownload = [filterType isEqualToString: FILTER_DOWNLOAD],
1716            isSeed = [filterType isEqualToString: FILTER_SEED],
1717            isPause = [filterType isEqualToString: FILTER_PAUSE];
1718    BOOL filtering = isDownload || isSeed || isPause;
1719   
1720    //get count of each type
1721    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1722    Torrent * torrent;
1723    while ((torrent = [enumerator nextObject]))
1724    {
1725        if ([torrent isActive])
1726        {
1727            if ([torrent isSeeding])
1728            {
1729                seeding++;
1730                if (isSeed)
1731                    [tempTorrents addObject: torrent];
1732            }
1733            else
1734            {
1735                downloading++;
1736                if (isDownload)
1737                    [tempTorrents addObject: torrent];
1738            }
1739        }
1740        else
1741        {
1742            paused++;
1743            if (isPause)
1744                [tempTorrents addObject: torrent];
1745        }
1746    }
1747   
1748    if (!filtering)
1749        [tempTorrents setArray: fTorrents];
1750   
1751    //set button tooltips
1752    [fNoFilterButton setCount: [fTorrents count]];
1753    [fDownloadFilterButton setCount: downloading];
1754    [fSeedFilterButton setCount: seeding];
1755    [fPauseFilterButton setCount: paused];
1756   
1757    NSString * searchString = [fSearchFilterField stringValue];
1758    if ([searchString length] > 0)
1759    {
1760        filtering = YES;
1761       
1762        Torrent * torrent;
1763        BOOL filterTracker = [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER], remove;
1764       
1765        int i;
1766        for (i = [tempTorrents count]-1; i >= 0; i--)
1767        {
1768            torrent = [tempTorrents objectAtIndex: i];
1769            remove = YES;
1770           
1771            if (filterTracker)
1772            {
1773                NSEnumerator * trackerEnumerator = [[torrent allTrackers] objectEnumerator], * subTrackerEnumerator;
1774                NSArray * subTrackers;
1775                NSString * tracker;
1776                while (remove && (subTrackers = [trackerEnumerator nextObject]))
1777                {
1778                    subTrackerEnumerator = [subTrackers objectEnumerator];
1779                    while ((tracker = [subTrackerEnumerator nextObject]))
1780                    {
1781                        if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1782                        {
1783                            remove = NO;
1784                            break;
1785                        }
1786                    }
1787                }
1788            }
1789            else
1790                remove = [[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound;
1791           
1792            if (remove)
1793                [tempTorrents removeObjectAtIndex: i];
1794        }
1795    }
1796   
1797    [fDisplayedTorrents setArray: tempTorrents];
1798   
1799    [self sortTorrentsIgnoreSelected];
1800   
1801    //set selected rows if needed
1802    if (selectedTorrents)
1803    {
1804        Torrent * torrent;
1805        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1806        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1807        unsigned index;
1808        while ((torrent = [enumerator nextObject]))
1809            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1810                [indexSet addIndex: index];
1811       
1812        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1813        [indexSet release];
1814    }
1815   
1816    //set status bar torrent count text
1817    NSMutableString * totalTorrentsString = [[NSMutableString alloc] initWithString: @""];
1818    if (filtering)
1819        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1820   
1821    int totalCount = [fTorrents count];
1822    if (totalCount != 1)
1823        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfers", "Status bar transfer count"), totalCount];
1824    else
1825        [totalTorrentsString appendString: NSLocalizedString(@"1 Transfer", "Status bar transfer count")];
1826   
1827    [fTotalTorrentsField setStringValue: totalTorrentsString];
1828    [totalTorrentsString release];
1829
1830    [self setWindowSizeToFit];
1831}
1832
1833//resets filter and sorts torrents
1834- (void) setFilter: (id) sender
1835{
1836    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
1837   
1838    NSButton * prevFilterButton;
1839    if ([oldFilterType isEqualToString: FILTER_PAUSE])
1840        prevFilterButton = fPauseFilterButton;
1841    else if ([oldFilterType isEqualToString: FILTER_SEED])
1842        prevFilterButton = fSeedFilterButton;
1843    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
1844        prevFilterButton = fDownloadFilterButton;
1845    else
1846        prevFilterButton = fNoFilterButton;
1847   
1848    if (sender != prevFilterButton)
1849    {
1850        [prevFilterButton setState: NSOffState];
1851        [sender setState: NSOnState];
1852
1853        NSString * filterType;
1854        if (sender == fDownloadFilterButton)
1855            filterType = FILTER_DOWNLOAD;
1856        else if (sender == fPauseFilterButton)
1857            filterType = FILTER_PAUSE;
1858        else if (sender == fSeedFilterButton)
1859            filterType = FILTER_SEED;
1860        else
1861            filterType = FILTER_NONE;
1862
1863        [fDefaults setObject: filterType forKey: @"Filter"];
1864    }
1865    else
1866        [sender setState: NSOnState];
1867
1868    [self applyFilter: nil];
1869}
1870
1871- (void) setFilterSearchType: (id) sender
1872{
1873    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
1874   
1875    int prevTag, currentTag = [sender tag];
1876    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
1877        prevTag = FILTER_TYPE_TAG_TRACKER;
1878    else
1879        prevTag = FILTER_TYPE_TAG_NAME;
1880   
1881    if (currentTag != prevTag)
1882    {
1883        NSString * filterType;
1884        if (currentTag == FILTER_TYPE_TAG_TRACKER)
1885            filterType = FILTER_TYPE_TRACKER;
1886        else
1887            filterType = FILTER_TYPE_NAME;
1888       
1889        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
1890       
1891        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
1892    }
1893   
1894    [self applyFilter: nil];
1895}
1896
1897- (void) switchFilter: (id) sender
1898{
1899    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1900   
1901    NSButton * button;
1902    if ([filterType isEqualToString: FILTER_NONE])
1903        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1904    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1905        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1906    else if ([filterType isEqualToString: FILTER_SEED])
1907        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1908    else if ([filterType isEqualToString: FILTER_PAUSE])
1909        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1910    else
1911        button = fNoFilterButton;
1912   
1913    [self setFilter: button];
1914}
1915
1916- (void) updateControlTint: (NSNotification *) notification
1917{
1918    if ([fDefaults boolForKey: @"SpeedLimit"])
1919        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSGraphiteControlTint
1920            ? [NSImage imageNamed: @"SpeedLimitButtonGraphite.png"] : [NSImage imageNamed: @"SpeedLimitButtonBlue.png"]];
1921}
1922
1923- (void) toggleSpeedLimit: (id) sender
1924{
1925    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
1926    [fPrefsController applySpeedSettings: nil];
1927}
1928
1929- (void) autoSpeedLimitChange: (NSNotification *) notification
1930{
1931    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1932        return;
1933 
1934    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1935                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
1936        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1937                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
1938        * nowDate = [NSCalendarDate calendarDate];
1939   
1940    //check if should be on if within range
1941    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
1942        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
1943        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
1944   
1945    BOOL shouldBeOn = NO;
1946    if (onTime < offTime)
1947        shouldBeOn = onTime <= nowTime && nowTime < offTime;
1948    else if (onTime > offTime)
1949        shouldBeOn = onTime <= nowTime || nowTime < offTime;
1950    else;
1951   
1952    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
1953        [self toggleSpeedLimit: nil];
1954}
1955
1956- (void) autoSpeedLimit
1957{
1958    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1959        return;
1960   
1961    //only toggle if within first few seconds of minutes
1962    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
1963    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
1964        return;
1965   
1966    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1967                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
1968   
1969    BOOL toggle;
1970    if ([fDefaults boolForKey: @"SpeedLimit"])
1971        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
1972    else
1973    {
1974        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1975                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
1976        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
1977                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
1978    }
1979   
1980    if (toggle)
1981    {
1982        [self toggleSpeedLimit: nil];
1983       
1984        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
1985                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
1986                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
1987            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
1988            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1989    }
1990}
1991
1992- (void) setLimitGlobalEnabled: (id) sender
1993{
1994    [fPrefsController applySpeedSettings: nil];
1995}
1996
1997- (void) setQuickLimitGlobal: (id) sender
1998{
1999    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
2000    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
2001   
2002    [fPrefsController updateLimitFields];
2003    [fPrefsController applySpeedSettings: nil];
2004}
2005
2006- (void) setQuickRatioGlobal: (id) sender
2007{
2008    [fDefaults setBool: YES forKey: @"RatioCheck"];
2009    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
2010   
2011    [fPrefsController updateRatioStopField];
2012}
2013
2014- (void) torrentStoppedForRatio: (NSNotification *) notification
2015{
2016    Torrent * torrent = [notification object];
2017   
2018    [self updateTorrentsInQueue];
2019    [fInfoController updateInfoStats];
2020    [fInfoController updateOptions];
2021   
2022    if ([fDefaults boolForKey: @"PlaySeedingSound"])
2023    {
2024        NSSound * sound;
2025        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
2026            [sound play];
2027    }
2028   
2029    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
2030                                    [torrent dataLocation], @"Location", nil];
2031    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
2032                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2033                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2034}
2035
2036-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2037{
2038    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2039    {
2040        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2041            return;
2042       
2043        if (fAutoImportTimer)
2044        {
2045            if ([fAutoImportTimer isValid])
2046                [fAutoImportTimer invalidate];
2047            [fAutoImportTimer release];
2048            fAutoImportTimer = nil;
2049        }
2050       
2051        //check again in 10 seconds in case torrent file wasn't complete
2052        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2053            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2054       
2055        [self checkAutoImportDirectory];
2056    }
2057}
2058
2059- (void) changeAutoImport
2060{
2061    if (fAutoImportTimer)
2062    {
2063        if ([fAutoImportTimer isValid])
2064            [fAutoImportTimer invalidate];
2065        [fAutoImportTimer release];
2066        fAutoImportTimer = nil;
2067    }
2068   
2069    if (fAutoImportedNames)
2070        [fAutoImportedNames removeAllObjects];
2071    [self checkAutoImportDirectory];
2072}
2073
2074- (void) checkAutoImportDirectory
2075{
2076    NSString * path;
2077    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2078        return;
2079   
2080    path = [path stringByExpandingTildeInPath];
2081   
2082    NSArray * importedNames;
2083    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2084        return;
2085   
2086    //only check files that have not been checked yet
2087    NSMutableArray * newNames = [importedNames mutableCopy];
2088   
2089    if (fAutoImportedNames)
2090        [newNames removeObjectsInArray: fAutoImportedNames];
2091    else
2092        fAutoImportedNames = [[NSMutableArray alloc] init];
2093    [fAutoImportedNames setArray: importedNames];
2094   
2095    NSString * file;
2096    int i;
2097    for (i = [newNames count] - 1; i >= 0; i--)
2098    {
2099        file = [newNames objectAtIndex: i];
2100        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2101            [newNames removeObjectAtIndex: i];
2102        else
2103            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2104    }
2105   
2106    BOOL ask = [[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"];
2107   
2108    NSEnumerator * enumerator = [newNames objectEnumerator];
2109    int canAdd, count;
2110    while ((file = [enumerator nextObject]))
2111    {
2112        canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL);
2113        if (canAdd == TR_OK)
2114        {
2115            if (!ask)
2116                count = [fTorrents count];
2117            [self openFiles: [NSArray arrayWithObject: file]];
2118           
2119            //check if torrent was opened
2120            if (!ask && [fTorrents count] > count)
2121                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
2122                    "Growl notification title") description: [file lastPathComponent]
2123                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
2124        }
2125        else if (canAdd == TR_EINVALID)
2126            [fAutoImportedNames removeObject: [file lastPathComponent]];
2127        else;
2128    }
2129   
2130    [newNames release];
2131}
2132
2133- (void) beginCreateFile: (NSNotification *) notification
2134{
2135    if (![fDefaults boolForKey: @"AutoImport"])
2136        return;
2137   
2138    NSString * location = [notification object],
2139            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2140   
2141    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2142                                    isEqualToString: [path stringByExpandingTildeInPath]])
2143        [fAutoImportedNames addObject: [location lastPathComponent]];
2144}
2145
2146- (int) numberOfRowsInTableView: (NSTableView *) tableview
2147{
2148    return [fDisplayedTorrents count];
2149}
2150
2151- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
2152{
2153    return nil;
2154}
2155
2156- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes toPasteboard: (NSPasteboard *) pasteboard
2157{
2158    //only allow reordering of rows if sorting by order
2159    if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2160    {
2161        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2162        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2163        return YES;
2164    }
2165    return NO;
2166}
2167
2168- (NSDragOperation) tableView: (NSTableView *) tableView validateDrop: (id <NSDraggingInfo>) info
2169    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
2170{
2171    NSPasteboard * pasteboard = [info draggingPasteboard];
2172    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2173    {
2174        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
2175        return NSDragOperationGeneric;
2176    }
2177   
2178    return NSDragOperationNone;
2179}
2180
2181- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
2182    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
2183{
2184    NSPasteboard * pasteboard = [info draggingPasteboard];
2185    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2186    {
2187        //remember selected rows if needed
2188        NSArray * selectedTorrents = nil;
2189        int numSelected = [fTableView numberOfSelectedRows];
2190        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
2191            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
2192   
2193        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
2194                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2195       
2196        //determine where to move them
2197        int i;
2198        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2199            newRow--;
2200       
2201        //reinsert into array
2202        int insertIndex = newRow > 0 ? [[[fDisplayedTorrents objectAtIndex: newRow-1] orderValue] intValue] + 1 : 0;
2203       
2204        //get all torrents to reorder
2205        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
2206                                                @"orderValue" ascending: YES] autorelease];
2207        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
2208       
2209        NSMutableArray * sortedTorrents = [[fTorrents sortedArrayUsingDescriptors: descriptors] mutableCopy];
2210        [descriptors release];
2211       
2212        //remove objects to reinsert
2213        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
2214        [sortedTorrents removeObjectsInArray: movingTorrents];
2215       
2216        //insert objects at new location
2217        for (i = 0; i < [movingTorrents count]; i++)
2218            [sortedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2219       
2220        [movingTorrents release];
2221       
2222        //redo order values
2223        i = 0;
2224        for (i = 0; i < [sortedTorrents count]; i++)
2225            [[sortedTorrents objectAtIndex: i] setOrderValue: i];
2226       
2227        [sortedTorrents release];
2228       
2229        [self applyFilter: nil];
2230       
2231        //set selected rows if needed
2232        if (selectedTorrents)
2233        {
2234            Torrent * torrent;
2235            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
2236            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
2237            while ((torrent = [enumerator nextObject]))
2238                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
2239           
2240            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
2241            [indexSet release];
2242        }
2243    }
2244   
2245    return YES;
2246}
2247
2248- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2249{
2250    [fInfoController setInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
2251}
2252
2253- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2254{
2255    NSPasteboard * pasteboard = [info draggingPasteboard];
2256    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2257    {
2258        //check if any torrent files can be added
2259        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2260        NSEnumerator * enumerator = [files objectEnumerator];
2261        NSString * file;
2262        BOOL torrent = NO;
2263        int canAdd;
2264        while ((file = [enumerator nextObject]))
2265        {
2266            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2267            {
2268                switch (canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2269                {
2270                    case TR_OK:
2271                        if (!fOverlayWindow)
2272                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2273                        [fOverlayWindow setTorrents: files];
2274                       
2275                        return NSDragOperationCopy;
2276                   
2277                    case TR_EDUPLICATE:
2278                        torrent = YES;
2279                }
2280            }
2281        }
2282       
2283        //create a torrent file if a single file
2284        if (!torrent && [files count] == 1)
2285        {
2286            if (!fOverlayWindow)
2287                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2288            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2289           
2290            return NSDragOperationCopy;
2291        }
2292    }
2293    else if ([[pasteboard types] containsObject: NSURLPboardType])
2294    {
2295        if (!fOverlayWindow)
2296            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2297        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2298       
2299        return NSDragOperationCopy;
2300    }
2301    else;
2302   
2303    return NSDragOperationNone;
2304}
2305
2306- (void) draggingExited: (id <NSDraggingInfo>) info
2307{
2308    if (fOverlayWindow)
2309        [fOverlayWindow fadeOut];
2310}
2311
2312- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2313{
2314    if (fOverlayWindow)
2315        [fOverlayWindow fadeOut];
2316   
2317    NSPasteboard * pasteboard = [info draggingPasteboard];
2318    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2319    {
2320        BOOL torrent = NO, accept = YES;
2321       
2322        //create an array of files that can be opened
2323        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2324        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2325        NSEnumerator * enumerator = [files objectEnumerator];
2326        NSString * file;
2327        int canAdd;
2328        while ((file = [enumerator nextObject]))
2329        {
2330            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2331            {
2332                switch(tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2333                {
2334                    case TR_OK:
2335                        [filesToOpen addObject: file];
2336                        torrent = YES;
2337                        break;
2338                       
2339                    case TR_EDUPLICATE:
2340                        torrent = YES;
2341                }
2342            }
2343        }
2344       
2345        if ([filesToOpen count] > 0)
2346            [self application: NSApp openFiles: filesToOpen];
2347        else
2348        {
2349            if (!torrent && [files count] == 1)
2350                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2351            else
2352                accept = NO;
2353        }
2354        [filesToOpen release];
2355       
2356        return accept;
2357    }
2358    else if ([[pasteboard types] containsObject: NSURLPboardType])
2359    {
2360        NSURL * url;
2361        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2362        {
2363            [self openURL: url];
2364            return YES;
2365        }
2366    }
2367    else;
2368   
2369    return NO;
2370}
2371
2372- (void) toggleSmallView: (id) sender
2373{
2374    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2375    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2376   
2377    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2378   
2379    //window min height
2380    NSSize contentMinSize = [fWindow contentMinSize],
2381            contentSize = [[fWindow contentView] frame].size;
2382    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
2383                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2384    [fWindow setContentMinSize: contentMinSize];
2385   
2386    //resize for larger min height if not set to auto size
2387    if (![fDefaults boolForKey: @"AutoSize"])
2388    {
2389        if (!makeSmall && contentSize.height < contentMinSize.height)
2390        {
2391            NSRect frame = [fWindow frame];
2392            float heightChange = contentMinSize.height - contentSize.height;
2393            frame.size.height += heightChange;
2394            frame.origin.y -= heightChange;
2395           
2396            [fWindow setFrame: frame display: YES];
2397            [fTableView reloadData];
2398        }
2399    }
2400    else
2401        [self setWindowSizeToFit];
2402}
2403
2404- (void) togglePiecesBar: (id) sender
2405{
2406    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2407    [fTableView display];
2408}
2409
2410- (void) toggleAvailabilityBar: (id) sender
2411{
2412    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2413    [fTableView display];
2414}
2415
2416- (void) toggleStatusBar: (id) sender
2417{
2418    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2419    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2420}
2421
2422- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2423{
2424    //convert pixels to points
2425    NSRect windowFrame = [fWindow frame];
2426    NSSize windowSize = [fScrollView convertSize: windowFrame.size fromView: nil];
2427    windowSize.height += height;
2428   
2429    if (check)
2430    {
2431        NSSize minSize = [fScrollView convertSize: [fWindow minSize] fromView: nil];
2432       
2433        if (windowSize.height < minSize.height)
2434            windowSize.height = minSize.height;
2435        else
2436        {
2437            NSSize maxSize = [fScrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2438            if ([fStatusBar isHidden])
2439                maxSize.height -= [fStatusBar frame].size.height;
2440            if ([fFilterBar isHidden])
2441                maxSize.height -= [fFilterBar frame].size.height;
2442            if (windowSize.height > maxSize.height)
2443                windowSize.height = maxSize.height;
2444        }
2445    }
2446
2447    //convert points to pixels
2448    windowSize = [fScrollView convertSize: windowSize toView: nil];
2449
2450    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2451    windowFrame.size.height = windowSize.height;
2452    return windowFrame;
2453}
2454
2455- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2456{
2457    if (show != [fStatusBar isHidden])
2458        return;
2459
2460    if (show)
2461        [fStatusBar setHidden: NO];
2462
2463    NSRect frame;
2464    float heightChange = [fStatusBar frame].size.height;
2465    if (!show)
2466        heightChange *= -1;
2467   
2468    //allow bar to show even if not enough room
2469    if (show && ![fDefaults boolForKey: @"AutoSize"])
2470    {
2471        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2472        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2473        if (change < 0.0)
2474        {
2475            frame = [fWindow frame];
2476            frame.size.height += change;
2477            frame.origin.y -= change;
2478            [fWindow setFrame: frame display: NO animate: NO];
2479        }
2480    }
2481
2482    [self updateUI];
2483   
2484    //set views to not autoresize
2485    unsigned int statsMask = [fStatusBar autoresizingMask];
2486    unsigned int filterMask = [fFilterBar autoresizingMask];
2487    unsigned int scrollMask = [fScrollView autoresizingMask];
2488    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2489    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2490    [fScrollView setAutoresizingMask: NSViewNotSizable];
2491   
2492    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2493    [fWindow setFrame: frame display: YES animate: animate];
2494   
2495    //re-enable autoresize
2496    [fStatusBar setAutoresizingMask: statsMask];
2497    [fFilterBar setAutoresizingMask: filterMask];
2498    [fScrollView setAutoresizingMask: scrollMask];
2499   
2500    //change min size
2501    NSSize minSize = [fWindow contentMinSize];
2502    minSize.height += heightChange;
2503    [fWindow setContentMinSize: minSize];
2504   
2505    if (!show)
2506        [fStatusBar setHidden: YES];
2507}
2508
2509- (void) toggleFilterBar: (id) sender
2510{
2511    //disable filtering when hiding
2512    if (![fFilterBar isHidden])
2513    {
2514        [fSearchFilterField setStringValue: @""];
2515        [self setFilter: fNoFilterButton];
2516    }
2517
2518    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2519    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2520}
2521
2522- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2523{
2524    if (show != [fFilterBar isHidden])
2525        return;
2526
2527    if (show)
2528        [fFilterBar setHidden: NO];
2529
2530    NSRect frame;
2531    float heightChange = [fFilterBar frame].size.height;
2532    if (!show)
2533        heightChange *= -1;
2534   
2535    //allow bar to show even if not enough room
2536    if (show && ![fDefaults boolForKey: @"AutoSize"])
2537    {
2538        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2539        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2540        if (change < 0.0)
2541        {
2542            frame = [fWindow frame];
2543            frame.size.height += change;
2544            frame.origin.y -= change;
2545            [fWindow setFrame: frame display: NO animate: NO];
2546        }
2547    }
2548
2549    //set views to not autoresize
2550    unsigned int filterMask = [fFilterBar autoresizingMask];
2551    unsigned int scrollMask = [fScrollView autoresizingMask];
2552    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2553    [fScrollView setAutoresizingMask: NSViewNotSizable];
2554   
2555    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2556    [fWindow setFrame: frame display: YES animate: animate];
2557   
2558    //re-enable autoresize
2559    [fFilterBar setAutoresizingMask: filterMask];
2560    [fScrollView setAutoresizingMask: scrollMask];
2561   
2562    //change min size
2563    NSSize minSize = [fWindow contentMinSize];
2564    minSize.height += heightChange;
2565    [fWindow setContentMinSize: minSize];
2566   
2567    if (!show)
2568    {
2569        [fFilterBar setHidden: YES];
2570        [fWindow makeFirstResponder: fTableView];
2571    }
2572}
2573
2574- (void) doNothing: (id) sender {}
2575
2576- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2577{
2578    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
2579
2580    if ([ident isEqualToString: TOOLBAR_CREATE])
2581    {
2582        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
2583        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
2584        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
2585        [item setImage: [NSImage imageNamed: @"Create.png"]];
2586        [item setTarget: self];
2587        [item setAction: @selector(createFile:)];
2588        [item setAutovalidates: NO];
2589    }
2590    else if ([ident isEqualToString: TOOLBAR_OPEN])
2591    {
2592        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
2593        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
2594        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
2595        [item setImage: [NSImage imageNamed: @"Open.png"]];
2596        [item setTarget: self];
2597        [item setAction: @selector(openShowSheet:)];
2598        [item setAutovalidates: NO];
2599    }
2600    else if ([ident isEqualToString: TOOLBAR_REMOVE])
2601    {
2602        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
2603        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
2604        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
2605        [item setImage: [NSImage imageNamed: @"Remove.png"]];
2606        [item setTarget: self];
2607        [item setAction: @selector(removeNoDelete:)];
2608    }
2609    else if ([ident isEqualToString: TOOLBAR_INFO])
2610    {
2611        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
2612        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
2613        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
2614        [item setImage: [NSImage imageNamed: @"Info.png"]];
2615        [item setTarget: self];
2616        [item setAction: @selector(showInfo:)];
2617        [item setAutovalidates: NO];
2618    }
2619    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2620    {
2621        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
2622        [item setPaletteLabel: [item label]];
2623        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
2624        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
2625        [item setTarget: self];
2626        [item setAction: @selector(stopAllTorrents:)];
2627    }
2628    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2629    {
2630        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
2631        [item setPaletteLabel: [item label]];
2632        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
2633        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
2634        [item setTarget: self];
2635        [item setAction: @selector(resumeAllTorrents:)];
2636    }
2637    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2638    {
2639        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
2640        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
2641        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
2642        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
2643        [item setTarget: self];
2644        [item setAction: @selector(stopSelectedTorrents:)];
2645    }
2646    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2647    {
2648        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
2649        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
2650        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
2651        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
2652        [item setTarget: self];
2653        [item setAction: @selector(resumeSelectedTorrents:)];
2654    }
2655    else if ([ident isEqualToString: TOOLBAR_FILTER])
2656    {
2657        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
2658        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
2659        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
2660        [item setImage: [NSImage imageNamed: @"Filter.png"]];
2661        [item setTarget: self];
2662        [item setAction: @selector(toggleFilterBar:)];
2663        [item setAutovalidates: NO];
2664    }
2665    else
2666    {
2667        [item release];
2668        return nil;
2669    }
2670
2671    return [item autorelease];
2672}
2673
2674- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
2675{
2676    return [NSArray arrayWithObjects:
2677            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2678            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
2679            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
2680            NSToolbarSeparatorItemIdentifier,
2681            NSToolbarSpaceItemIdentifier,
2682            NSToolbarFlexibleSpaceItemIdentifier,
2683            NSToolbarCustomizeToolbarItemIdentifier, nil];
2684}
2685
2686- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
2687{
2688    return [NSArray arrayWithObjects:
2689            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2690            NSToolbarSeparatorItemIdentifier,
2691            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2692            NSToolbarFlexibleSpaceItemIdentifier,
2693            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2694}
2695
2696- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2697{
2698    NSString * ident = [toolbarItem itemIdentifier];
2699
2700    //enable remove item
2701    if ([ident isEqualToString: TOOLBAR_REMOVE])
2702        return [fTableView numberOfSelectedRows] > 0;
2703
2704    //enable pause all item
2705    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2706    {
2707        Torrent * torrent;
2708        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2709        while ((torrent = [enumerator nextObject]))
2710            if ([torrent isActive] || [torrent waitingToStart])
2711                return YES;
2712        return NO;
2713    }
2714
2715    //enable resume all item
2716    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2717    {
2718        Torrent * torrent;
2719        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2720        while ((torrent = [enumerator nextObject]))
2721            if (![torrent isActive] && ![torrent waitingToStart])
2722                return YES;
2723        return NO;
2724    }
2725
2726    //enable pause item
2727    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2728    {
2729        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2730        Torrent * torrent;
2731        while ((torrent = [enumerator nextObject]))
2732            if ([torrent isActive] || [torrent waitingToStart])
2733                return YES;
2734        return NO;
2735    }
2736   
2737    //enable resume item
2738    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2739    {
2740        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2741        Torrent * torrent;
2742        while ((torrent = [enumerator nextObject]))
2743            if (![torrent isActive] && ![torrent waitingToStart])
2744                return YES;
2745        return NO;
2746    }
2747
2748    return YES;
2749}
2750
2751- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2752{
2753    SEL action = [menuItem action];
2754   
2755    if (action == @selector(toggleSpeedLimit:))
2756    {
2757        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
2758        return YES;
2759    }
2760   
2761    //only enable some items if it is in a context menu or the window is useable
2762    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
2763
2764    //enable open items
2765    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
2766        return [fWindow attachedSheet] == nil;
2767   
2768    //enable sort options
2769    if (action == @selector(setSort:))
2770    {
2771        NSString * sortType;
2772        switch ([menuItem tag])
2773        {
2774            case SORT_ORDER_TAG:
2775                sortType = SORT_ORDER;
2776                break;
2777            case SORT_DATE_TAG:
2778                sortType = SORT_DATE;
2779                break;
2780            case SORT_NAME_TAG:
2781                sortType = SORT_NAME;
2782                break;
2783            case SORT_PROGRESS_TAG:
2784                sortType = SORT_PROGRESS;
2785                break;
2786            case SORT_STATE_TAG:
2787                sortType = SORT_STATE;
2788                break;
2789            case SORT_TRACKER_TAG:
2790                sortType = SORT_TRACKER;
2791                break;
2792            default:
2793                sortType = @"";
2794        }
2795       
2796        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
2797        return [fWindow isVisible];
2798    }
2799   
2800    if (action == @selector(toggleSmallView:))
2801    {
2802        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
2803        return [fWindow isVisible];
2804    }
2805   
2806    if (action == @selector(togglePiecesBar:))
2807    {
2808        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
2809        return [fWindow isVisible];
2810    }
2811   
2812    if (action == @selector(toggleAvailabilityBar:))
2813    {
2814        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
2815        return [fWindow isVisible];
2816    }
2817
2818    //enable show info
2819    if (action == @selector(showInfo:))
2820    {
2821        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
2822                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2823        [menuItem setTitle: title];
2824
2825        return YES;
2826    }
2827   
2828    //enable prev/next inspector tab
2829    if (action == @selector(setInfoTab:))
2830        return [[fInfoController window] isVisible];
2831   
2832    //enable toggle status bar
2833    if (action == @selector(toggleStatusBar:))
2834    {
2835        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2836                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2837        [menuItem setTitle: title];
2838
2839        return [fWindow isVisible];
2840    }
2841   
2842    //enable toggle filter bar
2843    if (action == @selector(toggleFilterBar:))
2844    {
2845        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2846                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2847        [menuItem setTitle: title];
2848
2849        return [fWindow isVisible];
2850    }
2851   
2852    //enable prev/next filter button
2853    if (action == @selector(switchFilter:))
2854        return [fWindow isVisible] && ![fFilterBar isHidden];
2855
2856    //enable reveal in finder
2857    if (action == @selector(revealFile:))
2858        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2859
2860    //enable remove items
2861    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2862        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2863    {
2864        BOOL warning = NO,
2865            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2866            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2867       
2868        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2869        Torrent * torrent;
2870        while ((torrent = [enumerator nextObject]))
2871        {
2872            if (!warning && [torrent isActive])
2873            {
2874                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2875                if (warning && canDelete)
2876                    break;
2877            }
2878            if (!canDelete && [torrent publicTorrent])
2879            {
2880                canDelete = YES;
2881                if (warning)
2882                    break;
2883            }
2884        }
2885   
2886        //append or remove ellipsis when needed
2887        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2888        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2889        {
2890            if (![title hasSuffix: ellipsis])
2891                [menuItem setTitle: [title stringByAppendingEllipsis]];
2892        }
2893        else
2894        {
2895            if ([title hasSuffix: ellipsis])
2896                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2897        }
2898       
2899        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2900    }
2901
2902    //enable pause all item
2903    if (action == @selector(stopAllTorrents:))
2904    {
2905        Torrent * torrent;
2906        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2907        while ((torrent = [enumerator nextObject]))
2908            if ([torrent isActive] || [torrent waitingToStart])
2909                return YES;
2910        return NO;
2911    }
2912   
2913    //enable resume all item
2914    if (action == @selector(resumeAllTorrents:))
2915    {
2916        Torrent * torrent;
2917        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2918        while ((torrent = [enumerator nextObject]))
2919            if (![torrent isActive] && ![torrent waitingToStart])
2920                return YES;
2921        return NO;
2922    }
2923   
2924    //enable resume all waiting item
2925    if (action == @selector(resumeWaitingTorrents:))
2926    {
2927        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2928            return NO;
2929   
2930        Torrent * torrent;
2931        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2932        while ((torrent = [enumerator nextObject]))
2933            if (![torrent isActive] && [torrent waitingToStart])
2934                return YES;
2935        return NO;
2936    }
2937   
2938    //enable resume selected waiting item
2939    if (action == @selector(resumeSelectedTorrentsNoWait:))
2940    {
2941        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2942            return NO;
2943   
2944        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2945        Torrent * torrent;
2946        while ((torrent = [enumerator nextObject]))
2947            if (![torrent isActive])
2948                return YES;
2949        return NO;
2950    }
2951
2952    //enable pause item
2953    if (action == @selector(stopSelectedTorrents:))
2954    {
2955        if (!canUseTable)
2956            return NO;
2957   
2958        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2959        Torrent * torrent;
2960        while ((torrent = [enumerator nextObject]))
2961            if ([torrent isActive] || [torrent waitingToStart])
2962                return YES;
2963        return NO;
2964    }
2965   
2966    //enable resume item
2967    if (action == @selector(resumeSelectedTorrents:))
2968    {
2969        if (!canUseTable)
2970            return NO;
2971   
2972        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2973        Torrent * torrent;
2974        while ((torrent = [enumerator nextObject]))
2975            if (![torrent isActive] && ![torrent waitingToStart])
2976                return YES;
2977        return NO;
2978    }
2979   
2980    //enable manual announce item
2981    if (action == @selector(announceSelectedTorrents:))
2982    {
2983        if (!canUseTable)
2984            return NO;
2985       
2986        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2987        Torrent * torrent;
2988        while ((torrent = [enumerator nextObject]))
2989            if ([torrent canManualAnnounce])
2990                return YES;
2991        return NO;
2992    }
2993   
2994    //enable reset cache item
2995    if (action == @selector(resetCacheForSelectedTorrents:))
2996        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2997   
2998    //enable move torrent file item
2999    if (action == @selector(moveDataFiles:))
3000        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3001   
3002    //enable copy torrent file item
3003    if (action == @selector(copyTorrentFiles:))
3004        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3005   
3006    //enable reverse sort item
3007    if (action == @selector(setSortReverse:))
3008    {
3009        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3010        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3011    }
3012   
3013    //check proper filter search item
3014    if (action == @selector(setFilterSearchType:))
3015    {
3016        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3017       
3018        BOOL state;
3019        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3020            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3021        else
3022            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3023       
3024        [menuItem setState: state ? NSOnState : NSOffState];
3025        return YES;
3026    }
3027   
3028    return YES;
3029}
3030
3031- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
3032{
3033    NSEnumerator * enumerator;
3034    Torrent * torrent;
3035    BOOL allowSleep;
3036
3037    switch (messageType)
3038    {
3039        case kIOMessageSystemWillSleep:
3040            //close all connections before going to sleep and remember we should resume when we wake up
3041            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3042
3043            //wait for running transfers to stop (5 second timeout)
3044            NSDate * start = [NSDate date];
3045            BOOL timeUp = NO;
3046           
3047            enumerator = [fTorrents objectEnumerator];
3048            while (!timeUp && (torrent = [enumerator nextObject]))
3049                while ([torrent isActive] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
3050                {
3051                    usleep(100000);
3052                    [torrent update];
3053                }
3054
3055            IOAllowPowerChange(fRootPort, (long) messageArgument);
3056            break;
3057
3058        case kIOMessageCanSystemSleep:
3059            allowSleep = YES;
3060            if ([fDefaults boolForKey: @"SleepPrevent"])
3061            {
3062                //prevent idle sleep unless no torrents are active
3063                enumerator = [fTorrents objectEnumerator];
3064                while ((torrent = [enumerator nextObject]))
3065                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3066                    {
3067                        allowSleep = NO;
3068                        break;
3069                    }
3070            }
3071
3072            if (allowSleep)
3073                IOAllowPowerChange(fRootPort, (long) messageArgument);
3074            else
3075                IOCancelPowerChange(fRootPort, (long) messageArgument);
3076            break;
3077
3078        case kIOMessageSystemHasPoweredOn:
3079            //resume sleeping transfers after we wake up
3080            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3081            [self autoSpeedLimitChange: nil];
3082            break;
3083    }
3084}
3085
3086- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3087{
3088    int seeding = 0, downloading = 0;
3089    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3090    Torrent * torrent;
3091    while ((torrent = [enumerator nextObject]))
3092    {
3093        if ([torrent isSeeding])
3094            seeding++;
3095        else if ([torrent isActive])
3096            downloading++;
3097        else;
3098    }
3099   
3100    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3101            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3102   
3103    BOOL hasSeparator = seedingItem || downloadingItem;
3104   
3105    if (seeding > 0)
3106    {
3107        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding",
3108                                                        "Dock item - Seeding"), seeding];
3109        if (!seedingItem)
3110        {
3111            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3112            [seedingItem setTag: DOCK_SEEDING_TAG];
3113            [fDockMenu insertItem: seedingItem atIndex: 0];
3114        }
3115        else
3116            [seedingItem setTitle: title];
3117    }
3118    else
3119    {
3120        if (seedingItem)
3121            [fDockMenu removeItem: seedingItem];
3122    }
3123   
3124    if (downloading > 0)
3125    {
3126        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading",
3127                                                        "Dock item - Downloading"), downloading];
3128        if (!downloadingItem)
3129        {
3130            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3131            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3132            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3133        }
3134        else
3135            [downloadingItem setTitle: title];
3136    }
3137    else
3138    {
3139        if (downloadingItem)
3140            [fDockMenu removeItem: downloadingItem];
3141    }
3142   
3143    if (seeding > 0 || downloading > 0)
3144    {
3145        if (!hasSeparator)
3146            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3147    }
3148    else
3149    {
3150        if (hasSeparator)
3151            [fDockMenu removeItemAtIndex: 0];
3152    }
3153   
3154    return fDockMenu;
3155}
3156
3157- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3158{
3159    //if auto size is enabled, the current frame shouldn't need to change
3160    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3161   
3162    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3163    return frame;
3164}
3165
3166- (void) setWindowSizeToFit
3167{
3168    if ([fDefaults boolForKey: @"AutoSize"])
3169    {
3170        [fScrollView setHasVerticalScroller: NO];
3171        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3172        [fScrollView setHasVerticalScroller: YES];
3173    }
3174}
3175
3176- (NSRect) sizedWindowFrame
3177{
3178    float heightChange = [fDisplayedTorrents count] * ([fTableView rowHeight] +
3179            [fTableView intercellSpacing].height) - [fScrollView frame].size.height;
3180    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3181}
3182
3183- (void) showMainWindow: (id) sender
3184{
3185    [fWindow makeKeyAndOrderFront: nil];
3186}
3187
3188- (void) windowDidBecomeMain: (NSNotification *) notification
3189{
3190    [fBadger clearCompleted];
3191    [self updateUI];
3192}
3193
3194- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3195{
3196    //only resize horizontally if autosize is enabled
3197    if ([fDefaults boolForKey: @"AutoSize"])
3198        proposedFrameSize.height = [fWindow frame].size.height;
3199    return proposedFrameSize;
3200}
3201
3202- (void) windowDidResize: (NSNotification *) notification
3203{
3204    //size search filter to not overlap buttons
3205    float pointX = NSMaxX([fPauseFilterButton frame]) + 5.0;
3206    NSRect oldFrame = [fSearchFilterField frame],
3207            frame = NSMakeRect(pointX, oldFrame.origin.y, NSMaxX(oldFrame) - pointX, oldFrame.size.height);
3208   
3209    BOOL show = frame.size.width >= SEARCH_FILTER_MIN_WIDTH;
3210    if (show)
3211    {
3212        //make sure it is not too long
3213        if (frame.size.width > SEARCH_FILTER_MAX_WIDTH)
3214        {
3215            float different = frame.size.width - SEARCH_FILTER_MAX_WIDTH;
3216            frame.origin.x += different;
3217            frame.size.width -= different;
3218        }
3219        [fSearchFilterField setFrame: frame];
3220    }
3221   
3222    //hide search filter if it overlaps filter buttons
3223    [fSearchFilterField setHidden: !show];
3224}
3225
3226- (void) applicationWillUnhide: (NSNotification *) notification
3227{
3228    [self updateUI];
3229}
3230
3231- (void) linkHomepage: (id) sender
3232{
3233    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
3234}
3235
3236- (void) linkForums: (id) sender
3237{
3238    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
3239}
3240
3241- (void) linkDonate: (id) sender
3242{
3243    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
3244}
3245
3246- (void) prepareForUpdate: (NSNotification *) notification
3247{
3248    fUpdateInProgress = YES;
3249}
3250
3251- (NSDictionary *) registrationDictionaryForGrowl
3252{
3253    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
3254                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
3255    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
3256                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
3257}
3258
3259- (void) growlNotificationWasClicked: (id) clickContext
3260{
3261    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
3262        return;
3263   
3264    NSString * type = [clickContext objectForKey: @"Type"], * location;
3265    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
3266            && (location = [clickContext objectForKey: @"Location"]))
3267        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
3268}
3269
3270- (void) ipcQuit
3271{
3272    fRemoteQuit = YES;
3273    [NSApp terminate: self];
3274}
3275
3276- (NSArray *) ipcGetTorrentsByID: (NSArray *) idlist
3277{
3278    if (!idlist)
3279        return fTorrents;
3280   
3281    NSMutableArray * torrents = [NSMutableArray array];
3282   
3283    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * idEnum;
3284    int torId;
3285    Torrent * torrent;
3286    NSNumber * tempId;
3287    while ((torrent = [torrentEnum nextObject]))
3288    {
3289        torId = [torrent torrentID];
3290       
3291        idEnum = [idlist objectEnumerator];
3292        while ((tempId = [idEnum nextObject]))
3293        {
3294            if ([tempId intValue] == torId)
3295            {
3296                [torrents addObject: torrent];
3297                break;
3298            }
3299        }
3300    }
3301
3302    return torrents;
3303}
3304
3305- (NSArray *) ipcGetTorrentsByHash: (NSArray *) hashlist
3306{
3307    if (!hashlist)
3308        return fTorrents;
3309   
3310    NSMutableArray * torrents = [NSMutableArray array];
3311   
3312    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * hashEnum;
3313    NSString * torHash, * tempHash;
3314    Torrent * torrent;
3315    while ((torrent = [torrentEnum nextObject]))
3316    {
3317        torHash = [torrent hashString];
3318       
3319        hashEnum = [hashlist objectEnumerator];
3320        while ((tempHash = [hashEnum nextObject]))
3321        {
3322            if ([torHash caseInsensitiveCompare: tempHash] == NSOrderedSame)
3323            {
3324                [torrents addObject: torrent];
3325                break;
3326            }
3327        }
3328    }
3329   
3330    return torrents;
3331}
3332
3333- (BOOL) ipcAddTorrents: (NSArray *) torrents
3334{
3335    int oldCount = [fTorrents count];
3336   
3337    [self openFiles: torrents];
3338   
3339    return [fTorrents count] > oldCount;
3340}
3341
3342- (BOOL) ipcAddTorrentFile: (NSString *) path directory: (NSString *) directory
3343{
3344    int oldCount = [fTorrents count];
3345   
3346    [self openFiles: [NSArray arrayWithObject: path] forcePath: directory ignoreDownloadFolder: NO
3347            deleteTorrentFile: TORRENT_FILE_DEFAULT];
3348   
3349    return [fTorrents count] > oldCount;
3350}
3351
3352- (BOOL) ipcAddTorrentFileAutostart: (NSString *) path directory: (NSString *) directory autostart: (BOOL) autostart
3353{
3354    /* 'path' is path to torrent file, 'dir' is the directory it
3355       should download it's files to and may be nil, 'autostart' is a
3356       boolean indicating if the torrent should be automatically
3357       started (or queued to start, I guess), should return NO if
3358       torrent fails to load */
3359    return NO;
3360}
3361
3362- (BOOL) ipcAddTorrentData: (NSData *) data directory: (NSString *) directory
3363{
3364    /* 'data' is the contents of a torrent file, 'directory' is the
3365       directory it should download it's files to and may be nil,
3366       should return NO if torrent fails to load */
3367    return NO;
3368}
3369
3370- (BOOL) ipcAddTorrentDataAutostart: (NSData *) path directory: (NSString *) directory autostart: (BOOL) autostart
3371{
3372    /* 'data' is the contents of a torrent file, 'directory' is the
3373       directory it should download it's files to and may be nil,
3374       'autostart' is a boolean indicating if the torrent should be
3375       automatically started (or queued to start, I guess), should
3376       return NO if torrent fails to load */
3377    return NO;
3378}
3379
3380- (BOOL) ipcStartTorrents: (NSArray *) torrents
3381{
3382    if (!torrents)
3383        [self resumeAllTorrents: self];
3384    else
3385        [self resumeTorrents: torrents];
3386
3387    return YES;
3388}
3389
3390- (BOOL) ipcStopTorrents: (NSArray *) torrents
3391{
3392    if (!torrents)
3393        [self stopAllTorrents: self];
3394    else
3395        [self stopTorrents: torrents];
3396
3397    return YES;
3398}
3399
3400- (BOOL) ipcRemoveTorrents: (NSArray *) torrents
3401{
3402    if (!torrents)
3403        torrents = [NSArray arrayWithArray: fTorrents];
3404
3405    [self confirmRemoveTorrents: torrents deleteData: NO deleteTorrent: NO];
3406
3407    return YES;
3408}
3409
3410@end
Note: See TracBrowser for help on using the repository browser.