source: trunk/macosx/Controller.m @ 3640

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

trunk: Leopard: Fix bug with toggling Minimal View

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