source: trunk/macosx/Controller.m @ 3563

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

fix mistake in [3560]

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