source: trunk/macosx/Controller.m @ 3588

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

suppress a warning on Leopard

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