source: trunk/macosx/Controller.m @ 1080

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

use bindings for speed limit

  • Property svn:keywords set to Date Rev Author Id
File size: 86.8 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 1080 2006-11-11 21:03:50Z livings124 $
3 *
4 * Copyright (c) 2005-2006 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 "StringAdditions.h"
32#import "UKKQueue.h"
33#import "ActionMenuSpeedToDisplayLimitTransformer.h"
34#import "ActionMenuRatioToDisplayRatioTransformer.h"
35#import "ExpandedPathToPathTransformer.h"
36#import "ExpandedPathToIconTransformer.h"
37#import "SpeedLimitToTurtleIconTransformer.h"
38
39#import <Sparkle/Sparkle.h>
40
41#define TOOLBAR_OPEN            @"Toolbar Open"
42#define TOOLBAR_REMOVE          @"Toolbar Remove"
43#define TOOLBAR_INFO            @"Toolbar Info"
44#define TOOLBAR_PAUSE_ALL       @"Toolbar Pause All"
45#define TOOLBAR_RESUME_ALL      @"Toolbar Resume All"
46#define TOOLBAR_PAUSE_SELECTED  @"Toolbar Pause Selected"
47#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected"
48#define TOOLBAR_FILTER          @"Toolbar Toggle Filter"
49
50#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
51#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
52#define GROWL_AUTO_ADD          @"Torrent Auto Added"
53#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
54
55#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
56
57#define ROW_HEIGHT_REGULAR      65.0
58#define ROW_HEIGHT_SMALL        40.0
59#define WINDOW_REGULAR_WIDTH    468.0
60
61#define UPDATE_UI_SECONDS           1.0
62#define AUTO_SPEED_LIMIT_SECONDS    5.0
63
64#define WEBSITE_URL @"http://transmission.m0k.org/"
65#define FORUM_URL   @"http://transmission.m0k.org/forum/"
66
67static void sleepCallBack(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
68{
69    Controller * c = controller;
70    [c sleepCallBack: messageType argument: messageArgument];
71}
72
73@implementation Controller
74
75+ (void) initialize
76{
77    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
78        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
79   
80    //set custom value transformers
81    ActionMenuSpeedToDisplayLimitTransformer * limitTransformer =
82                        [[[ActionMenuSpeedToDisplayLimitTransformer alloc] init] autorelease];
83    [NSValueTransformer setValueTransformer: limitTransformer forName: @"ActionMenuSpeedToDisplayLimitTransformer"];
84   
85    ActionMenuRatioToDisplayRatioTransformer * ratioTransformer =
86                        [[[ActionMenuRatioToDisplayRatioTransformer alloc] init] autorelease];
87    [NSValueTransformer setValueTransformer: ratioTransformer forName: @"ActionMenuRatioToDisplayRatioTransformer"];
88   
89    ExpandedPathToPathTransformer * pathTransformer =
90                        [[[ExpandedPathToPathTransformer alloc] init] autorelease];
91    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
92   
93    ExpandedPathToIconTransformer * iconTransformer =
94                        [[[ExpandedPathToIconTransformer alloc] init] autorelease];
95    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
96   
97    SpeedLimitToTurtleIconTransformer * speedLimitIconTransformer =
98                        [[[SpeedLimitToTurtleIconTransformer alloc] init] autorelease];
99    [NSValueTransformer setValueTransformer: speedLimitIconTransformer forName: @"SpeedLimitToTurtleIconTransformer"];
100}
101
102- (id) init
103{
104    if ((self = [super init]))
105    {
106        fLib = tr_init();
107       
108        fTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
109        fDisplayedTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
110       
111        fDefaults = [NSUserDefaults standardUserDefaults];
112       
113        fMessageController = [[MessageWindowController alloc] initWithWindowNibName: @"MessageWindow"];
114        fInfoController = [[InfoWindowController alloc] initWithWindowNibName: @"InfoWindow"];
115        fPrefsController = [[PrefsController alloc] initWithWindowNibName: @"PrefsWindow" handle: fLib];
116       
117        fBadger = [[Badger alloc] init];
118       
119        [GrowlApplicationBridge setGrowlDelegate: self];
120       
121        [[UKKQueue sharedFileWatcher] setDelegate: self];
122    }
123    return self;
124}
125
126- (void) dealloc
127{
128    [[NSNotificationCenter defaultCenter] removeObserver: self];
129   
130    [fInfoController release];
131    [fMessageController release];
132    [fPrefsController release];
133   
134    [fToolbar release];
135    [fTorrents release];
136    [fDisplayedTorrents release];
137    [fBadger release];
138   
139    [fSortType release];
140    [fFilterType release];
141   
142    [fAutoImportedNames release];
143   
144    tr_close(fLib);
145    [super dealloc];
146}
147
148- (void) awakeFromNib
149{
150    [fStatusBar setBackgroundImage: [NSImage imageNamed: @"StatusBarBackground.png"]];
151    [fFilterBar setBackgroundImage: [NSImage imageNamed: @"FilterBarBackground.png"]];
152   
153    [fWindow setAcceptsMouseMovedEvents: YES]; //ensure filter buttons display correctly
154
155    fToolbar = [[NSToolbar alloc] initWithIdentifier: @"Transmission Toolbar"];
156    [fToolbar setDelegate: self];
157    [fToolbar setAllowsUserCustomization: YES];
158    [fToolbar setAutosavesConfiguration: YES];
159    [fWindow setToolbar: fToolbar];
160    [fWindow setDelegate: self];
161   
162    [fWindow makeFirstResponder: fTableView];
163    [fWindow setExcludedFromWindowsMenu: YES];
164   
165    //set table size
166    if ([fDefaults boolForKey: @"SmallView"])
167        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
168   
169    //window min height
170    NSSize contentMinSize = [fWindow contentMinSize];
171    contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
172                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
173    [fWindow setContentMinSize: contentMinSize];
174   
175    //set info and filter keyboard shortcuts
176    unichar rightChar = NSRightArrowFunctionKey, leftChar = NSLeftArrowFunctionKey;
177    [fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & rightChar length: 1]];
178    [fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & leftChar length: 1]];
179   
180    [fNextFilterItem setKeyEquivalent: [NSString stringWithCharacters: & rightChar length: 1]];
181    [fNextFilterItem setKeyEquivalentModifierMask: NSCommandKeyMask + NSAlternateKeyMask];
182    [fPrevFilterItem setKeyEquivalent: [NSString stringWithCharacters: & leftChar length: 1]];
183    [fPrevFilterItem setKeyEquivalentModifierMask: NSCommandKeyMask + NSAlternateKeyMask];
184   
185    //set up filter bar
186    NSView * contentView = [fWindow contentView];
187    [fFilterBar setHidden: YES];
188   
189    NSRect filterBarFrame = [fFilterBar frame];
190    filterBarFrame.size.width = [fWindow frame].size.width;
191    [fFilterBar setFrame: filterBarFrame];
192   
193    [contentView addSubview: fFilterBar];
194    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
195   
196    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
197   
198    //set up status bar
199    [fStatusBar setHidden: YES];
200   
201    NSRect statusBarFrame = [fStatusBar frame];
202    statusBarFrame.size.width = [fWindow frame].size.width;
203    [fStatusBar setFrame: statusBarFrame];
204   
205    [contentView addSubview: fStatusBar];
206    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
207    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
208
209    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
210                                "Main window -> 1st bottom left button (action) tooltip")];
211    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
212                                "Main window -> 2nd bottom left button (turtle) tooltip")];
213   
214    [fPrefsController setUpdater: fUpdater];
215   
216    [fTableView setTorrents: fDisplayedTorrents];
217    [[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell: [[TorrentCell alloc] init]];
218
219    [fTableView registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType,
220                                                        TORRENT_TABLE_VIEW_DATA_TYPE, nil]];
221
222    //register for sleep notifications
223    IONotificationPortRef notify;
224    io_object_t iterator;
225    if (fRootPort = IORegisterForSystemPower(self, & notify, sleepCallBack, & iterator))
226        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
227    else
228        NSLog(@"Could not IORegisterForSystemPower");
229
230    //load torrents from history
231    Torrent * torrent;
232    NSDictionary * historyItem;
233    NSEnumerator * enumerator = [[fDefaults arrayForKey: @"History"] objectEnumerator];
234    while ((historyItem = [enumerator nextObject]))
235        if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
236        {
237            [fTorrents addObject: torrent];
238            [torrent release];
239        }
240   
241    //set sort
242    fSortType = [[fDefaults stringForKey: @"Sort"] retain];
243   
244    NSMenuItem * currentSortItem, * currentSortActionItem;
245    if ([fSortType isEqualToString: @"Name"])
246    {
247        currentSortItem = fNameSortItem;
248        currentSortActionItem = fNameSortActionItem;
249    }
250    else if ([fSortType isEqualToString: @"State"])
251    {
252        currentSortItem = fStateSortItem;
253        currentSortActionItem = fStateSortActionItem;
254    }
255    else if ([fSortType isEqualToString: @"Progress"])
256    {
257        currentSortItem = fProgressSortItem;
258        currentSortActionItem = fProgressSortActionItem;
259    }
260    else if ([fSortType isEqualToString: @"Date"])
261    {
262        currentSortItem = fDateSortItem;
263        currentSortActionItem = fDateSortActionItem;
264    }
265    else
266    {
267        currentSortItem = fOrderSortItem;
268        currentSortActionItem = fOrderSortActionItem;
269    }
270    [currentSortItem setState: NSOnState];
271    [currentSortActionItem setState: NSOnState];
272   
273    //set filter
274    fFilterType = [[fDefaults stringForKey: @"Filter"] retain];
275
276    BarButton * currentFilterButton;
277    if ([fFilterType isEqualToString: @"Pause"])
278        currentFilterButton = fPauseFilterButton;
279    else if ([fFilterType isEqualToString: @"Seed"])
280        currentFilterButton = fSeedFilterButton;
281    else if ([fFilterType isEqualToString: @"Download"])
282        currentFilterButton = fDownloadFilterButton;
283    else
284        currentFilterButton = fNoFilterButton;
285
286    [currentFilterButton setEnabled: YES];
287   
288    //observe notifications
289    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
290   
291    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
292                    name: @"TorrentFinishedDownloading" object: nil];
293   
294    [nc addObserver: self selector: @selector(updateControlTint:)
295                    name: NSControlTintDidChangeNotification object: nil];
296   
297    [nc addObserver: self selector: @selector(prepareForUpdate:)
298                    name: SUUpdaterWillRestartNotification object: nil];
299    fUpdateInProgress = NO;
300   
301    [nc addObserver: self selector: @selector(autoSpeedLimitChange:)
302                    name: @"AutoSpeedLimitChange" object: nil];
303   
304    [nc addObserver: self selector: @selector(changeAutoImport)
305                    name: @"AutoImportSettingChange" object: nil];
306   
307    [nc addObserver: self selector: @selector(setWindowSizeToFit)
308                    name: @"AutoSizeSettingChange" object: nil];
309   
310    //check to start another because of stopped torrent
311    [nc addObserver: self selector: @selector(checkWaitingForStopped:)
312                    name: @"StoppedDownloading" object: nil];
313   
314    //check all torrents for starting
315    [nc addObserver: self selector: @selector(globalStartSettingChange:)
316                    name: @"GlobalStartSettingChange" object: nil];
317   
318    //check if torrent should now start
319    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
320                    name: @"TorrentStoppedForRatio" object: nil];
321   
322    //change that just impacts the dock badge
323    [nc addObserver: self selector: @selector(resetDockBadge:)
324                    name: @"DockBadgeChange" object: nil];
325
326    //timer to update the interface every second
327    fCompleted = 0;
328    [self updateUI: nil];
329    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
330        selector: @selector(updateUI:) userInfo: nil repeats: YES];
331    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
332    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
333   
334    [self applyFilter: nil];
335   
336    [fWindow makeKeyAndOrderFront: nil];
337
338    if ([fDefaults boolForKey: @"InfoVisible"])
339        [self showInfo: nil];
340   
341    //timer to auto toggle speed limit
342    [self autoSpeedLimitChange: nil];
343    fSpeedLimitTimer = [NSTimer scheduledTimerWithTimeInterval: AUTO_SPEED_LIMIT_SECONDS target: self
344        selector: @selector(autoSpeedLimit:) userInfo: nil repeats: YES];
345   
346    //auto importing
347    fAutoImportedNames = [[NSMutableArray alloc] init];
348    [self checkAutoImportDirectory];
349}
350
351- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
352{
353    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
354        [fWindow makeKeyAndOrderFront: nil];
355    return NO;
356}
357
358- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
359{
360    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
361    {
362        int active = 0, downloading = 0;
363        Torrent * torrent;
364        NSEnumerator * enumerator = [fTorrents objectEnumerator];
365        while ((torrent = [enumerator nextObject]))
366            if ([torrent isActive])
367            {
368                active++;
369                if (![torrent isSeeding])
370                    downloading++;
371            }
372
373        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
374        {
375            NSString * message = active == 1
376                ? NSLocalizedString(@"There is an active transfer. Do you really want to quit?",
377                    "Confirm Quit panel -> message")
378                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers. Do you really want to quit?",
379                    "Confirm Quit panel -> message"), active];
380
381            NSBeginAlertSheet(NSLocalizedString(@"Confirm Quit", "Confirm Quit panel -> title"),
382                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
383                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
384                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
385            return NSTerminateLater;
386        }
387    }
388
389    return NSTerminateNow;
390}
391
392- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
393{
394    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
395}
396
397- (void) applicationWillTerminate: (NSNotification *) notification
398{
399    //stop timers
400    [fSpeedLimitTimer invalidate];
401    [fTimer invalidate];
402   
403    //save history and stop running torrents
404    [self updateTorrentHistory];
405    [fTorrents makeObjectsPerformSelector: @selector(stopTransferForQuit)];
406   
407    //disable NAT traversal
408    tr_natTraversalDisable(fLib);
409   
410    //remember window states and close all windows
411    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
412    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
413    [self showStatusBar: NO animate: NO];
414    [self showFilterBar: NO animate: NO];
415   
416    //clear badge
417    [fBadger clearBadge];
418
419    //end quickly if the app is updating
420    if (fUpdateInProgress)
421        return;
422
423    //wait for running transfers to stop (5 second timeout) and for NAT to be disabled
424    NSDate * start = [NSDate date];
425    BOOL timeUp = NO;
426   
427    NSEnumerator * enumerator = [fTorrents objectEnumerator];
428    Torrent * torrent;
429    while (!timeUp && ((torrent = [enumerator nextObject]) || tr_natTraversalStatus(fLib) != TR_NAT_TRAVERSAL_DISABLED))
430        while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
431        {
432            usleep(100000);
433            [torrent update];
434        }
435}
436
437- (void) application: (NSApplication *) sender openFiles: (NSArray *) filenames
438{
439    [self openFiles: filenames ignoreDownloadFolder: NO];
440}
441
442- (void) openFiles: (NSArray *) filenames ignoreDownloadFolder: (BOOL) ignore
443{
444    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"], * torrentPath;
445   
446    if (ignore || [downloadChoice isEqualToString: @"Ask"])
447    {
448        [self openFilesAsk: [filenames mutableCopy]];
449        return;
450    }
451   
452    Torrent * torrent;
453    NSEnumerator * enumerator = [filenames objectEnumerator];
454    while ((torrentPath = [enumerator nextObject]))
455    {
456        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
457            continue;
458
459        //add it to the "File > Open Recent" menu
460        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
461
462        NSString * folder = [downloadChoice isEqualToString: @"Constant"]
463            ? [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]
464            : [torrentPath stringByDeletingLastPathComponent];
465       
466        [torrent setDownloadFolder: folder];
467        [torrent update];
468        [self attemptToStartAuto: torrent];
469       
470        [fTorrents addObject: torrent];
471        [torrent release];
472    }
473
474    [self updateUI: nil];
475    [self applyFilter: nil];
476   
477    [self updateTorrentHistory];
478}
479
480//called by the main open method to show sheet for choosing download location
481- (void) openFilesAsk: (NSMutableArray *) files
482{
483    NSString * torrentPath;
484    Torrent * torrent;
485   
486    //determine next file that can be opened
487    do
488    {
489        if ([files count] == 0) //recursive base case
490        {
491            [files release];
492           
493            [self updateTorrentHistory];
494            return;
495        }
496   
497        torrentPath = [files objectAtIndex: 0];
498        torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib];
499       
500        [files removeObjectAtIndex: 0];
501    } while (!torrent);
502
503    //add it to the "File > Open Recent" menu
504    [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
505
506    NSOpenPanel * panel = [NSOpenPanel openPanel];
507
508    [panel setPrompt: @"Select"];
509    [panel setAllowsMultipleSelection: NO];
510    [panel setCanChooseFiles: NO];
511    [panel setCanChooseDirectories: YES];
512
513    [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
514                        "Open torrent -> select destination folder"), [torrent name]]];
515   
516    NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: torrent, @"Torrent", files, @"Files", nil];
517
518    [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
519            didEndSelector: @selector(folderChoiceClosed:returnCode:contextInfo:) contextInfo: dictionary];
520}
521
522- (void) folderChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code
523    contextInfo: (NSDictionary *) dictionary
524{
525    Torrent * torrent = [dictionary objectForKey: @"Torrent"];
526
527    if (code == NSOKButton)
528    {
529        [torrent setDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
530        [torrent update];
531        [self attemptToStartAuto: torrent];
532       
533        [fTorrents addObject: torrent];
534       
535        [self updateUI: nil];
536        [self applyFilter: nil];
537    }
538   
539    [self performSelectorOnMainThread: @selector(openFilesAsk:) withObject: [dictionary objectForKey: @"Files"]
540                        waitUntilDone: NO];
541   
542    [torrent release];
543    [dictionary release];
544}
545
546//called on by applescript
547- (void) open: (NSArray *) files
548{
549    [self performSelectorOnMainThread: @selector(openFiles:) withObject: files waitUntilDone: NO];
550}
551
552- (void) openFiles: (NSArray *) filenames
553{
554    [self openFiles: filenames ignoreDownloadFolder: NO];
555}
556
557- (void) openShowSheet: (id) sender
558{
559    NSOpenPanel * panel = [NSOpenPanel openPanel];
560
561    [panel setAllowsMultipleSelection: YES];
562    [panel setCanChooseFiles: YES];
563    [panel setCanChooseDirectories: NO];
564
565    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
566        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
567        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
568}
569
570- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSNumber *) ignore
571{
572    if (code == NSOKButton)
573    {
574        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
575                                        [panel filenames], @"Files", ignore, @"Ignore", nil];
576        [self performSelectorOnMainThread: @selector(openFromSheet:) withObject: dictionary waitUntilDone: NO];
577    }
578}
579
580- (void) openFromSheet: (NSDictionary *) dictionary
581{
582    [self openFiles: [dictionary objectForKey: @"Files"]
583        ignoreDownloadFolder: [[dictionary objectForKey: @"Ignore"] boolValue]];
584   
585    [dictionary release];
586}
587
588- (void) resumeSelectedTorrents: (id) sender
589{
590    [self resumeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
591}
592
593- (void) resumeAllTorrents: (id) sender
594{
595    [self resumeTorrents: fTorrents];
596}
597
598- (void) resumeTorrents: (NSArray *) torrents
599{
600    NSEnumerator * enumerator = [torrents objectEnumerator];
601    Torrent * torrent;
602    while ((torrent = [enumerator nextObject]))
603        [torrent setWaitToStart: YES];
604   
605    [self attemptToStartMultipleAuto: torrents];
606   
607    [self updateUI: nil];
608    [self applyFilter: nil];
609    [self updateTorrentHistory];
610}
611
612- (void) resumeSelectedTorrentsNoWait:  (id) sender
613{
614    [self resumeTorrentsNoWait: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
615}
616
617- (void) resumeWaitingTorrents: (id) sender
618{
619    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
620   
621    NSEnumerator * enumerator = [fTorrents objectEnumerator];
622    Torrent * torrent;
623    while ((torrent = [enumerator nextObject]))
624        if ([torrent waitingToStart])
625            [torrents addObject: torrent];
626   
627    [self resumeTorrentsNoWait: torrents];
628}
629
630- (void) resumeTorrentsNoWait: (NSArray *) torrents
631{
632    //iterate through instead of all at once to ensure no conflicts
633    NSEnumerator * enumerator = [torrents objectEnumerator];
634    Torrent * torrent;
635    while ((torrent = [enumerator nextObject]))
636        [torrent startTransfer];
637   
638    [self updateUI: nil];
639    [self applyFilter: nil];
640    [self updateTorrentHistory];
641}
642
643- (void) stopSelectedTorrents: (id) sender
644{
645    [self stopTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
646}
647
648- (void) stopAllTorrents: (id) sender
649{
650    [self stopTorrents: fTorrents];
651}
652
653- (void) stopTorrents: (NSArray *) torrents
654{
655    //don't want any of these starting then stopping
656    NSEnumerator * enumerator = [torrents objectEnumerator];
657    Torrent * torrent;
658    while ((torrent = [enumerator nextObject]))
659        [torrent setWaitToStart: NO];
660
661    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
662   
663    [self updateUI: nil];
664    [self applyFilter: nil];
665    [self updateTorrentHistory];
666}
667
668- (void) removeTorrents: (NSArray *) torrents
669        deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
670{
671    [torrents retain];
672    int active = 0, downloading = 0;
673
674    if ([fDefaults boolForKey: @"CheckRemove"])
675    {
676        Torrent * torrent;
677        NSEnumerator * enumerator = [torrents objectEnumerator];
678        while ((torrent = [enumerator nextObject]))
679            if ([torrent isActive])
680            {
681                active++;
682                if (![torrent isSeeding])
683                    downloading++;
684            }
685
686        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
687        {
688            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
689                torrents, @"Torrents",
690                [NSNumber numberWithBool: deleteData], @"DeleteData",
691                [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
692
693            NSString * title, * message;
694           
695            int selected = [fTableView numberOfSelectedRows];
696            if (selected == 1)
697            {
698                title = [NSString stringWithFormat: NSLocalizedString(@"Confirm Removal of \"%@\"",
699                            "Removal confirm panel -> title"),
700                            [[fDisplayedTorrents objectAtIndex: [fTableView selectedRow]] name]];
701                message = NSLocalizedString(@"This transfer is active."
702                            " Once removed, continuing the transfer will require the torrent file."
703                            " Do you really want to remove it?", "Removal confirm panel -> message");
704            }
705            else
706            {
707                title = [NSString stringWithFormat: NSLocalizedString(@"Confirm Removal of %d Transfers",
708                            "Removal confirm panel -> title"), selected];
709                if (selected == active)
710                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
711                                "Removal confirm panel -> message part 1"), active];
712                else
713                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
714                                "Removal confirm panel -> message part 1"), selected, active];
715                message = [message stringByAppendingString:
716                    NSLocalizedString(@" Once removed, continuing the transfers will require the torrent files."
717                    " Do you really want to remove them?", "Removal confirm panel -> message part 2")];
718            }
719
720            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
721                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
722                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
723            return;
724        }
725    }
726   
727    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
728}
729
730- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (NSDictionary *) dict
731{
732    NSArray * torrents = [dict objectForKey: @"Torrents"];
733    BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue],
734        deleteTorrent = [[dict objectForKey: @"DeleteTorrent"] boolValue];
735    [dict release];
736   
737    if (returnCode == NSAlertDefaultReturn)
738        [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
739    else
740        [torrents release];
741}
742
743- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
744{
745    //don't want any of these starting then stopping
746    NSEnumerator * enumerator = [torrents objectEnumerator];
747    Torrent * torrent;
748    while ((torrent = [enumerator nextObject]))
749        [torrent setWaitToStart: NO];
750
751    NSNumber * lowestOrderValue = [NSNumber numberWithInt: [torrents count]], * currentOrderValue;
752
753    enumerator = [torrents objectEnumerator];
754    while ((torrent = [enumerator nextObject]))
755    {
756        [torrent stopTransfer];
757
758        if (deleteData)
759            [torrent trashData];
760        if (deleteTorrent)
761            [torrent trashTorrent];
762       
763        //determine lowest order value
764        currentOrderValue = [torrent orderValue];
765        if ([lowestOrderValue compare: currentOrderValue] == NSOrderedDescending)
766            lowestOrderValue = currentOrderValue;
767
768        [torrent removeForever];
769       
770        [fTorrents removeObject: torrent];
771        [fDisplayedTorrents removeObject: torrent];
772    }
773    [torrents release];
774
775    //reset the order values if necessary
776    if ([lowestOrderValue intValue] < [fTorrents count])
777    {
778        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
779                                                @"orderValue" ascending: YES] autorelease];
780        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
781
782        NSArray * tempTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
783        [descriptors release];
784
785        int i;
786        for (i = [lowestOrderValue intValue]; i < [tempTorrents count]; i++)
787            [[tempTorrents objectAtIndex: i] setOrderValue: i];
788    }
789   
790    [fTableView deselectAll: nil];
791   
792    [self updateUI: nil];
793    [self applyFilter: nil];
794   
795    [self updateTorrentHistory];
796}
797
798- (void) removeNoDelete: (id) sender
799{
800    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
801                deleteData: NO deleteTorrent: NO];
802}
803
804- (void) removeDeleteData: (id) sender
805{
806    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
807                deleteData: YES deleteTorrent: NO];
808}
809
810- (void) removeDeleteTorrent: (id) sender
811{
812    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
813                deleteData: NO deleteTorrent: YES];
814}
815
816- (void) removeDeleteDataAndTorrent: (id) sender
817{
818    [self removeTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]
819                deleteData: YES deleteTorrent: YES];
820}
821
822- (void) copyTorrentFile: (id) sender
823{
824    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
825            [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]]];
826}
827
828- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
829{
830    if ([torrents count] == 0)
831    {
832        [torrents release];
833        return;
834    }
835
836    Torrent * torrent = [torrents objectAtIndex: 0];
837
838    //warn user if torrent file can't be found
839    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
840    {
841        NSAlert * alert = [[NSAlert alloc] init];
842        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
843        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
844                                "Torrent file copy alert -> title"), [torrent name]]];
845        [alert setInformativeText: [NSString stringWithFormat:
846                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
847                                    [torrent torrentLocation]]];
848        [alert setAlertStyle: NSWarningAlertStyle];
849       
850        [alert runModal];
851       
852        [torrents removeObjectAtIndex: 0];
853        [self copyTorrentFileForTorrents: torrents];
854    }
855    else
856    {
857        NSSavePanel * panel = [NSSavePanel savePanel];
858        [panel setRequiredFileType: @"torrent"];
859        [panel setCanSelectHiddenExtension: YES];
860       
861        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
862            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
863    }
864}
865
866- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (NSMutableArray *) torrents
867{
868    //if save successful, copy torrent to new location with name of data file
869    if (code == NSOKButton)
870        [[NSFileManager defaultManager] copyPath: [[torrents objectAtIndex: 0] torrentLocation]
871            toPath: [panel filename] handler: nil];
872   
873    [torrents removeObjectAtIndex: 0];
874    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
875}
876
877- (void) revealFile: (id) sender
878{
879    NSIndexSet * indexSet = [fTableView selectedRowIndexes];
880    unsigned int i;
881    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
882        [[fDisplayedTorrents objectAtIndex: i] revealData];
883}
884
885- (void) showPreferenceWindow: (id) sender
886{
887    NSWindow * window = [fPrefsController window];
888    if (![window isVisible])
889        [window center];
890
891    [window makeKeyAndOrderFront: nil];
892}
893
894- (void) showInfo: (id) sender
895{
896    if ([[fInfoController window] isVisible])
897        [fInfoController close];
898    else
899    {
900        [fInfoController updateInfoStats];
901        [[fInfoController window] orderFront: nil];
902    }
903}
904
905- (void) setInfoTab: (id) sender
906{
907    if (sender == fNextInfoTabItem)
908        [fInfoController setNextTab];
909    else
910        [fInfoController setPreviousTab];
911}
912
913- (void) showMessageWindow: (id) sender
914{
915    [fMessageController showWindow: nil];
916}
917
918- (void) updateUI: (NSTimer *) timer
919{
920    [fTorrents makeObjectsPerformSelector: @selector(update)];
921
922    //resort if necessary or just update the table
923    if ([fSortType isEqualToString: @"Progress"] || [fSortType isEqualToString: @"State"])
924        [self sortTorrents];
925    else
926        [fTableView reloadData];
927   
928    //update the global DL/UL rates
929    float downloadRate, uploadRate;
930    tr_torrentRates(fLib, & downloadRate, & uploadRate);
931    if (![fStatusBar isHidden])
932    {
933        [fTotalDLField setStringValue: [NSLocalizedString(@"Total DL: ", "Status bar -> total download")
934                                        stringByAppendingString: [NSString stringForSpeed: downloadRate]]];
935        [fTotalULField setStringValue: [NSLocalizedString(@"Total UL: ", "Status bar -> total upload")
936                                        stringByAppendingString: [NSString stringForSpeed: uploadRate]]];
937    }
938
939    //update non-constant parts of info window
940    if ([[fInfoController window] isVisible])
941        [fInfoController updateInfoStats];
942
943    //badge dock
944    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
945}
946
947- (void) torrentFinishedDownloading: (NSNotification *) notification
948{
949    Torrent * torrent = [notification object];
950   
951    [fInfoController updateInfoSettings];
952   
953    [self applyFilter: nil];
954    [self checkToStartWaiting: torrent];
955   
956    if ([fDefaults boolForKey: @"PlayDownloadSound"])
957    {
958        NSSound * sound;
959        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
960            [sound play];
961    }
962   
963    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
964        description: [torrent name]
965        notificationName: GROWL_DOWNLOAD_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
966   
967    if (![fWindow isKeyWindow])
968        fCompleted++;
969}
970
971- (void) updateTorrentHistory
972{
973    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
974
975    NSEnumerator * enumerator = [fTorrents objectEnumerator];
976    Torrent * torrent;
977    while ((torrent = [enumerator nextObject]))
978        [history addObject: [torrent history]];
979
980    [fDefaults setObject: history forKey: @"History"];
981    [fDefaults synchronize];
982}
983
984- (void) sortTorrents
985{
986    //remember selected rows if needed
987    NSArray * selectedTorrents = nil;
988    int numSelected = [fTableView numberOfSelectedRows];
989    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
990        selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
991
992    [self sortTorrentsIgnoreSelected]; //actually sort
993   
994    //set selected rows if needed
995    if (selectedTorrents)
996    {
997        Torrent * torrent;
998        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
999        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1000        while ((torrent = [enumerator nextObject]))
1001            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1002       
1003        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1004        [indexSet release];
1005    }
1006}
1007
1008//doesn't remember selected rows
1009- (void) sortTorrentsIgnoreSelected
1010{
1011    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1012                            ascending: YES selector: @selector(caseInsensitiveCompare:)] autorelease],
1013                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1014                                            ascending: YES] autorelease];
1015
1016    NSArray * descriptors;
1017    if ([fSortType isEqualToString: @"Name"])
1018        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1019    else if ([fSortType isEqualToString: @"State"])
1020    {
1021        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1022                                                @"stateSortKey" ascending: NO] autorelease],
1023                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1024                                            @"progressSortKey" ascending: NO] autorelease];
1025       
1026        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
1027                                                            nameDescriptor, orderDescriptor, nil];
1028    }
1029    else if ([fSortType isEqualToString: @"Progress"])
1030    {
1031        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1032                                            @"progressSortKey" ascending: YES] autorelease];
1033       
1034        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
1035    }
1036    else if ([fSortType isEqualToString: @"Date"])
1037    {
1038        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"date" ascending: YES] autorelease];
1039   
1040        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1041    }
1042    else
1043        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1044
1045    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1046    [descriptors release];
1047   
1048    [fTableView reloadData];
1049}
1050
1051- (void) setSort: (id) sender
1052{
1053    //get checked items
1054    NSMenuItem * prevSortItem, * prevSortActionItem;
1055    if ([fSortType isEqualToString: @"Name"])
1056    {
1057        prevSortItem = fNameSortItem;
1058        prevSortActionItem = fNameSortActionItem;
1059    }
1060    else if ([fSortType isEqualToString: @"State"])
1061    {
1062        prevSortItem = fStateSortItem;
1063        prevSortActionItem = fStateSortActionItem;
1064    }
1065    else if ([fSortType isEqualToString: @"Progress"])
1066    {
1067        prevSortItem = fProgressSortItem;
1068        prevSortActionItem = fProgressSortActionItem;
1069    }
1070    else if ([fSortType isEqualToString: @"Date"])
1071    {
1072        prevSortItem = fDateSortItem;
1073        prevSortActionItem = fDateSortActionItem;
1074    }
1075    else
1076    {
1077        prevSortItem = fOrderSortItem;
1078        prevSortActionItem = fOrderSortActionItem;
1079    }
1080   
1081    if (sender != prevSortItem && sender != prevSortActionItem)
1082    {
1083        [fSortType release];
1084       
1085        //get new items to check
1086        NSMenuItem * currentSortItem, * currentSortActionItem;
1087        if (sender == fNameSortItem || sender == fNameSortActionItem)
1088        {
1089            currentSortItem = fNameSortItem;
1090            currentSortActionItem = fNameSortActionItem;
1091            fSortType = [[NSString alloc] initWithString: @"Name"];
1092        }
1093        else if (sender == fStateSortItem || sender == fStateSortActionItem)
1094        {
1095            currentSortItem = fStateSortItem;
1096            currentSortActionItem = fStateSortActionItem;
1097            fSortType = [[NSString alloc] initWithString: @"State"];
1098        }
1099        else if (sender == fProgressSortItem || sender == fProgressSortActionItem)
1100        {
1101            currentSortItem = fProgressSortItem;
1102            currentSortActionItem = fProgressSortActionItem;
1103            fSortType = [[NSString alloc] initWithString: @"Progress"];
1104        }
1105        else if (sender == fDateSortItem || sender == fDateSortActionItem)
1106        {
1107            currentSortItem = fDateSortItem;
1108            currentSortActionItem = fDateSortActionItem;
1109            fSortType = [[NSString alloc] initWithString: @"Date"];
1110        }
1111        else
1112        {
1113            currentSortItem = fOrderSortItem;
1114            currentSortActionItem = fOrderSortActionItem;
1115            fSortType = [[NSString alloc] initWithString: @"Order"];
1116        }
1117   
1118        [prevSortItem setState: NSOffState];
1119        [prevSortActionItem setState: NSOffState];
1120        [currentSortItem setState: NSOnState];
1121        [currentSortActionItem setState: NSOnState];
1122       
1123        [fDefaults setObject: fSortType forKey: @"Sort"];
1124    }
1125
1126    [self sortTorrents];
1127}
1128
1129- (void) applyFilter: (id) sender
1130{
1131    //remember selected rows if needed
1132    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1133                ? [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1134
1135    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1136
1137    BOOL filtering = YES;
1138    if ([fFilterType isEqualToString: @"Pause"])
1139    {
1140        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1141        Torrent * torrent;
1142        while ((torrent = [enumerator nextObject]))
1143            if (![torrent isActive])
1144                [tempTorrents addObject: torrent];
1145    }
1146    else if ([fFilterType isEqualToString: @"Seed"])
1147    {
1148        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1149        Torrent * torrent;
1150        while ((torrent = [enumerator nextObject]))
1151            if ([torrent isActive] && [torrent progress] >= 1.0)
1152                [tempTorrents addObject: torrent];
1153    }
1154    else if ([fFilterType isEqualToString: @"Download"])
1155    {
1156        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1157        Torrent * torrent;
1158        while ((torrent = [enumerator nextObject]))
1159            if ([torrent isActive] && [torrent progress] < 1.0)
1160                [tempTorrents addObject: torrent];
1161    }
1162    else
1163    {
1164        filtering = NO;
1165        [tempTorrents setArray: fTorrents];
1166    }
1167   
1168    NSString * searchString = [fSearchFilterField stringValue];
1169    if ([searchString length] > 0)
1170    {
1171        filtering = YES;
1172       
1173        int i;
1174        for (i = [tempTorrents count] - 1; i >= 0; i--)
1175            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1176                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1177                [tempTorrents removeObjectAtIndex: i];
1178    }
1179   
1180    [fDisplayedTorrents setArray: tempTorrents];
1181    [tempTorrents release];
1182   
1183    [self sortTorrentsIgnoreSelected];
1184   
1185    //set selected rows if needed
1186    if (selectedTorrents)
1187    {
1188        Torrent * torrent;
1189        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1190        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1191        unsigned index;
1192        while ((torrent = [enumerator nextObject]))
1193            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1194                [indexSet addIndex: index];
1195       
1196        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1197        [indexSet release];
1198    }
1199   
1200    //set status bar torrent count text
1201    NSMutableString * totalTorrentsString = [NSMutableString stringWithString: @""];
1202    if (filtering)
1203        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1204   
1205    int totalCount = [fTorrents count];
1206    if (totalCount > 1)
1207        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfers", "Status bar transfer count"), totalCount];
1208    else
1209        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfer", "Status bar transfer count"), totalCount];
1210   
1211    [fTotalTorrentsField setStringValue: totalTorrentsString];
1212
1213    [self setWindowSizeToFit];
1214}
1215
1216//resets filter and sorts torrents
1217- (void) setFilter: (id) sender
1218{
1219    BarButton * prevFilterButton;
1220    if ([fFilterType isEqualToString: @"Pause"])
1221        prevFilterButton = fPauseFilterButton;
1222    else if ([fFilterType isEqualToString: @"Seed"])
1223        prevFilterButton = fSeedFilterButton;
1224    else if ([fFilterType isEqualToString: @"Download"])
1225        prevFilterButton = fDownloadFilterButton;
1226    else
1227        prevFilterButton = fNoFilterButton;
1228   
1229    if (sender != prevFilterButton)
1230    {
1231        [prevFilterButton setEnabled: NO];
1232        [sender setEnabled: YES];
1233
1234        [fFilterType release];
1235        if (sender == fDownloadFilterButton)
1236            fFilterType = [[NSString alloc] initWithString: @"Download"];
1237        else if (sender == fPauseFilterButton)
1238            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1239        else if (sender == fSeedFilterButton)
1240            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1241        else
1242            fFilterType = [[NSString alloc] initWithString: @"None"];
1243
1244        [fDefaults setObject: fFilterType forKey: @"Filter"];
1245    }
1246
1247    [self applyFilter: nil];
1248}
1249
1250- (void) switchFilter: (id) sender
1251{
1252    NSButton * button;
1253    if ([fFilterType isEqualToString: @"None"])
1254        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1255    else if ([fFilterType isEqualToString: @"Download"])
1256        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1257    else if ([fFilterType isEqualToString: @"Seed"])
1258        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1259    else if ([fFilterType isEqualToString: @"Pause"])
1260        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1261    else
1262        button = fNoFilterButton;
1263   
1264    [self setFilter: button];
1265}
1266
1267- (void) updateControlTint: (NSNotification *) notification
1268{
1269    if ([fDefaults boolForKey: @"SpeedLimit"])
1270        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
1271            ? [NSImage imageNamed: @"SpeedLimitButtonBlue.png"] : [NSImage imageNamed: @"SpeedLimitButtonGraphite.png"]];
1272}
1273
1274- (void) applySpeedLimit: (id) sender
1275{
1276    [fPrefsController applySpeedSettings: nil];
1277}
1278
1279- (void) toggleSpeedLimit: (id) sender
1280{
1281    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
1282    [self applySpeedLimit: nil];
1283}
1284
1285- (void) autoSpeedLimitChange: (NSNotification *) notification
1286{
1287    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1288        return;
1289 
1290    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1291                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
1292        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1293                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
1294        * nowDate = [NSCalendarDate calendarDate];
1295   
1296    //check if should be on if within range
1297    BOOL shouldBeOn;
1298   
1299    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
1300        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
1301        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
1302   
1303    if (onTime == offTime)
1304        shouldBeOn = NO;
1305    else if (onTime < offTime)
1306        shouldBeOn = onTime <= nowTime && nowTime < offTime;
1307    else
1308        shouldBeOn = onTime <= nowTime || nowTime < offTime;
1309   
1310    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
1311        [self toggleSpeedLimit: nil];
1312}
1313
1314- (void) autoSpeedLimit: (NSTimer *) timer
1315{
1316    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1317        return;
1318   
1319    //only toggle if within first few seconds of minutes
1320    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
1321    if ([nowDate secondOfMinute] < AUTO_SPEED_LIMIT_SECONDS)
1322        return;
1323   
1324    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1325                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
1326   
1327    BOOL toggle;
1328    if ([fDefaults boolForKey: @"SpeedLimit"])
1329        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
1330    else
1331    {
1332        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1333                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
1334        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
1335                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
1336    }
1337   
1338    if (toggle)
1339    {
1340        [self toggleSpeedLimit: nil];
1341       
1342        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
1343                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
1344                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
1345            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
1346            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1347    }
1348}
1349
1350- (void) setLimitGlobalEnabled: (id) sender
1351{
1352    [fPrefsController applySpeedSettings: nil];
1353}
1354
1355- (void) setQuickLimitGlobal: (id) sender
1356{
1357    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
1358    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
1359   
1360    [fPrefsController applySpeedSettings: nil];
1361}
1362
1363- (void) setQuickRatioGlobal: (id) sender
1364{
1365    [fDefaults setBool: YES forKey: @"RatioCheck"];
1366    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
1367}
1368
1369- (void) checkWaitingForStopped: (NSNotification *) notification
1370{
1371    [self checkToStartWaiting: [notification object]];
1372   
1373    [self updateUI: nil];
1374    [self applyFilter: nil];
1375    [self updateTorrentHistory];
1376}
1377
1378- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1379{
1380    //don't try to start a transfer if there should be none waiting
1381    if (![fDefaults boolForKey: @"Queue"])
1382        return;
1383
1384    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1385   
1386    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1387    Torrent * torrent, * torrentToStart = nil;
1388    while ((torrent = [enumerator nextObject]))
1389    {
1390        //ignore the torrent just stopped
1391        if (torrent == finishedTorrent)
1392            continue;
1393   
1394        if ([torrent isActive])
1395        {
1396            if (![torrent isSeeding] && ![torrent isError])
1397            {
1398                desiredActive--;
1399                if (desiredActive <= 0)
1400                    return;
1401            }
1402        }
1403        else
1404        {
1405            //use as next if it is waiting to start and either no previous or order value is lower
1406            if ([torrent waitingToStart] && (!torrentToStart
1407                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1408                torrentToStart = torrent;
1409        }
1410    }
1411   
1412    //since it hasn't returned, the queue amount has not been met
1413    if (torrentToStart)
1414    {
1415        [torrentToStart startTransfer];
1416       
1417        [self updateUI: nil];
1418        [self applyFilter: nil];
1419        [self updateTorrentHistory];
1420    }
1421}
1422
1423- (void) torrentStartSettingChange: (NSNotification *) notification
1424{
1425    [self attemptToStartMultipleAuto: [notification object]];
1426
1427    [self updateUI: nil];
1428    [self applyFilter: nil];
1429    [self updateTorrentHistory];
1430}
1431
1432- (void) globalStartSettingChange: (NSNotification *) notification
1433{
1434    [self attemptToStartMultipleAuto: fTorrents];
1435   
1436    [self updateUI: nil];
1437    [self applyFilter: nil];
1438    [self updateTorrentHistory];
1439}
1440
1441- (void) torrentStoppedForRatio: (NSNotification *) notification
1442{
1443    [self applyFilter: nil];
1444    [fInfoController updateInfoStats];
1445    [fInfoController updateInfoSettings];
1446   
1447    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1448    {
1449        NSSound * sound;
1450        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1451            [sound play];
1452    }
1453   
1454    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1455        description: [[notification object] name]
1456        notificationName: GROWL_SEEDING_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1457}
1458
1459- (void) attemptToStartAuto: (Torrent *) torrent
1460{
1461    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1462}
1463
1464//will try to start, taking into consideration the start preference
1465- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1466{
1467    if (![fDefaults boolForKey: @"Queue"])
1468    {
1469        NSEnumerator * enumerator = [torrents objectEnumerator];
1470        Torrent * torrent;
1471        while ((torrent = [enumerator nextObject]))
1472            if ([torrent waitingToStart])
1473                [torrent startTransfer];
1474       
1475        return;
1476    }
1477   
1478    //determine the number of downloads needed to start
1479    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1480           
1481    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1482    Torrent * torrent;
1483    while ((torrent = [enumerator nextObject]))
1484        if ([torrent isActive] && ![torrent isSeeding] && ![torrent isError])
1485        {
1486            desiredActive--;
1487            if (desiredActive <= 0)
1488                break;
1489        }
1490   
1491    //sort torrents by order value
1492    NSArray * sortedTorrents;
1493    if ([torrents count] > 1 && desiredActive > 0)
1494    {
1495        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1496                                                    @"orderValue" ascending: YES] autorelease];
1497        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1498       
1499        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1500        [descriptors release];
1501    }
1502    else
1503        sortedTorrents = torrents;
1504
1505    enumerator = [sortedTorrents objectEnumerator];
1506    while ((torrent = [enumerator nextObject]))
1507    {
1508        if ([torrent waitingToStart])
1509        {
1510            if ([torrent progress] >= 1.0)
1511                [torrent startTransfer];
1512            else if (desiredActive > 0)
1513            {
1514                [torrent startTransfer];
1515                desiredActive--;
1516            }
1517            else
1518                continue;
1519           
1520            [torrent update];
1521        }
1522    }
1523}
1524
1525-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
1526{
1527    if ([notification isEqualToString: UKFileWatcherWriteNotification])
1528        [self checkAutoImportDirectory];
1529}
1530
1531- (void) changeAutoImport
1532{
1533    [fAutoImportedNames removeAllObjects];
1534    [self checkAutoImportDirectory];
1535}
1536
1537- (void) checkAutoImportDirectory
1538{
1539    if (![fDefaults boolForKey: @"AutoImport"])
1540        return;
1541       
1542    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1543   
1544    NSArray * importedNames;
1545    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
1546        return;
1547   
1548    //only import those that have not been imported yet
1549    NSMutableArray * newNames = [importedNames mutableCopy];
1550    [newNames removeObjectsInArray: fAutoImportedNames];
1551    [fAutoImportedNames setArray: importedNames];
1552   
1553    NSString * file;
1554    int i;
1555    for (i = [newNames count] - 1; i >= 0; i--)
1556    {
1557        file = [newNames objectAtIndex: i];
1558        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
1559            [newNames removeObjectAtIndex: i];
1560        else
1561            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
1562    }
1563   
1564    NSEnumerator * enumerator;
1565    if (![[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"])
1566    {
1567        enumerator = [newNames objectEnumerator];
1568        int count;
1569        while ((file = [enumerator nextObject]))
1570        {
1571            count = [fTorrents count];
1572            [self openFiles: [NSArray arrayWithObject: file]];
1573           
1574            //check if torrent was opened
1575            if ([fTorrents count] > count)
1576                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
1577                    "Growl notification title") description: [file lastPathComponent]
1578                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1579        }
1580    }
1581    else
1582        [self openFiles: newNames];
1583   
1584    //create temporary torrents to check if an import fails because of an error
1585    enumerator = [newNames objectEnumerator];
1586    int error;
1587    while ((file = [enumerator nextObject]))
1588    {
1589        tr_torrent_t * tempTor = tr_torrentInit(fLib, [file UTF8String], 0, & error);
1590       
1591        if (tempTor)
1592            tr_torrentClose(fLib, tempTor);
1593        else if (error != TR_EUNSUPPORTED && error != TR_EDUPLICATE)
1594            [fAutoImportedNames removeObjectIdenticalTo: [file lastPathComponent]]; //can try to import later
1595        else;
1596    }
1597   
1598    [newNames release];
1599}
1600
1601- (int) numberOfRowsInTableView: (NSTableView *) tableview
1602{
1603    return [fDisplayedTorrents count];
1604}
1605
1606- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
1607{
1608    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
1609}
1610
1611- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1612    toPasteboard: (NSPasteboard *) pasteboard
1613{
1614    //only allow reordering of rows if sorting by order with no filter
1615    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1616            && [[fSearchFilterField stringValue] length] == 0)
1617    {
1618        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1619        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1620                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1621        return YES;
1622    }
1623    return NO;
1624}
1625
1626- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1627    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1628{
1629    NSPasteboard * pasteboard = [info draggingPasteboard];
1630    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1631    {
1632        //check if any files to add have "torrent" as an extension
1633        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1634        NSString * file;
1635        while ((file = [enumerator nextObject]))
1636            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1637            {
1638                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1639                return NSDragOperationGeneric;
1640            }
1641    }
1642    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1643    {
1644        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1645        return NSDragOperationGeneric;
1646    }
1647    else
1648        return NSDragOperationNone;
1649}
1650
1651- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1652    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1653{
1654    NSPasteboard * pasteboard = [info draggingPasteboard];
1655    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1656    {
1657        //create an array of files with the "torrent" extension
1658        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1659        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1660        NSString * file;
1661        while ((file = [enumerator nextObject]))
1662            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1663                [filesToOpen addObject: file];
1664   
1665        [self application: NSApp openFiles: filesToOpen];
1666        [filesToOpen release];
1667    }
1668    else
1669    {
1670        //remember selected rows if needed
1671        NSArray * selectedTorrents = nil;
1672        int numSelected = [fTableView numberOfSelectedRows];
1673        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1674            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1675   
1676        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1677                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1678       
1679        //move torrent in array
1680        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
1681        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1682       
1683        //determine the insertion index now that transfers to move have been removed
1684        int i, decrease = 0;
1685        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1686            decrease++;
1687       
1688        //insert objects at new location
1689        for (i = 0; i < [movingTorrents count]; i++)
1690            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1691       
1692        [movingTorrents release];
1693       
1694        //redo order values
1695        int low = [indexes firstIndex], high = [indexes lastIndex];
1696        if (newRow < low)
1697            low = newRow;
1698        else if (newRow > high + 1)
1699            high = newRow - 1;
1700        else;
1701       
1702        for (i = low; i <= high; i++)
1703            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1704       
1705        [fTableView reloadData];
1706       
1707        //set selected rows if needed
1708        if (selectedTorrents)
1709        {
1710            Torrent * torrent;
1711            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1712            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1713            while ((torrent = [enumerator nextObject]))
1714                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1715           
1716            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1717            [indexSet release];
1718        }
1719    }
1720   
1721    return YES;
1722}
1723
1724- (void) tableViewSelectionDidChange: (NSNotification *) notification
1725{
1726    [fInfoController updateInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
1727}
1728
1729- (void) toggleSmallView: (id) sender
1730{
1731    BOOL makeSmall = [fDefaults boolForKey: @"SmallView"];
1732   
1733    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1734   
1735    //window min height
1736    NSSize contentMinSize = [fWindow contentMinSize],
1737            contentSize = [[fWindow contentView] frame].size;
1738    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1739                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1740    [fWindow setContentMinSize: contentMinSize];
1741   
1742    //resize for larger min height if not set to auto size
1743    if (![fDefaults boolForKey: @"AutoSize"])
1744    {
1745        if (!makeSmall && contentSize.height < contentMinSize.height)
1746        {
1747            NSRect frame = [fWindow frame];
1748            float heightChange = contentMinSize.height - contentSize.height;
1749            frame.size.height += heightChange;
1750            frame.origin.y -= heightChange;
1751           
1752            [fWindow setFrame: frame display: YES];
1753            [fTableView reloadData];
1754        }
1755    }
1756    else
1757        [self setWindowSizeToFit];
1758}
1759
1760- (void) toggleStatusBar: (id) sender
1761{
1762    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1763    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1764}
1765
1766- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1767{
1768    if (show != [fStatusBar isHidden])
1769        return;
1770
1771    if (show)
1772        [fStatusBar setHidden: NO];
1773
1774    NSRect frame = [fWindow frame];
1775    float heightChange = [fStatusBar frame].size.height;
1776    if (!show)
1777        heightChange *= -1;
1778   
1779    //allow bar to show even if not enough room
1780    if (show && ![fDefaults boolForKey: @"AutoSize"])
1781    {
1782        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1783        if (frame.size.height > maxHeight)
1784        {
1785            float change = maxHeight - frame.size.height;
1786            frame.size.height += change;
1787            frame.origin.y -= change;
1788           
1789            [fWindow setFrame: frame display: NO animate: NO];
1790        }
1791    }
1792
1793    frame.size.height += heightChange;
1794    frame.origin.y -= heightChange;
1795   
1796    [self updateUI: nil];
1797   
1798    //set views to not autoresize
1799    unsigned int statsMask = [fStatusBar autoresizingMask];
1800    unsigned int filterMask = [fFilterBar autoresizingMask];
1801    unsigned int scrollMask = [fScrollView autoresizingMask];
1802    [fStatusBar setAutoresizingMask: 0];
1803    [fFilterBar setAutoresizingMask: 0];
1804    [fScrollView setAutoresizingMask: 0];
1805   
1806    [fWindow setFrame: frame display: YES animate: animate];
1807   
1808    //re-enable autoresize
1809    [fStatusBar setAutoresizingMask: statsMask];
1810    [fFilterBar setAutoresizingMask: filterMask];
1811    [fScrollView setAutoresizingMask: scrollMask];
1812   
1813    //change min size
1814    NSSize minSize = [fWindow contentMinSize];
1815    minSize.height += heightChange;
1816    [fWindow setContentMinSize: minSize];
1817   
1818    if (!show)
1819        [fStatusBar setHidden: YES];
1820}
1821
1822- (void) toggleFilterBar: (id) sender
1823{
1824    //disable filtering when hiding
1825    if (![fFilterBar isHidden])
1826    {
1827        [fSearchFilterField setStringValue: @""];
1828        [self setFilter: fNoFilterButton];
1829    }
1830
1831    [self showFilterBar: [fFilterBar isHidden] animate: YES];
1832    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
1833}
1834
1835- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1836{
1837    if (show != [fFilterBar isHidden])
1838        return;
1839
1840    if (show)
1841        [fFilterBar setHidden: NO];
1842
1843    NSRect frame = [fWindow frame];
1844    float heightChange = [fFilterBar frame].size.height;
1845    if (!show)
1846        heightChange *= -1;
1847   
1848    //allow bar to show even if not enough room
1849    if (show && ![fDefaults boolForKey: @"AutoSize"])
1850    {
1851        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1852        if (frame.size.height > maxHeight)
1853        {
1854            float change = maxHeight - frame.size.height;
1855            frame.size.height += change;
1856            frame.origin.y -= change;
1857           
1858            [fWindow setFrame: frame display: NO animate: NO];
1859        }
1860    }
1861
1862    frame.size.height += heightChange;
1863    frame.origin.y -= heightChange;
1864   
1865    //set views to not autoresize
1866    unsigned int filterMask = [fFilterBar autoresizingMask];
1867    unsigned int scrollMask = [fScrollView autoresizingMask];
1868    [fFilterBar setAutoresizingMask: 0];
1869    [fScrollView setAutoresizingMask: 0];
1870   
1871    [fWindow setFrame: frame display: YES animate: animate];
1872   
1873    //re-enable autoresize
1874    [fFilterBar setAutoresizingMask: filterMask];
1875    [fScrollView setAutoresizingMask: scrollMask];
1876   
1877    //change min size
1878    NSSize minSize = [fWindow contentMinSize];
1879    minSize.height += heightChange;
1880    [fWindow setContentMinSize: minSize];
1881   
1882    if (!show)
1883    {
1884        [fFilterBar setHidden: YES];
1885        [fWindow makeFirstResponder: fTableView];
1886    }
1887}
1888
1889- (void) toggleAdvancedBar: (id) sender
1890{
1891    [fTableView display];
1892}
1893
1894- (void) doNothing: (id) sender {}
1895
1896- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1897    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1898{
1899    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1900
1901    if ([ident isEqualToString: TOOLBAR_OPEN])
1902    {
1903        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
1904        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
1905        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
1906        [item setImage: [NSImage imageNamed: @"Open.png"]];
1907        [item setTarget: self];
1908        [item setAction: @selector(openShowSheet:)];
1909        [item setAutovalidates: NO];
1910    }
1911    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1912    {
1913        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
1914        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
1915        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
1916        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1917        [item setTarget: self];
1918        [item setAction: @selector(removeNoDelete:)];
1919    }
1920    else if ([ident isEqualToString: TOOLBAR_INFO])
1921    {
1922        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
1923        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
1924        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
1925        [item setImage: [NSImage imageNamed: @"Info.png"]];
1926        [item setTarget: self];
1927        [item setAction: @selector(showInfo:)];
1928        [item setAutovalidates: NO];
1929    }
1930    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1931    {
1932        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
1933        [item setPaletteLabel: [item label]];
1934        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
1935        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1936        [item setTarget: self];
1937        [item setAction: @selector(stopAllTorrents:)];
1938    }
1939    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1940    {
1941        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
1942        [item setPaletteLabel: [item label]];
1943        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
1944        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1945        [item setTarget: self];
1946        [item setAction: @selector(resumeAllTorrents:)];
1947    }
1948    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1949    {
1950        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
1951        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
1952        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
1953        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1954        [item setTarget: self];
1955        [item setAction: @selector(stopSelectedTorrents:)];
1956    }
1957    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1958    {
1959        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
1960        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
1961        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
1962        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1963        [item setTarget: self];
1964        [item setAction: @selector(resumeSelectedTorrents:)];
1965    }
1966    else if ([ident isEqualToString: TOOLBAR_FILTER])
1967    {
1968        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
1969        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
1970        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
1971        [item setImage: [NSImage imageNamed: @"Filter.png"]];
1972        [item setTarget: self];
1973        [item setAction: @selector(toggleFilterBar:)];
1974        [item setAutovalidates: NO];
1975    }
1976    else
1977    {
1978        [item release];
1979        return nil;
1980    }
1981
1982    return item;
1983}
1984
1985- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1986{
1987    return [NSArray arrayWithObjects:
1988            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1989            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1990            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
1991            NSToolbarSeparatorItemIdentifier,
1992            NSToolbarSpaceItemIdentifier,
1993            NSToolbarFlexibleSpaceItemIdentifier,
1994            NSToolbarCustomizeToolbarItemIdentifier, nil];
1995}
1996
1997- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1998{
1999    return [NSArray arrayWithObjects:
2000            TOOLBAR_OPEN, TOOLBAR_REMOVE,
2001            NSToolbarSeparatorItemIdentifier,
2002            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2003            NSToolbarFlexibleSpaceItemIdentifier,
2004            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2005}
2006
2007- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2008{
2009    NSString * ident = [toolbarItem itemIdentifier];
2010
2011    //enable remove item
2012    if ([ident isEqualToString: TOOLBAR_REMOVE])
2013        return [fTableView numberOfSelectedRows] > 0;
2014
2015    //enable pause all item
2016    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2017    {
2018        Torrent * torrent;
2019        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2020        while ((torrent = [enumerator nextObject]))
2021            if ([torrent isActive] || [torrent waitingToStart])
2022                return YES;
2023        return NO;
2024    }
2025
2026    //enable resume all item
2027    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2028    {
2029        Torrent * torrent;
2030        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2031        while ((torrent = [enumerator nextObject]))
2032            if ([torrent isPaused] && ![torrent waitingToStart])
2033                return YES;
2034        return NO;
2035    }
2036
2037    //enable pause item
2038    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2039    {
2040        Torrent * torrent;
2041        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2042        unsigned int i;
2043       
2044        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2045        {
2046            torrent = [fDisplayedTorrents objectAtIndex: i];
2047            if ([torrent isActive] || [torrent waitingToStart])
2048                return YES;
2049        }
2050        return NO;
2051    }
2052   
2053    //enable resume item
2054    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2055    {
2056        Torrent * torrent;
2057        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2058        unsigned int i;
2059       
2060        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2061        {
2062            torrent = [fDisplayedTorrents objectAtIndex: i];
2063            if ([torrent isPaused] && ![torrent waitingToStart])
2064                return YES;
2065        }
2066        return NO;
2067    }
2068
2069    return YES;
2070}
2071
2072- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2073{
2074    SEL action = [menuItem action];
2075
2076    //only enable some items if it is in a context menu or the window is useable
2077    BOOL canUseTable = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
2078
2079    //enable open items
2080    if (action == @selector(openShowSheet:))
2081        return [fWindow attachedSheet] == nil;
2082   
2083    //enable sort and advanced bar items
2084    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2085        return [fWindow isVisible];
2086
2087    //enable show info
2088    if (action == @selector(showInfo:))
2089    {
2090        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector",
2091                            "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2092        if (![[menuItem title] isEqualToString: title])
2093                [menuItem setTitle: title];
2094
2095        return YES;
2096    }
2097   
2098    //enable prev/next inspector tab
2099    if (action == @selector(setInfoTab:))
2100        return [[fInfoController window] isVisible];
2101   
2102    //enable toggle status bar
2103    if (action == @selector(toggleStatusBar:))
2104    {
2105        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2106                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2107        if (![[menuItem title] isEqualToString: title])
2108            [menuItem setTitle: title];
2109
2110        return [fWindow isVisible];
2111    }
2112   
2113    //enable toggle filter bar
2114    if (action == @selector(toggleFilterBar:))
2115    {
2116        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2117                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2118        if (![[menuItem title] isEqualToString: title])
2119            [menuItem setTitle: title];
2120
2121        return [fWindow isVisible];
2122    }
2123   
2124    //enable prev/next filter button
2125    if (action == @selector(switchFilter:))
2126        return [fWindow isVisible] && ![fFilterBar isHidden];
2127
2128    //enable reveal in finder
2129    if (action == @selector(revealFile:))
2130        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2131
2132    //enable remove items
2133    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2134        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2135    {
2136        BOOL warning = NO,
2137            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2138            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2139        Torrent * torrent;
2140        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2141        unsigned int i;
2142       
2143        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2144        {
2145            torrent = [fDisplayedTorrents objectAtIndex: i];
2146            if (!warning && [torrent isActive])
2147            {
2148                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2149                if (warning && canDelete)
2150                    break;
2151            }
2152            if (!canDelete && [torrent publicTorrent])
2153            {
2154                canDelete = YES;
2155                if (warning)
2156                    break;
2157            }
2158        }
2159   
2160        //append or remove ellipsis when needed
2161        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2162        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2163        {
2164            if (![title hasSuffix: ellipsis])
2165                [menuItem setTitle: [title stringByAppendingEllipsis]];
2166        }
2167        else
2168        {
2169            if ([title hasSuffix: ellipsis])
2170                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2171        }
2172       
2173        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2174    }
2175
2176    //enable pause all item
2177    if (action == @selector(stopAllTorrents:))
2178    {
2179        Torrent * torrent;
2180        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2181        while ((torrent = [enumerator nextObject]))
2182            if ([torrent isActive] || [torrent waitingToStart])
2183                return YES;
2184        return NO;
2185    }
2186   
2187    //enable resume all item
2188    if (action == @selector(resumeAllTorrents:))
2189    {
2190        Torrent * torrent;
2191        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2192        while ((torrent = [enumerator nextObject]))
2193            if ([torrent isPaused] && ![torrent waitingToStart])
2194                return YES;
2195        return NO;
2196    }
2197   
2198    //enable resume all waiting item
2199    if (action == @selector(resumeWaitingTorrents:))
2200    {
2201        if (![fDefaults boolForKey: @"Queue"])
2202            return NO;
2203   
2204        Torrent * torrent;
2205        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2206        while ((torrent = [enumerator nextObject]))
2207            if ([torrent waitingToStart])
2208                return YES;
2209        return NO;
2210    }
2211   
2212    //enable resume selected waiting item
2213    if (action == @selector(resumeSelectedTorrentsNoWait:))
2214    {
2215        if (![fDefaults boolForKey: @"Queue"])
2216            return NO;
2217   
2218        Torrent * torrent;
2219        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2220        unsigned int i;
2221       
2222        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2223        {
2224            torrent = [fDisplayedTorrents objectAtIndex: i];
2225            if ([torrent isPaused] && [torrent progress] < 1.0)
2226                return YES;
2227        }
2228        return NO;
2229    }
2230
2231    //enable pause item
2232    if (action == @selector(stopSelectedTorrents:))
2233    {
2234        if (!canUseTable)
2235            return NO;
2236   
2237        Torrent * torrent;
2238        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2239        unsigned int i;
2240       
2241        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2242        {
2243            torrent = [fDisplayedTorrents objectAtIndex: i];
2244            if ([torrent isActive] || [torrent waitingToStart])
2245                return YES;
2246        }
2247        return NO;
2248    }
2249   
2250    //enable resume item
2251    if (action == @selector(resumeSelectedTorrents:))
2252    {
2253        if (!canUseTable)
2254            return NO;
2255   
2256        Torrent * torrent;
2257        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2258        unsigned int i;
2259       
2260        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2261        {
2262            torrent = [fDisplayedTorrents objectAtIndex: i];
2263            if ([torrent isPaused] && ![torrent waitingToStart])
2264                return YES;
2265        }
2266        return NO;
2267    }
2268   
2269    //enable copy torrent file item
2270    if (action == @selector(copyTorrentFile:))
2271        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2272
2273    return YES;
2274}
2275
2276- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2277{
2278    NSEnumerator * enumerator;
2279    Torrent * torrent;
2280    BOOL active;
2281
2282    switch (messageType)
2283    {
2284        case kIOMessageSystemWillSleep:
2285            //close all connections before going to sleep and remember we should resume when we wake up
2286            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2287
2288            //wait for running transfers to stop (5 second timeout)
2289            NSDate * start = [NSDate date];
2290            BOOL timeUp = NO;
2291           
2292            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2293            Torrent * torrent;
2294            while (!timeUp && (torrent = [enumerator nextObject]))
2295                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2296                {
2297                    usleep(100000);
2298                    [torrent update];
2299                }
2300
2301            IOAllowPowerChange(fRootPort, (long) messageArgument);
2302            break;
2303
2304        case kIOMessageCanSystemSleep:
2305            //pevent idle sleep unless all paused
2306            active = NO;
2307            enumerator = [fTorrents objectEnumerator];
2308            while ((torrent = [enumerator nextObject]))
2309                if ([torrent isActive])
2310                {
2311                    active = YES;
2312                    break;
2313                }
2314
2315            if (active)
2316                IOCancelPowerChange(fRootPort, (long) messageArgument);
2317            else
2318                IOAllowPowerChange(fRootPort, (long) messageArgument);
2319            break;
2320
2321        case kIOMessageSystemHasPoweredOn:
2322            //resume sleeping transfers after we wake up
2323            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2324            break;
2325    }
2326}
2327
2328- (void) resetDockBadge: (NSNotification *) notification
2329{
2330    float downloadRate, uploadRate;
2331    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2332   
2333    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2334}
2335
2336- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2337{
2338    //if auto size is enabled, the current frame shouldn't need to change
2339    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2340   
2341    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2342    return frame;
2343}
2344
2345- (void) setWindowSizeToFit
2346{
2347    if ([fDefaults boolForKey: @"AutoSize"])
2348    {
2349        [fScrollView setHasVerticalScroller: NO];
2350        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2351        [fScrollView setHasVerticalScroller: YES];
2352    }
2353}
2354
2355- (NSRect) sizedWindowFrame
2356{
2357    NSRect frame = [fWindow frame];
2358    float newHeight = frame.size.height - [fScrollView frame].size.height
2359        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2360
2361    float minHeight = [fWindow minSize].height;
2362    if (newHeight < minHeight)
2363        newHeight = minHeight;
2364    else
2365    {
2366        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2367        if ([fStatusBar isHidden])
2368            maxHeight -= [fStatusBar frame].size.height;
2369        if ([fFilterBar isHidden])
2370            maxHeight -= [fFilterBar frame].size.height;
2371       
2372        if (newHeight > maxHeight)
2373            newHeight = maxHeight;
2374    }
2375
2376    frame.origin.y -= (newHeight - frame.size.height);
2377    frame.size.height = newHeight;
2378    return frame;
2379}
2380
2381- (void) showMainWindow: (id) sender
2382{
2383    [fWindow makeKeyAndOrderFront: nil];
2384}
2385
2386- (void) windowDidBecomeKey: (NSNotification *) notification
2387{
2388    //reset dock badge for completed
2389    if (fCompleted > 0)
2390    {
2391        fCompleted = 0;
2392        [self resetDockBadge: nil];
2393    }
2394}
2395
2396- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2397{
2398    //only resize horizontally if autosize is enabled
2399    if ([fDefaults boolForKey: @"AutoSize"])
2400        proposedFrameSize.height = [fWindow frame].size.height;
2401    return proposedFrameSize;
2402}
2403
2404- (void) windowDidResize: (NSNotification *) notification
2405{
2406    //hide search filter if it overlaps filter buttons
2407    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2408}
2409
2410- (void) linkHomepage: (id) sender
2411{
2412    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2413}
2414
2415- (void) linkForums: (id) sender
2416{
2417    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2418}
2419
2420- (void) prepareForUpdate: (NSNotification *) notification
2421{
2422    fUpdateInProgress = YES;
2423}
2424
2425- (NSDictionary *) registrationDictionaryForGrowl
2426{
2427    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2428                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2429    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2430                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2431}
2432
2433@end
Note: See TracBrowser for help on using the repository browser.