source: trunk/macosx/Controller.m @ 3922

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

get building again

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