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

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

suppress a warning on Leopard

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