source: trunk/macosx/Controller.m @ 3851

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

fix bug where dragging a torrent that is already opened off of the window will make the overlay appear and fade off

  • Property svn:keywords set to Date Rev Author Id
File size: 126.0 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 3851 2007-11-17 14:43:05Z 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    #warning make better
1753    [fNoFilterButton setToolTip: [fTorrents count] == 1 ? NSLocalizedString(@"1 Transfer", "Filter Button -> tool tip")
1754        : [NSString stringWithFormat: NSLocalizedString(@"%d Transfers", "Filter Bar Button -> tool tip"), [fTorrents count]]];
1755    [fDownloadFilterButton setToolTip: downloading == 1 ? NSLocalizedString(@"1 Transfer", "Filter Button -> tool tip")
1756        : [NSString stringWithFormat: NSLocalizedString(@"%d Transfers", "Filter Bar Button -> tool tip"), downloading]];
1757    [fSeedFilterButton setToolTip: seeding == 1 ? NSLocalizedString(@"1 Transfer", "Filter Button -> tool tip")
1758        : [NSString stringWithFormat: NSLocalizedString(@"%d Transfers", "Filter Bar Button -> tool tip"), seeding]];
1759    [fPauseFilterButton setToolTip: paused == 1 ? NSLocalizedString(@"1 Transfer", "Filter Button -> tool tip")
1760        : [NSString stringWithFormat: NSLocalizedString(@"%d Transfers", "Filter Bar Button -> tool tip"), paused]];
1761   
1762    NSString * searchString = [fSearchFilterField stringValue];
1763    if ([searchString length] > 0)
1764    {
1765        filtering = YES;
1766       
1767        Torrent * torrent;
1768        BOOL filterTracker = [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER], remove;
1769       
1770        int i;
1771        for (i = [tempTorrents count]-1; i >= 0; i--)
1772        {
1773            torrent = [tempTorrents objectAtIndex: i];
1774            remove = YES;
1775           
1776            if (filterTracker)
1777            {
1778                NSEnumerator * trackerEnumerator = [[torrent allTrackers] objectEnumerator], * subTrackerEnumerator;
1779                NSArray * subTrackers;
1780                NSString * tracker;
1781                while (remove && (subTrackers = [trackerEnumerator nextObject]))
1782                {
1783                    subTrackerEnumerator = [subTrackers objectEnumerator];
1784                    while ((tracker = [subTrackerEnumerator nextObject]))
1785                    {
1786                        if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1787                        {
1788                            remove = NO;
1789                            break;
1790                        }
1791                    }
1792                }
1793            }
1794            else
1795                remove = [[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound;
1796           
1797            if (remove)
1798                [tempTorrents removeObjectAtIndex: i];
1799        }
1800    }
1801   
1802    [fDisplayedTorrents setArray: tempTorrents];
1803   
1804    [self sortTorrentsIgnoreSelected];
1805   
1806    //set selected rows if needed
1807    if (selectedTorrents)
1808    {
1809        Torrent * torrent;
1810        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1811        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1812        unsigned index;
1813        while ((torrent = [enumerator nextObject]))
1814            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1815                [indexSet addIndex: index];
1816       
1817        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1818        [indexSet release];
1819    }
1820   
1821    //set status bar torrent count text
1822    NSMutableString * totalTorrentsString = [[NSMutableString alloc] initWithString: @""];
1823    if (filtering)
1824        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1825   
1826    int totalCount = [fTorrents count];
1827    if (totalCount != 1)
1828        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfers", "Status bar transfer count"), totalCount];
1829    else
1830        [totalTorrentsString appendString: NSLocalizedString(@"1 Transfer", "Status bar transfer count")];
1831   
1832    [fTotalTorrentsField setStringValue: totalTorrentsString];
1833    [totalTorrentsString release];
1834
1835    [self setWindowSizeToFit];
1836}
1837
1838//resets filter and sorts torrents
1839- (void) setFilter: (id) sender
1840{
1841    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
1842   
1843    NSButton * prevFilterButton;
1844    if ([oldFilterType isEqualToString: FILTER_PAUSE])
1845        prevFilterButton = fPauseFilterButton;
1846    else if ([oldFilterType isEqualToString: FILTER_SEED])
1847        prevFilterButton = fSeedFilterButton;
1848    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
1849        prevFilterButton = fDownloadFilterButton;
1850    else
1851        prevFilterButton = fNoFilterButton;
1852   
1853    if (sender != prevFilterButton)
1854    {
1855        [prevFilterButton setState: NSOffState];
1856        [sender setState: NSOnState];
1857
1858        NSString * filterType;
1859        if (sender == fDownloadFilterButton)
1860            filterType = FILTER_DOWNLOAD;
1861        else if (sender == fPauseFilterButton)
1862            filterType = FILTER_PAUSE;
1863        else if (sender == fSeedFilterButton)
1864            filterType = FILTER_SEED;
1865        else
1866            filterType = FILTER_NONE;
1867
1868        [fDefaults setObject: filterType forKey: @"Filter"];
1869    }
1870    else
1871        [sender setState: NSOnState];
1872
1873    [self applyFilter: nil];
1874}
1875
1876- (void) setFilterSearchType: (id) sender
1877{
1878    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
1879   
1880    int prevTag, currentTag = [sender tag];
1881    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
1882        prevTag = FILTER_TYPE_TAG_TRACKER;
1883    else
1884        prevTag = FILTER_TYPE_TAG_NAME;
1885   
1886    if (currentTag != prevTag)
1887    {
1888        NSString * filterType;
1889        if (currentTag == FILTER_TYPE_TAG_TRACKER)
1890            filterType = FILTER_TYPE_TRACKER;
1891        else
1892            filterType = FILTER_TYPE_NAME;
1893       
1894        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
1895       
1896        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
1897    }
1898   
1899    [self applyFilter: nil];
1900}
1901
1902- (void) switchFilter: (id) sender
1903{
1904    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1905   
1906    NSButton * button;
1907    if ([filterType isEqualToString: FILTER_NONE])
1908        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1909    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1910        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1911    else if ([filterType isEqualToString: FILTER_SEED])
1912        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1913    else if ([filterType isEqualToString: FILTER_PAUSE])
1914        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1915    else
1916        button = fNoFilterButton;
1917   
1918    [self setFilter: button];
1919}
1920
1921- (void) updateControlTint: (NSNotification *) notification
1922{
1923    if ([fDefaults boolForKey: @"SpeedLimit"])
1924        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSGraphiteControlTint
1925            ? [NSImage imageNamed: @"SpeedLimitButtonGraphite.png"] : [NSImage imageNamed: @"SpeedLimitButtonBlue.png"]];
1926}
1927
1928- (void) toggleSpeedLimit: (id) sender
1929{
1930    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
1931    [fPrefsController applySpeedSettings: nil];
1932}
1933
1934- (void) autoSpeedLimitChange: (NSNotification *) notification
1935{
1936    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1937        return;
1938 
1939    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1940                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
1941        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1942                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
1943        * nowDate = [NSCalendarDate calendarDate];
1944   
1945    //check if should be on if within range
1946    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
1947        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
1948        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
1949   
1950    BOOL shouldBeOn = NO;
1951    if (onTime < offTime)
1952        shouldBeOn = onTime <= nowTime && nowTime < offTime;
1953    else if (onTime > offTime)
1954        shouldBeOn = onTime <= nowTime || nowTime < offTime;
1955    else;
1956   
1957    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
1958        [self toggleSpeedLimit: nil];
1959}
1960
1961- (void) autoSpeedLimit
1962{
1963    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1964        return;
1965   
1966    //only toggle if within first few seconds of minutes
1967    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
1968    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
1969        return;
1970   
1971    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1972                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
1973   
1974    BOOL toggle;
1975    if ([fDefaults boolForKey: @"SpeedLimit"])
1976        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
1977    else
1978    {
1979        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1980                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
1981        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
1982                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
1983    }
1984   
1985    if (toggle)
1986    {
1987        [self toggleSpeedLimit: nil];
1988       
1989        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
1990                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
1991                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
1992            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
1993            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1994    }
1995}
1996
1997- (void) setLimitGlobalEnabled: (id) sender
1998{
1999    [fPrefsController applySpeedSettings: nil];
2000}
2001
2002- (void) setQuickLimitGlobal: (id) sender
2003{
2004    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
2005    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
2006   
2007    [fPrefsController updateLimitFields];
2008    [fPrefsController applySpeedSettings: nil];
2009}
2010
2011- (void) setQuickRatioGlobal: (id) sender
2012{
2013    [fDefaults setBool: YES forKey: @"RatioCheck"];
2014    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
2015   
2016    [fPrefsController updateRatioStopField];
2017}
2018
2019- (void) torrentStoppedForRatio: (NSNotification *) notification
2020{
2021    Torrent * torrent = [notification object];
2022   
2023    [self updateTorrentsInQueue];
2024    [fInfoController updateInfoStats];
2025    [fInfoController updateOptions];
2026   
2027    if ([fDefaults boolForKey: @"PlaySeedingSound"])
2028    {
2029        NSSound * sound;
2030        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
2031            [sound play];
2032    }
2033   
2034    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
2035                                    [torrent dataLocation], @"Location", nil];
2036    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
2037                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2038                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2039}
2040
2041-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2042{
2043    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2044    {
2045        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2046            return;
2047       
2048        if (fAutoImportTimer)
2049        {
2050            if ([fAutoImportTimer isValid])
2051                [fAutoImportTimer invalidate];
2052            [fAutoImportTimer release];
2053            fAutoImportTimer = nil;
2054        }
2055       
2056        //check again in 10 seconds in case torrent file wasn't complete
2057        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2058            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2059       
2060        [self checkAutoImportDirectory];
2061    }
2062}
2063
2064- (void) changeAutoImport
2065{
2066    if (fAutoImportTimer)
2067    {
2068        if ([fAutoImportTimer isValid])
2069            [fAutoImportTimer invalidate];
2070        [fAutoImportTimer release];
2071        fAutoImportTimer = nil;
2072    }
2073   
2074    if (fAutoImportedNames)
2075        [fAutoImportedNames removeAllObjects];
2076    [self checkAutoImportDirectory];
2077}
2078
2079- (void) checkAutoImportDirectory
2080{
2081    NSString * path;
2082    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2083        return;
2084   
2085    path = [path stringByExpandingTildeInPath];
2086   
2087    NSArray * importedNames;
2088    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2089        return;
2090   
2091    //only check files that have not been checked yet
2092    NSMutableArray * newNames = [importedNames mutableCopy];
2093   
2094    if (fAutoImportedNames)
2095        [newNames removeObjectsInArray: fAutoImportedNames];
2096    else
2097        fAutoImportedNames = [[NSMutableArray alloc] init];
2098    [fAutoImportedNames setArray: importedNames];
2099   
2100    NSString * file;
2101    int i;
2102    for (i = [newNames count] - 1; i >= 0; i--)
2103    {
2104        file = [newNames objectAtIndex: i];
2105        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2106            [newNames removeObjectAtIndex: i];
2107        else
2108            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2109    }
2110   
2111    BOOL ask = [[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"];
2112   
2113    NSEnumerator * enumerator = [newNames objectEnumerator];
2114    int canAdd, count;
2115    while ((file = [enumerator nextObject]))
2116    {
2117        canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL);
2118        if (canAdd == TR_OK)
2119        {
2120            if (!ask)
2121                count = [fTorrents count];
2122            [self openFiles: [NSArray arrayWithObject: file]];
2123           
2124            //check if torrent was opened
2125            if (!ask && [fTorrents count] > count)
2126                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
2127                    "Growl notification title") description: [file lastPathComponent]
2128                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
2129        }
2130        else if (canAdd == TR_EINVALID)
2131            [fAutoImportedNames removeObject: [file lastPathComponent]];
2132        else;
2133    }
2134   
2135    [newNames release];
2136}
2137
2138- (void) beginCreateFile: (NSNotification *) notification
2139{
2140    if (![fDefaults boolForKey: @"AutoImport"])
2141        return;
2142   
2143    NSString * location = [notification object],
2144            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2145   
2146    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2147                                    isEqualToString: [path stringByExpandingTildeInPath]])
2148        [fAutoImportedNames addObject: [location lastPathComponent]];
2149}
2150
2151- (int) numberOfRowsInTableView: (NSTableView *) tableview
2152{
2153    return [fDisplayedTorrents count];
2154}
2155
2156- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
2157{
2158    return nil;
2159}
2160
2161- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes toPasteboard: (NSPasteboard *) pasteboard
2162{
2163    //only allow reordering of rows if sorting by order
2164    if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2165    {
2166        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2167        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2168        return YES;
2169    }
2170    return NO;
2171}
2172
2173- (NSDragOperation) tableView: (NSTableView *) tableView validateDrop: (id <NSDraggingInfo>) info
2174    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
2175{
2176    NSPasteboard * pasteboard = [info draggingPasteboard];
2177    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2178    {
2179        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
2180        return NSDragOperationGeneric;
2181    }
2182   
2183    return NSDragOperationNone;
2184}
2185
2186- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
2187    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
2188{
2189    NSPasteboard * pasteboard = [info draggingPasteboard];
2190    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2191    {
2192        //remember selected rows if needed
2193        NSArray * selectedTorrents = nil;
2194        int numSelected = [fTableView numberOfSelectedRows];
2195        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
2196            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
2197   
2198        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
2199                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2200       
2201        //determine where to move them
2202        int i;
2203        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2204            newRow--;
2205       
2206        //reinsert into array
2207        int insertIndex = newRow > 0 ? [[[fDisplayedTorrents objectAtIndex: newRow-1] orderValue] intValue] + 1 : 0;
2208       
2209        //get all torrents to reorder
2210        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
2211                                                @"orderValue" ascending: YES] autorelease];
2212        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
2213       
2214        NSMutableArray * sortedTorrents = [[fTorrents sortedArrayUsingDescriptors: descriptors] mutableCopy];
2215        [descriptors release];
2216       
2217        //remove objects to reinsert
2218        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
2219        [sortedTorrents removeObjectsInArray: movingTorrents];
2220       
2221        //insert objects at new location
2222        for (i = 0; i < [movingTorrents count]; i++)
2223            [sortedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2224       
2225        [movingTorrents release];
2226       
2227        //redo order values
2228        i = 0;
2229        for (i = 0; i < [sortedTorrents count]; i++)
2230            [[sortedTorrents objectAtIndex: i] setOrderValue: i];
2231       
2232        [sortedTorrents release];
2233       
2234        [self applyFilter: nil];
2235       
2236        //set selected rows if needed
2237        if (selectedTorrents)
2238        {
2239            Torrent * torrent;
2240            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
2241            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
2242            while ((torrent = [enumerator nextObject]))
2243                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
2244           
2245            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
2246            [indexSet release];
2247        }
2248    }
2249   
2250    return YES;
2251}
2252
2253- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2254{
2255    [fInfoController setInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
2256}
2257
2258- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2259{
2260    NSPasteboard * pasteboard = [info draggingPasteboard];
2261    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2262    {
2263        //check if any torrent files can be added
2264        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2265        NSEnumerator * enumerator = [files objectEnumerator];
2266        NSString * file;
2267        BOOL torrent = NO;
2268        int canAdd;
2269        while ((file = [enumerator nextObject]))
2270        {
2271            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2272            {
2273                switch (canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2274                {
2275                    case TR_OK:
2276                        if (!fOverlayWindow)
2277                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2278                        [fOverlayWindow setTorrents: files];
2279                       
2280                        return NSDragOperationCopy;
2281                   
2282                    case TR_EDUPLICATE:
2283                        torrent = YES;
2284                }
2285            }
2286        }
2287       
2288        //create a torrent file if a single file
2289        if (!torrent && [files count] == 1)
2290        {
2291            if (!fOverlayWindow)
2292                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2293            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2294           
2295            return NSDragOperationCopy;
2296        }
2297    }
2298    else if ([[pasteboard types] containsObject: NSURLPboardType])
2299    {
2300        if (!fOverlayWindow)
2301            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2302        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2303       
2304        return NSDragOperationCopy;
2305    }
2306    else;
2307   
2308    return NSDragOperationNone;
2309}
2310
2311- (void) draggingExited: (id <NSDraggingInfo>) info
2312{
2313    if (fOverlayWindow)
2314        [fOverlayWindow fadeOut];
2315}
2316
2317- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2318{
2319    if (fOverlayWindow)
2320        [fOverlayWindow fadeOut];
2321   
2322    NSPasteboard * pasteboard = [info draggingPasteboard];
2323    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2324    {
2325        BOOL torrent = NO, accept = YES;
2326       
2327        //create an array of files that can be opened
2328        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2329        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2330        NSEnumerator * enumerator = [files objectEnumerator];
2331        NSString * file;
2332        int canAdd;
2333        while ((file = [enumerator nextObject]))
2334        {
2335            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2336            {
2337                switch(tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2338                {
2339                    case TR_OK:
2340                        [filesToOpen addObject: file];
2341                        torrent = YES;
2342                        break;
2343                       
2344                    case TR_EDUPLICATE:
2345                        torrent = YES;
2346                }
2347            }
2348        }
2349       
2350        if ([filesToOpen count] > 0)
2351            [self application: NSApp openFiles: filesToOpen];
2352        else
2353        {
2354            if (!torrent && [files count] == 1)
2355                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2356            else
2357                accept = NO;
2358        }
2359        [filesToOpen release];
2360       
2361        return accept;
2362    }
2363    else if ([[pasteboard types] containsObject: NSURLPboardType])
2364    {
2365        NSURL * url;
2366        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2367        {
2368            [self openURL: url];
2369            return YES;
2370        }
2371    }
2372    else;
2373   
2374    return NO;
2375}
2376
2377- (void) toggleSmallView: (id) sender
2378{
2379    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2380    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2381   
2382    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2383   
2384    //window min height
2385    NSSize contentMinSize = [fWindow contentMinSize],
2386            contentSize = [[fWindow contentView] frame].size;
2387    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
2388                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2389    [fWindow setContentMinSize: contentMinSize];
2390   
2391    //resize for larger min height if not set to auto size
2392    if (![fDefaults boolForKey: @"AutoSize"])
2393    {
2394        if (!makeSmall && contentSize.height < contentMinSize.height)
2395        {
2396            NSRect frame = [fWindow frame];
2397            float heightChange = contentMinSize.height - contentSize.height;
2398            frame.size.height += heightChange;
2399            frame.origin.y -= heightChange;
2400           
2401            [fWindow setFrame: frame display: YES];
2402            [fTableView reloadData];
2403        }
2404    }
2405    else
2406        [self setWindowSizeToFit];
2407}
2408
2409- (void) togglePiecesBar: (id) sender
2410{
2411    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2412    [fTableView display];
2413}
2414
2415- (void) toggleAvailabilityBar: (id) sender
2416{
2417    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2418    [fTableView display];
2419}
2420
2421- (void) toggleStatusBar: (id) sender
2422{
2423    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2424    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2425}
2426
2427- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2428{
2429    //convert pixels to points
2430    NSRect windowFrame = [fWindow frame];
2431    NSSize windowSize = [fScrollView convertSize: windowFrame.size fromView: nil];
2432    windowSize.height += height;
2433   
2434    if (check)
2435    {
2436        NSSize minSize = [fScrollView convertSize: [fWindow minSize] fromView: nil];
2437       
2438        if (windowSize.height < minSize.height)
2439            windowSize.height = minSize.height;
2440        else
2441        {
2442            NSSize maxSize = [fScrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2443            if ([fStatusBar isHidden])
2444                maxSize.height -= [fStatusBar frame].size.height;
2445            if ([fFilterBar isHidden])
2446                maxSize.height -= [fFilterBar frame].size.height;
2447            if (windowSize.height > maxSize.height)
2448                windowSize.height = maxSize.height;
2449        }
2450    }
2451
2452    //convert points to pixels
2453    windowSize = [fScrollView convertSize: windowSize toView: nil];
2454
2455    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2456    windowFrame.size.height = windowSize.height;
2457    return windowFrame;
2458}
2459
2460- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2461{
2462    if (show != [fStatusBar isHidden])
2463        return;
2464
2465    if (show)
2466        [fStatusBar setHidden: NO];
2467
2468    NSRect frame;
2469    float heightChange = [fStatusBar frame].size.height;
2470    if (!show)
2471        heightChange *= -1;
2472   
2473    //allow bar to show even if not enough room
2474    if (show && ![fDefaults boolForKey: @"AutoSize"])
2475    {
2476        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2477        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2478        if (change < 0.0)
2479        {
2480            frame = [fWindow frame];
2481            frame.size.height += change;
2482            frame.origin.y -= change;
2483            [fWindow setFrame: frame display: NO animate: NO];
2484        }
2485    }
2486
2487    [self updateUI];
2488   
2489    //set views to not autoresize
2490    unsigned int statsMask = [fStatusBar autoresizingMask];
2491    unsigned int filterMask = [fFilterBar autoresizingMask];
2492    unsigned int scrollMask = [fScrollView autoresizingMask];
2493    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2494    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2495    [fScrollView setAutoresizingMask: NSViewNotSizable];
2496   
2497    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2498    [fWindow setFrame: frame display: YES animate: animate];
2499   
2500    //re-enable autoresize
2501    [fStatusBar setAutoresizingMask: statsMask];
2502    [fFilterBar setAutoresizingMask: filterMask];
2503    [fScrollView setAutoresizingMask: scrollMask];
2504   
2505    //change min size
2506    NSSize minSize = [fWindow contentMinSize];
2507    minSize.height += heightChange;
2508    [fWindow setContentMinSize: minSize];
2509   
2510    if (!show)
2511        [fStatusBar setHidden: YES];
2512}
2513
2514- (void) toggleFilterBar: (id) sender
2515{
2516    //disable filtering when hiding
2517    if (![fFilterBar isHidden])
2518    {
2519        [fSearchFilterField setStringValue: @""];
2520        [self setFilter: fNoFilterButton];
2521    }
2522
2523    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2524    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2525}
2526
2527- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2528{
2529    if (show != [fFilterBar isHidden])
2530        return;
2531
2532    if (show)
2533        [fFilterBar setHidden: NO];
2534
2535    NSRect frame;
2536    float heightChange = [fFilterBar frame].size.height;
2537    if (!show)
2538        heightChange *= -1;
2539   
2540    //allow bar to show even if not enough room
2541    if (show && ![fDefaults boolForKey: @"AutoSize"])
2542    {
2543        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2544        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2545        if (change < 0.0)
2546        {
2547            frame = [fWindow frame];
2548            frame.size.height += change;
2549            frame.origin.y -= change;
2550            [fWindow setFrame: frame display: NO animate: NO];
2551        }
2552    }
2553
2554    //set views to not autoresize
2555    unsigned int filterMask = [fFilterBar autoresizingMask];
2556    unsigned int scrollMask = [fScrollView autoresizingMask];
2557    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2558    [fScrollView setAutoresizingMask: NSViewNotSizable];
2559   
2560    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2561    [fWindow setFrame: frame display: YES animate: animate];
2562   
2563    //re-enable autoresize
2564    [fFilterBar setAutoresizingMask: filterMask];
2565    [fScrollView setAutoresizingMask: scrollMask];
2566   
2567    //change min size
2568    NSSize minSize = [fWindow contentMinSize];
2569    minSize.height += heightChange;
2570    [fWindow setContentMinSize: minSize];
2571   
2572    if (!show)
2573    {
2574        [fFilterBar setHidden: YES];
2575        [fWindow makeFirstResponder: fTableView];
2576    }
2577}
2578
2579- (void) doNothing: (id) sender {}
2580
2581- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2582{
2583    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
2584
2585    if ([ident isEqualToString: TOOLBAR_CREATE])
2586    {
2587        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
2588        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
2589        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
2590        [item setImage: [NSImage imageNamed: @"Create.png"]];
2591        [item setTarget: self];
2592        [item setAction: @selector(createFile:)];
2593        [item setAutovalidates: NO];
2594    }
2595    else if ([ident isEqualToString: TOOLBAR_OPEN])
2596    {
2597        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
2598        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
2599        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
2600        [item setImage: [NSImage imageNamed: @"Open.png"]];
2601        [item setTarget: self];
2602        [item setAction: @selector(openShowSheet:)];
2603        [item setAutovalidates: NO];
2604    }
2605    else if ([ident isEqualToString: TOOLBAR_REMOVE])
2606    {
2607        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
2608        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
2609        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
2610        [item setImage: [NSImage imageNamed: @"Remove.png"]];
2611        [item setTarget: self];
2612        [item setAction: @selector(removeNoDelete:)];
2613    }
2614    else if ([ident isEqualToString: TOOLBAR_INFO])
2615    {
2616        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
2617        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
2618        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
2619        [item setImage: [NSImage imageNamed: @"Info.png"]];
2620        [item setTarget: self];
2621        [item setAction: @selector(showInfo:)];
2622        [item setAutovalidates: NO];
2623    }
2624    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2625    {
2626        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
2627        [item setPaletteLabel: [item label]];
2628        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
2629        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
2630        [item setTarget: self];
2631        [item setAction: @selector(stopAllTorrents:)];
2632    }
2633    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2634    {
2635        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
2636        [item setPaletteLabel: [item label]];
2637        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
2638        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
2639        [item setTarget: self];
2640        [item setAction: @selector(resumeAllTorrents:)];
2641    }
2642    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2643    {
2644        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
2645        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
2646        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
2647        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
2648        [item setTarget: self];
2649        [item setAction: @selector(stopSelectedTorrents:)];
2650    }
2651    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2652    {
2653        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
2654        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
2655        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
2656        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
2657        [item setTarget: self];
2658        [item setAction: @selector(resumeSelectedTorrents:)];
2659    }
2660    else if ([ident isEqualToString: TOOLBAR_FILTER])
2661    {
2662        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
2663        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
2664        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
2665        [item setImage: [NSImage imageNamed: @"Filter.png"]];
2666        [item setTarget: self];
2667        [item setAction: @selector(toggleFilterBar:)];
2668        [item setAutovalidates: NO];
2669    }
2670    else
2671    {
2672        [item release];
2673        return nil;
2674    }
2675
2676    return [item autorelease];
2677}
2678
2679- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
2680{
2681    return [NSArray arrayWithObjects:
2682            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2683            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
2684            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
2685            NSToolbarSeparatorItemIdentifier,
2686            NSToolbarSpaceItemIdentifier,
2687            NSToolbarFlexibleSpaceItemIdentifier,
2688            NSToolbarCustomizeToolbarItemIdentifier, nil];
2689}
2690
2691- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
2692{
2693    return [NSArray arrayWithObjects:
2694            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2695            NSToolbarSeparatorItemIdentifier,
2696            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2697            NSToolbarFlexibleSpaceItemIdentifier,
2698            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2699}
2700
2701- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2702{
2703    NSString * ident = [toolbarItem itemIdentifier];
2704
2705    //enable remove item
2706    if ([ident isEqualToString: TOOLBAR_REMOVE])
2707        return [fTableView numberOfSelectedRows] > 0;
2708
2709    //enable pause all item
2710    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2711    {
2712        Torrent * torrent;
2713        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2714        while ((torrent = [enumerator nextObject]))
2715            if ([torrent isActive] || [torrent waitingToStart])
2716                return YES;
2717        return NO;
2718    }
2719
2720    //enable resume all item
2721    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2722    {
2723        Torrent * torrent;
2724        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2725        while ((torrent = [enumerator nextObject]))
2726            if (![torrent isActive] && ![torrent waitingToStart])
2727                return YES;
2728        return NO;
2729    }
2730
2731    //enable pause item
2732    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2733    {
2734        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2735        Torrent * torrent;
2736        while ((torrent = [enumerator nextObject]))
2737            if ([torrent isActive] || [torrent waitingToStart])
2738                return YES;
2739        return NO;
2740    }
2741   
2742    //enable resume item
2743    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2744    {
2745        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2746        Torrent * torrent;
2747        while ((torrent = [enumerator nextObject]))
2748            if (![torrent isActive] && ![torrent waitingToStart])
2749                return YES;
2750        return NO;
2751    }
2752
2753    return YES;
2754}
2755
2756- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2757{
2758    SEL action = [menuItem action];
2759   
2760    if (action == @selector(toggleSpeedLimit:))
2761    {
2762        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
2763        return YES;
2764    }
2765   
2766    //only enable some items if it is in a context menu or the window is useable
2767    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
2768
2769    //enable open items
2770    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
2771        return [fWindow attachedSheet] == nil;
2772   
2773    //enable sort options
2774    if (action == @selector(setSort:))
2775    {
2776        NSString * sortType;
2777        switch ([menuItem tag])
2778        {
2779            case SORT_ORDER_TAG:
2780                sortType = SORT_ORDER;
2781                break;
2782            case SORT_DATE_TAG:
2783                sortType = SORT_DATE;
2784                break;
2785            case SORT_NAME_TAG:
2786                sortType = SORT_NAME;
2787                break;
2788            case SORT_PROGRESS_TAG:
2789                sortType = SORT_PROGRESS;
2790                break;
2791            case SORT_STATE_TAG:
2792                sortType = SORT_STATE;
2793                break;
2794            case SORT_TRACKER_TAG:
2795                sortType = SORT_TRACKER;
2796                break;
2797            default:
2798                sortType = @"";
2799        }
2800       
2801        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
2802        return [fWindow isVisible];
2803    }
2804   
2805    if (action == @selector(toggleSmallView:))
2806    {
2807        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
2808        return [fWindow isVisible];
2809    }
2810   
2811    if (action == @selector(togglePiecesBar:))
2812    {
2813        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
2814        return [fWindow isVisible];
2815    }
2816   
2817    if (action == @selector(toggleAvailabilityBar:))
2818    {
2819        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
2820        return [fWindow isVisible];
2821    }
2822
2823    //enable show info
2824    if (action == @selector(showInfo:))
2825    {
2826        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
2827                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2828        [menuItem setTitle: title];
2829
2830        return YES;
2831    }
2832   
2833    //enable prev/next inspector tab
2834    if (action == @selector(setInfoTab:))
2835        return [[fInfoController window] isVisible];
2836   
2837    //enable toggle status bar
2838    if (action == @selector(toggleStatusBar:))
2839    {
2840        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2841                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2842        [menuItem setTitle: title];
2843
2844        return [fWindow isVisible];
2845    }
2846   
2847    //enable toggle filter bar
2848    if (action == @selector(toggleFilterBar:))
2849    {
2850        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2851                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2852        [menuItem setTitle: title];
2853
2854        return [fWindow isVisible];
2855    }
2856   
2857    //enable prev/next filter button
2858    if (action == @selector(switchFilter:))
2859        return [fWindow isVisible] && ![fFilterBar isHidden];
2860
2861    //enable reveal in finder
2862    if (action == @selector(revealFile:))
2863        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2864
2865    //enable remove items
2866    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2867        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2868    {
2869        BOOL warning = NO,
2870            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2871            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2872       
2873        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2874        Torrent * torrent;
2875        while ((torrent = [enumerator nextObject]))
2876        {
2877            if (!warning && [torrent isActive])
2878            {
2879                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2880                if (warning && canDelete)
2881                    break;
2882            }
2883            if (!canDelete && [torrent publicTorrent])
2884            {
2885                canDelete = YES;
2886                if (warning)
2887                    break;
2888            }
2889        }
2890   
2891        //append or remove ellipsis when needed
2892        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2893        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2894        {
2895            if (![title hasSuffix: ellipsis])
2896                [menuItem setTitle: [title stringByAppendingEllipsis]];
2897        }
2898        else
2899        {
2900            if ([title hasSuffix: ellipsis])
2901                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2902        }
2903       
2904        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2905    }
2906
2907    //enable pause all item
2908    if (action == @selector(stopAllTorrents:))
2909    {
2910        Torrent * torrent;
2911        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2912        while ((torrent = [enumerator nextObject]))
2913            if ([torrent isActive] || [torrent waitingToStart])
2914                return YES;
2915        return NO;
2916    }
2917   
2918    //enable resume all item
2919    if (action == @selector(resumeAllTorrents:))
2920    {
2921        Torrent * torrent;
2922        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2923        while ((torrent = [enumerator nextObject]))
2924            if (![torrent isActive] && ![torrent waitingToStart])
2925                return YES;
2926        return NO;
2927    }
2928   
2929    //enable resume all waiting item
2930    if (action == @selector(resumeWaitingTorrents:))
2931    {
2932        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2933            return NO;
2934   
2935        Torrent * torrent;
2936        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2937        while ((torrent = [enumerator nextObject]))
2938            if (![torrent isActive] && [torrent waitingToStart])
2939                return YES;
2940        return NO;
2941    }
2942   
2943    //enable resume selected waiting item
2944    if (action == @selector(resumeSelectedTorrentsNoWait:))
2945    {
2946        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
2947            return NO;
2948   
2949        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2950        Torrent * torrent;
2951        while ((torrent = [enumerator nextObject]))
2952            if (![torrent isActive])
2953                return YES;
2954        return NO;
2955    }
2956
2957    //enable pause item
2958    if (action == @selector(stopSelectedTorrents:))
2959    {
2960        if (!canUseTable)
2961            return NO;
2962   
2963        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2964        Torrent * torrent;
2965        while ((torrent = [enumerator nextObject]))
2966            if ([torrent isActive] || [torrent waitingToStart])
2967                return YES;
2968        return NO;
2969    }
2970   
2971    //enable resume item
2972    if (action == @selector(resumeSelectedTorrents:))
2973    {
2974        if (!canUseTable)
2975            return NO;
2976   
2977        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2978        Torrent * torrent;
2979        while ((torrent = [enumerator nextObject]))
2980            if (![torrent isActive] && ![torrent waitingToStart])
2981                return YES;
2982        return NO;
2983    }
2984   
2985    //enable manual announce item
2986    if (action == @selector(announceSelectedTorrents:))
2987    {
2988        if (!canUseTable)
2989            return NO;
2990       
2991        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2992        Torrent * torrent;
2993        while ((torrent = [enumerator nextObject]))
2994            if ([torrent canManualAnnounce])
2995                return YES;
2996        return NO;
2997    }
2998   
2999    //enable reset cache item
3000    if (action == @selector(resetCacheForSelectedTorrents:))
3001        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3002   
3003    //enable move torrent file item
3004    if (action == @selector(moveDataFiles:))
3005        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3006   
3007    //enable copy torrent file item
3008    if (action == @selector(copyTorrentFiles:))
3009        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3010   
3011    //enable reverse sort item
3012    if (action == @selector(setSortReverse:))
3013    {
3014        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3015        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3016    }
3017   
3018    //check proper filter search item
3019    if (action == @selector(setFilterSearchType:))
3020    {
3021        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3022       
3023        BOOL state;
3024        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3025            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3026        else
3027            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3028       
3029        [menuItem setState: state ? NSOnState : NSOffState];
3030        return YES;
3031    }
3032   
3033    return YES;
3034}
3035
3036- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
3037{
3038    NSEnumerator * enumerator;
3039    Torrent * torrent;
3040    BOOL allowSleep;
3041
3042    switch (messageType)
3043    {
3044        case kIOMessageSystemWillSleep:
3045            //close all connections before going to sleep and remember we should resume when we wake up
3046            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3047
3048            //wait for running transfers to stop (5 second timeout)
3049            NSDate * start = [NSDate date];
3050            BOOL timeUp = NO;
3051           
3052            enumerator = [fTorrents objectEnumerator];
3053            while (!timeUp && (torrent = [enumerator nextObject]))
3054                while ([torrent isActive] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
3055                {
3056                    usleep(100000);
3057                    [torrent update];
3058                }
3059
3060            IOAllowPowerChange(fRootPort, (long) messageArgument);
3061            break;
3062
3063        case kIOMessageCanSystemSleep:
3064            allowSleep = YES;
3065            if ([fDefaults boolForKey: @"SleepPrevent"])
3066            {
3067                //prevent idle sleep unless no torrents are active
3068                enumerator = [fTorrents objectEnumerator];
3069                while ((torrent = [enumerator nextObject]))
3070                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3071                    {
3072                        allowSleep = NO;
3073                        break;
3074                    }
3075            }
3076
3077            if (allowSleep)
3078                IOAllowPowerChange(fRootPort, (long) messageArgument);
3079            else
3080                IOCancelPowerChange(fRootPort, (long) messageArgument);
3081            break;
3082
3083        case kIOMessageSystemHasPoweredOn:
3084            //resume sleeping transfers after we wake up
3085            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3086            [self autoSpeedLimitChange: nil];
3087            break;
3088    }
3089}
3090
3091- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3092{
3093    int seeding = 0, downloading = 0;
3094    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3095    Torrent * torrent;
3096    while ((torrent = [enumerator nextObject]))
3097    {
3098        if ([torrent isSeeding])
3099            seeding++;
3100        else if ([torrent isActive])
3101            downloading++;
3102        else;
3103    }
3104   
3105    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3106            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3107   
3108    BOOL hasSeparator = seedingItem || downloadingItem;
3109   
3110    if (seeding > 0)
3111    {
3112        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding",
3113                                                        "Dock item - Seeding"), seeding];
3114        if (!seedingItem)
3115        {
3116            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3117            [seedingItem setTag: DOCK_SEEDING_TAG];
3118            [fDockMenu insertItem: seedingItem atIndex: 0];
3119        }
3120        else
3121            [seedingItem setTitle: title];
3122    }
3123    else
3124    {
3125        if (seedingItem)
3126            [fDockMenu removeItem: seedingItem];
3127    }
3128   
3129    if (downloading > 0)
3130    {
3131        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading",
3132                                                        "Dock item - Downloading"), downloading];
3133        if (!downloadingItem)
3134        {
3135            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3136            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3137            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3138        }
3139        else
3140            [downloadingItem setTitle: title];
3141    }
3142    else
3143    {
3144        if (downloadingItem)
3145            [fDockMenu removeItem: downloadingItem];
3146    }
3147   
3148    if (seeding > 0 || downloading > 0)
3149    {
3150        if (!hasSeparator)
3151            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3152    }
3153    else
3154    {
3155        if (hasSeparator)
3156            [fDockMenu removeItemAtIndex: 0];
3157    }
3158   
3159    return fDockMenu;
3160}
3161
3162- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3163{
3164    //if auto size is enabled, the current frame shouldn't need to change
3165    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3166   
3167    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3168    return frame;
3169}
3170
3171- (void) setWindowSizeToFit
3172{
3173    if ([fDefaults boolForKey: @"AutoSize"])
3174    {
3175        [fScrollView setHasVerticalScroller: NO];
3176        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3177        [fScrollView setHasVerticalScroller: YES];
3178    }
3179}
3180
3181- (NSRect) sizedWindowFrame
3182{
3183    float heightChange = [fDisplayedTorrents count] * ([fTableView rowHeight] +
3184            [fTableView intercellSpacing].height) - [fScrollView frame].size.height;
3185    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3186}
3187
3188- (void) showMainWindow: (id) sender
3189{
3190    [fWindow makeKeyAndOrderFront: nil];
3191}
3192
3193- (void) windowDidBecomeMain: (NSNotification *) notification
3194{
3195    [fBadger clearCompleted];
3196    [self updateUI];
3197}
3198
3199- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3200{
3201    //only resize horizontally if autosize is enabled
3202    if ([fDefaults boolForKey: @"AutoSize"])
3203        proposedFrameSize.height = [fWindow frame].size.height;
3204    return proposedFrameSize;
3205}
3206
3207- (void) windowDidResize: (NSNotification *) notification
3208{
3209    //size search filter to not overlap buttons
3210    float pointX = NSMaxX([fPauseFilterButton frame]) + 5.0;
3211    NSRect oldFrame = [fSearchFilterField frame],
3212            frame = NSMakeRect(pointX, oldFrame.origin.y, NSMaxX(oldFrame) - pointX, oldFrame.size.height);
3213   
3214    BOOL show = frame.size.width >= SEARCH_FILTER_MIN_WIDTH;
3215    if (show)
3216    {
3217        //make sure it is not too long
3218        if (frame.size.width > SEARCH_FILTER_MAX_WIDTH)
3219        {
3220            float different = frame.size.width - SEARCH_FILTER_MAX_WIDTH;
3221            frame.origin.x += different;
3222            frame.size.width -= different;
3223        }
3224        [fSearchFilterField setFrame: frame];
3225    }
3226   
3227    //hide search filter if it overlaps filter buttons
3228    [fSearchFilterField setHidden: !show];
3229}
3230
3231- (void) applicationWillUnhide: (NSNotification *) notification
3232{
3233    [self updateUI];
3234}
3235
3236- (void) linkHomepage: (id) sender
3237{
3238    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
3239}
3240
3241- (void) linkForums: (id) sender
3242{
3243    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
3244}
3245
3246- (void) linkDonate: (id) sender
3247{
3248    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
3249}
3250
3251- (void) prepareForUpdate: (NSNotification *) notification
3252{
3253    fUpdateInProgress = YES;
3254}
3255
3256- (NSDictionary *) registrationDictionaryForGrowl
3257{
3258    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
3259                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
3260    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
3261                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
3262}
3263
3264- (void) growlNotificationWasClicked: (id) clickContext
3265{
3266    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
3267        return;
3268   
3269    NSString * type = [clickContext objectForKey: @"Type"], * location;
3270    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
3271            && (location = [clickContext objectForKey: @"Location"]))
3272        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
3273}
3274
3275- (void) ipcQuit
3276{
3277    fRemoteQuit = YES;
3278    [NSApp terminate: self];
3279}
3280
3281- (NSArray *) ipcGetTorrentsByID: (NSArray *) idlist
3282{
3283    if (!idlist)
3284        return fTorrents;
3285   
3286    NSMutableArray * torrents = [NSMutableArray array];
3287   
3288    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * idEnum;
3289    int torId;
3290    Torrent * torrent;
3291    NSNumber * tempId;
3292    while ((torrent = [torrentEnum nextObject]))
3293    {
3294        torId = [torrent torrentID];
3295       
3296        idEnum = [idlist objectEnumerator];
3297        while ((tempId = [idEnum nextObject]))
3298        {
3299            if ([tempId intValue] == torId)
3300            {
3301                [torrents addObject: torrent];
3302                break;
3303            }
3304        }
3305    }
3306
3307    return torrents;
3308}
3309
3310- (NSArray *) ipcGetTorrentsByHash: (NSArray *) hashlist
3311{
3312    if (!hashlist)
3313        return fTorrents;
3314   
3315    NSMutableArray * torrents = [NSMutableArray array];
3316   
3317    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * hashEnum;
3318    NSString * torHash, * tempHash;
3319    Torrent * torrent;
3320    while ((torrent = [torrentEnum nextObject]))
3321    {
3322        torHash = [torrent hashString];
3323       
3324        hashEnum = [hashlist objectEnumerator];
3325        while ((tempHash = [hashEnum nextObject]))
3326        {
3327            if ([torHash caseInsensitiveCompare: tempHash] == NSOrderedSame)
3328            {
3329                [torrents addObject: torrent];
3330                break;
3331            }
3332        }
3333    }
3334   
3335    return torrents;
3336}
3337
3338- (BOOL) ipcAddTorrents: (NSArray *) torrents
3339{
3340    int oldCount = [fTorrents count];
3341   
3342    [self openFiles: torrents];
3343   
3344    return [fTorrents count] > oldCount;
3345}
3346
3347- (BOOL) ipcAddTorrentFile: (NSString *) path directory: (NSString *) directory
3348{
3349    int oldCount = [fTorrents count];
3350   
3351    [self openFiles: [NSArray arrayWithObject: path] forcePath: directory ignoreDownloadFolder: NO
3352            deleteTorrentFile: TORRENT_FILE_DEFAULT];
3353   
3354    return [fTorrents count] > oldCount;
3355}
3356
3357- (BOOL) ipcAddTorrentFileAutostart: (NSString *) path directory: (NSString *) directory autostart: (BOOL) autostart
3358{
3359    /* 'path' is path to torrent file, 'dir' is the directory it
3360       should download it's files to and may be nil, 'autostart' is a
3361       boolean indicating if the torrent should be automatically
3362       started (or queued to start, I guess), should return NO if
3363       torrent fails to load */
3364    return NO;
3365}
3366
3367- (BOOL) ipcAddTorrentData: (NSData *) data directory: (NSString *) directory
3368{
3369    /* 'data' is the contents of a torrent file, 'directory' is the
3370       directory it should download it's files to and may be nil,
3371       should return NO if torrent fails to load */
3372    return NO;
3373}
3374
3375- (BOOL) ipcAddTorrentDataAutostart: (NSData *) path directory: (NSString *) directory autostart: (BOOL) autostart
3376{
3377    /* 'data' is the contents of a torrent file, 'directory' is the
3378       directory it should download it's files to and may be nil,
3379       'autostart' is a boolean indicating if the torrent should be
3380       automatically started (or queued to start, I guess), should
3381       return NO if torrent fails to load */
3382    return NO;
3383}
3384
3385- (BOOL) ipcStartTorrents: (NSArray *) torrents
3386{
3387    if (!torrents)
3388        [self resumeAllTorrents: self];
3389    else
3390        [self resumeTorrents: torrents];
3391
3392    return YES;
3393}
3394
3395- (BOOL) ipcStopTorrents: (NSArray *) torrents
3396{
3397    if (!torrents)
3398        [self stopAllTorrents: self];
3399    else
3400        [self stopTorrents: torrents];
3401
3402    return YES;
3403}
3404
3405- (BOOL) ipcRemoveTorrents: (NSArray *) torrents
3406{
3407    if (!torrents)
3408        torrents = [NSArray arrayWithArray: fTorrents];
3409
3410    [self confirmRemoveTorrents: torrents deleteData: NO deleteTorrent: NO];
3411
3412    return YES;
3413}
3414
3415@end
Note: See TracBrowser for help on using the repository browser.