source: trunk/macosx/Controller.m @ 3560

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

filtering by a search string for tracker now checks all trackers in the announce-list

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