source: branches/0.9x/macosx/Controller.m @ 3642

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

0.9x: fix last commit

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