source: trunk/macosx/Controller.m @ 1058

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

don't autovalidate toolbar items that never change

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