source: trunk/macosx/Controller.m @ 1050

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

remove some 10.3 checks

  • Property svn:keywords set to Date Rev Author Id
File size: 86.9 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 1050 2006-11-03 02:49:16Z 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    [self applyFilter: nil];
971    [self checkToStartWaiting: torrent];
972
973    if ([fDefaults boolForKey: @"PlayDownloadSound"])
974    {
975        NSSound * sound;
976        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
977            [sound play];
978    }
979
980    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
981        description: [torrent name]
982        notificationName: GROWL_DOWNLOAD_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
983
984    if (![fWindow isKeyWindow])
985        fCompleted++;
986}
987
988- (void) updateTorrentHistory
989{
990    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
991
992    NSEnumerator * enumerator = [fTorrents objectEnumerator];
993    Torrent * torrent;
994    while ((torrent = [enumerator nextObject]))
995        [history addObject: [torrent history]];
996
997    [fDefaults setObject: history forKey: @"History"];
998    [fDefaults synchronize];
999}
1000
1001- (void) sortTorrents
1002{
1003    //remember selected rows if needed
1004    NSArray * selectedTorrents = nil;
1005    int numSelected = [fTableView numberOfSelectedRows];
1006    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1007        selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1008
1009    [self sortTorrentsIgnoreSelected]; //actually sort
1010   
1011    //set selected rows if needed
1012    if (selectedTorrents)
1013    {
1014        Torrent * torrent;
1015        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1016        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1017        while ((torrent = [enumerator nextObject]))
1018            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1019       
1020        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1021        [indexSet release];
1022    }
1023}
1024
1025//doesn't remember selected rows
1026- (void) sortTorrentsIgnoreSelected
1027{
1028    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1029                            ascending: YES selector: @selector(caseInsensitiveCompare:)] autorelease],
1030                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1031                                            ascending: YES] autorelease];
1032
1033    NSArray * descriptors;
1034    if ([fSortType isEqualToString: @"Name"])
1035        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1036    else if ([fSortType isEqualToString: @"State"])
1037    {
1038        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1039                                                @"stateSortKey" ascending: NO] autorelease],
1040                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1041                                            @"progressSortKey" ascending: NO] autorelease];
1042       
1043        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
1044                                                            nameDescriptor, orderDescriptor, nil];
1045    }
1046    else if ([fSortType isEqualToString: @"Progress"])
1047    {
1048        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1049                                            @"progressSortKey" ascending: YES] autorelease];
1050       
1051        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
1052    }
1053    else if ([fSortType isEqualToString: @"Date"])
1054    {
1055        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"date" ascending: YES] autorelease];
1056   
1057        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1058    }
1059    else
1060        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1061
1062    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1063    [descriptors release];
1064   
1065    [fTableView reloadData];
1066}
1067
1068- (void) setSort: (id) sender
1069{
1070    //get checked items
1071    NSMenuItem * prevSortItem, * prevSortActionItem;
1072    if ([fSortType isEqualToString: @"Name"])
1073    {
1074        prevSortItem = fNameSortItem;
1075        prevSortActionItem = fNameSortActionItem;
1076    }
1077    else if ([fSortType isEqualToString: @"State"])
1078    {
1079        prevSortItem = fStateSortItem;
1080        prevSortActionItem = fStateSortActionItem;
1081    }
1082    else if ([fSortType isEqualToString: @"Progress"])
1083    {
1084        prevSortItem = fProgressSortItem;
1085        prevSortActionItem = fProgressSortActionItem;
1086    }
1087    else if ([fSortType isEqualToString: @"Date"])
1088    {
1089        prevSortItem = fDateSortItem;
1090        prevSortActionItem = fDateSortActionItem;
1091    }
1092    else
1093    {
1094        prevSortItem = fOrderSortItem;
1095        prevSortActionItem = fOrderSortActionItem;
1096    }
1097   
1098    if (sender != prevSortItem && sender != prevSortActionItem)
1099    {
1100        [fSortType release];
1101       
1102        //get new items to check
1103        NSMenuItem * currentSortItem, * currentSortActionItem;
1104        if (sender == fNameSortItem || sender == fNameSortActionItem)
1105        {
1106            currentSortItem = fNameSortItem;
1107            currentSortActionItem = fNameSortActionItem;
1108            fSortType = [[NSString alloc] initWithString: @"Name"];
1109        }
1110        else if (sender == fStateSortItem || sender == fStateSortActionItem)
1111        {
1112            currentSortItem = fStateSortItem;
1113            currentSortActionItem = fStateSortActionItem;
1114            fSortType = [[NSString alloc] initWithString: @"State"];
1115        }
1116        else if (sender == fProgressSortItem || sender == fProgressSortActionItem)
1117        {
1118            currentSortItem = fProgressSortItem;
1119            currentSortActionItem = fProgressSortActionItem;
1120            fSortType = [[NSString alloc] initWithString: @"Progress"];
1121        }
1122        else if (sender == fDateSortItem || sender == fDateSortActionItem)
1123        {
1124            currentSortItem = fDateSortItem;
1125            currentSortActionItem = fDateSortActionItem;
1126            fSortType = [[NSString alloc] initWithString: @"Date"];
1127        }
1128        else
1129        {
1130            currentSortItem = fOrderSortItem;
1131            currentSortActionItem = fOrderSortActionItem;
1132            fSortType = [[NSString alloc] initWithString: @"Order"];
1133        }
1134   
1135        [prevSortItem setState: NSOffState];
1136        [prevSortActionItem setState: NSOffState];
1137        [currentSortItem setState: NSOnState];
1138        [currentSortActionItem setState: NSOnState];
1139       
1140        [fDefaults setObject: fSortType forKey: @"Sort"];
1141    }
1142
1143    [self sortTorrents];
1144}
1145
1146- (void) applyFilter: (id) sender
1147{
1148    //remember selected rows if needed
1149    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1150                ? [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1151
1152    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1153
1154    BOOL filtering = YES;
1155    if ([fFilterType isEqualToString: @"Pause"])
1156    {
1157        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1158        Torrent * torrent;
1159        while ((torrent = [enumerator nextObject]))
1160            if (![torrent isActive])
1161                [tempTorrents addObject: torrent];
1162    }
1163    else if ([fFilterType isEqualToString: @"Seed"])
1164    {
1165        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1166        Torrent * torrent;
1167        while ((torrent = [enumerator nextObject]))
1168            if ([torrent isActive] && [torrent progress] >= 1.0)
1169                [tempTorrents addObject: torrent];
1170    }
1171    else if ([fFilterType isEqualToString: @"Download"])
1172    {
1173        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1174        Torrent * torrent;
1175        while ((torrent = [enumerator nextObject]))
1176            if ([torrent isActive] && [torrent progress] < 1.0)
1177                [tempTorrents addObject: torrent];
1178    }
1179    else
1180    {
1181        filtering = NO;
1182        [tempTorrents setArray: fTorrents];
1183    }
1184   
1185    NSString * searchString = [fSearchFilterField stringValue];
1186    if ([searchString length] > 0)
1187    {
1188        filtering = YES;
1189       
1190        int i;
1191        for (i = [tempTorrents count] - 1; i >= 0; i--)
1192            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1193                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1194                [tempTorrents removeObjectAtIndex: i];
1195    }
1196   
1197    [fDisplayedTorrents setArray: tempTorrents];
1198    [tempTorrents release];
1199   
1200    [self sortTorrentsIgnoreSelected];
1201   
1202    //set selected rows if needed
1203    if (selectedTorrents)
1204    {
1205        Torrent * torrent;
1206        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1207        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1208        unsigned index;
1209        while ((torrent = [enumerator nextObject]))
1210            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1211                [indexSet addIndex: index];
1212       
1213        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1214        [indexSet release];
1215    }
1216   
1217    //set status bar torrent count text
1218    NSMutableString * totalTorrentsString = [NSMutableString stringWithString: @""];
1219    if (filtering)
1220        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1221   
1222    int totalCount = [fTorrents count];
1223    if (totalCount > 1)
1224        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfers", "Status bar transfer count"), totalCount];
1225    else
1226        [totalTorrentsString appendFormat: NSLocalizedString(@"%d Transfer", "Status bar transfer count"), totalCount];
1227   
1228    [fTotalTorrentsField setStringValue: totalTorrentsString];
1229
1230    [self setWindowSizeToFit];
1231}
1232
1233//resets filter and sorts torrents
1234- (void) setFilter: (id) sender
1235{
1236    BarButton * prevFilterButton;
1237    if ([fFilterType isEqualToString: @"Pause"])
1238        prevFilterButton = fPauseFilterButton;
1239    else if ([fFilterType isEqualToString: @"Seed"])
1240        prevFilterButton = fSeedFilterButton;
1241    else if ([fFilterType isEqualToString: @"Download"])
1242        prevFilterButton = fDownloadFilterButton;
1243    else
1244        prevFilterButton = fNoFilterButton;
1245   
1246    if (sender != prevFilterButton)
1247    {
1248        [prevFilterButton setEnabled: NO];
1249        [sender setEnabled: YES];
1250
1251        [fFilterType release];
1252        if (sender == fDownloadFilterButton)
1253            fFilterType = [[NSString alloc] initWithString: @"Download"];
1254        else if (sender == fPauseFilterButton)
1255            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1256        else if (sender == fSeedFilterButton)
1257            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1258        else
1259            fFilterType = [[NSString alloc] initWithString: @"None"];
1260
1261        [fDefaults setObject: fFilterType forKey: @"Filter"];
1262    }
1263
1264    [self applyFilter: nil];
1265}
1266
1267- (void) switchFilter: (id) sender
1268{
1269    NSButton * button;
1270    if ([fFilterType isEqualToString: @"None"])
1271        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1272    else if ([fFilterType isEqualToString: @"Download"])
1273        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1274    else if ([fFilterType isEqualToString: @"Seed"])
1275        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1276    else if ([fFilterType isEqualToString: @"Pause"])
1277        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1278    else
1279        button = fNoFilterButton;
1280   
1281    [self setFilter: button];
1282}
1283
1284- (void) toggleSpeedLimit: (id) sender
1285{
1286    BOOL setEnabled = ![fDefaults boolForKey: @"SpeedLimit"];
1287    int state = setEnabled ? NSOnState : NSOffState;
1288   
1289    [fDefaults setBool: setEnabled forKey: @"SpeedLimit"];
1290
1291    #warning get rid of
1292    [fSpeedLimitItem setState: state];
1293    [fSpeedLimitDockItem setState: state];
1294   
1295    [fSpeedLimitButton setImage: !setEnabled ? fSpeedLimitNormalImage
1296        : ([NSColor currentControlTint] == NSBlueControlTint ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage)];
1297   
1298    [fPrefsController applySpeedSettings: nil];
1299}
1300
1301- (void) autoSpeedLimitChange: (NSNotification *) notification
1302{
1303    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1304        return;
1305 
1306    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1307                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
1308        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1309                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
1310        * nowDate = [NSCalendarDate calendarDate];
1311   
1312    //check if should be on if within range
1313    BOOL shouldBeOn;
1314   
1315    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
1316        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
1317        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
1318   
1319    if (onTime == offTime)
1320        shouldBeOn = NO;
1321    else if (onTime < offTime)
1322        shouldBeOn = onTime <= nowTime && nowTime < offTime;
1323    else
1324        shouldBeOn = onTime <= nowTime || nowTime < offTime;
1325   
1326    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
1327        [self toggleSpeedLimit: nil];
1328}
1329
1330- (void) autoSpeedLimit: (NSTimer *) timer
1331{
1332    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1333        return;
1334   
1335    //only toggle if within first few seconds of minutes
1336    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
1337    if ([nowDate secondOfMinute] < AUTO_SPEED_LIMIT_SECONDS)
1338        return;
1339   
1340    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1341                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
1342   
1343    BOOL toggle;
1344    if ([fDefaults boolForKey: @"SpeedLimit"])
1345        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
1346    else
1347    {
1348        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
1349                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
1350        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
1351                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
1352    }
1353   
1354    if (toggle)
1355    {
1356        [self toggleSpeedLimit: nil];
1357       
1358        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
1359                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
1360                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
1361            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
1362            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1363    }
1364}
1365
1366- (void) setLimitGlobalEnabled: (id) sender
1367{
1368    [fPrefsController applySpeedSettings: nil];
1369}
1370
1371- (void) setQuickLimitGlobal: (id) sender
1372{
1373    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
1374    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
1375   
1376    [fPrefsController applySpeedSettings: nil];
1377}
1378
1379- (void) setQuickRatioGlobal: (id) sender
1380{
1381    [fDefaults setBool: YES forKey: @"RatioCheck"];
1382    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
1383}
1384
1385- (void) checkWaitingForStopped: (NSNotification *) notification
1386{
1387    [self checkToStartWaiting: [notification object]];
1388   
1389    [self updateUI: nil];
1390    [self applyFilter: nil];
1391    [self updateTorrentHistory];
1392}
1393
1394- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1395{
1396    //don't try to start a transfer if there should be none waiting
1397    if (![fDefaults boolForKey: @"Queue"])
1398        return;
1399
1400    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1401   
1402    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1403    Torrent * torrent, * torrentToStart = nil;
1404    while ((torrent = [enumerator nextObject]))
1405    {
1406        //ignore the torrent just stopped
1407        if (torrent == finishedTorrent)
1408            continue;
1409   
1410        if ([torrent isActive])
1411        {
1412            if (![torrent isSeeding] && ![torrent isError])
1413            {
1414                desiredActive--;
1415                if (desiredActive <= 0)
1416                    return;
1417            }
1418        }
1419        else
1420        {
1421            //use as next if it is waiting to start and either no previous or order value is lower
1422            if ([torrent waitingToStart] && (!torrentToStart
1423                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1424                torrentToStart = torrent;
1425        }
1426    }
1427   
1428    //since it hasn't returned, the queue amount has not been met
1429    if (torrentToStart)
1430    {
1431        [torrentToStart startTransfer];
1432       
1433        [self updateUI: nil];
1434        [self applyFilter: nil];
1435        [self updateTorrentHistory];
1436    }
1437}
1438
1439- (void) torrentStartSettingChange: (NSNotification *) notification
1440{
1441    [self attemptToStartMultipleAuto: [notification object]];
1442
1443    [self updateUI: nil];
1444    [self applyFilter: nil];
1445    [self updateTorrentHistory];
1446}
1447
1448- (void) globalStartSettingChange: (NSNotification *) notification
1449{
1450    [self attemptToStartMultipleAuto: fTorrents];
1451   
1452    [self updateUI: nil];
1453    [self applyFilter: nil];
1454    [self updateTorrentHistory];
1455}
1456
1457- (void) torrentStoppedForRatio: (NSNotification *) notification
1458{
1459    [self applyFilter: nil];
1460    [fInfoController updateInfoStats];
1461    [fInfoController updateInfoSettings];
1462   
1463    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1464    {
1465        NSSound * sound;
1466        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1467            [sound play];
1468    }
1469   
1470    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1471        description: [[notification object] name]
1472        notificationName: GROWL_SEEDING_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1473}
1474
1475- (void) attemptToStartAuto: (Torrent *) torrent
1476{
1477    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1478}
1479
1480//will try to start, taking into consideration the start preference
1481- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1482{
1483    if (![fDefaults boolForKey: @"Queue"])
1484    {
1485        NSEnumerator * enumerator = [torrents objectEnumerator];
1486        Torrent * torrent;
1487        while ((torrent = [enumerator nextObject]))
1488            if ([torrent waitingToStart])
1489                [torrent startTransfer];
1490       
1491        return;
1492    }
1493   
1494    //determine the number of downloads needed to start
1495    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1496           
1497    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1498    Torrent * torrent;
1499    while ((torrent = [enumerator nextObject]))
1500        if ([torrent isActive] && ![torrent isSeeding] && ![torrent isError])
1501        {
1502            desiredActive--;
1503            if (desiredActive <= 0)
1504                break;
1505        }
1506   
1507    //sort torrents by order value
1508    NSArray * sortedTorrents;
1509    if ([torrents count] > 1 && desiredActive > 0)
1510    {
1511        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1512                                                    @"orderValue" ascending: YES] autorelease];
1513        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1514       
1515        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1516        [descriptors release];
1517    }
1518    else
1519        sortedTorrents = torrents;
1520
1521    enumerator = [sortedTorrents objectEnumerator];
1522    while ((torrent = [enumerator nextObject]))
1523    {
1524        if ([torrent waitingToStart])
1525        {
1526            if ([torrent progress] >= 1.0)
1527                [torrent startTransfer];
1528            else if (desiredActive > 0)
1529            {
1530                [torrent startTransfer];
1531                desiredActive--;
1532            }
1533            else
1534                continue;
1535           
1536            [torrent update];
1537        }
1538    }
1539}
1540
1541-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
1542{
1543    if ([notification isEqualToString: UKFileWatcherWriteNotification])
1544        [self checkAutoImportDirectory];
1545}
1546
1547- (void) changeAutoImport
1548{
1549    [fAutoImportedNames removeAllObjects];
1550    [self checkAutoImportDirectory];
1551}
1552
1553- (void) checkAutoImportDirectory
1554{
1555    if (![fDefaults boolForKey: @"AutoImport"])
1556        return;
1557       
1558    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1559   
1560    NSArray * importedNames;
1561    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
1562        return;
1563   
1564    //only import those that have not been imported yet
1565    NSMutableArray * newNames = [importedNames mutableCopy];
1566    [newNames removeObjectsInArray: fAutoImportedNames];
1567    [fAutoImportedNames setArray: importedNames];
1568   
1569    NSEnumerator * enumerator = [newNames objectEnumerator];
1570    NSString * file;
1571    unsigned oldCount;
1572    while ((file = [enumerator nextObject]))
1573    {
1574        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1575        {
1576            int count = [fTorrents count];
1577            [self openFiles: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1578           
1579            //check if torrent was opened
1580            if ([fTorrents count] > count)
1581            {
1582                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
1583                    "Growl notification title") description: file
1584                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1585            }
1586            else
1587            {
1588                //create a temporary torrent to check if it didn't import because of error
1589                int error;
1590                tr_torrent_t * tempTor = tr_torrentInit(fLib, [[path stringByAppendingPathComponent: file] UTF8String],
1591                                                    0, & error);
1592               
1593                if (tempTor)
1594                    tr_torrentClose(fLib, tempTor);
1595                else if (error != TR_EUNSUPPORTED && error != TR_EDUPLICATE)
1596                    [fAutoImportedNames removeObjectIdenticalTo: file]; //can try to import later
1597                else;
1598            }
1599        }
1600    }
1601   
1602    [newNames release];
1603}
1604
1605- (int) numberOfRowsInTableView: (NSTableView *) tableview
1606{
1607    return [fDisplayedTorrents count];
1608}
1609
1610- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
1611{
1612    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
1613}
1614
1615- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1616    toPasteboard: (NSPasteboard *) pasteboard
1617{
1618    //only allow reordering of rows if sorting by order with no filter
1619    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1620            && [[fSearchFilterField stringValue] length] == 0)
1621    {
1622        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1623        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1624                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1625        return YES;
1626    }
1627    return NO;
1628}
1629
1630- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1631    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1632{
1633    NSPasteboard * pasteboard = [info draggingPasteboard];
1634    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1635    {
1636        //check if any files to add have "torrent" as an extension
1637        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1638        NSString * file;
1639        while ((file = [enumerator nextObject]))
1640            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1641            {
1642                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1643                return NSDragOperationGeneric;
1644            }
1645    }
1646    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1647    {
1648        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1649        return NSDragOperationGeneric;
1650    }
1651    else
1652        return NSDragOperationNone;
1653}
1654
1655- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1656    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1657{
1658    NSPasteboard * pasteboard = [info draggingPasteboard];
1659    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1660    {
1661        //create an array of files with the "torrent" extension
1662        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1663        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1664        NSString * file;
1665        while ((file = [enumerator nextObject]))
1666            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1667                [filesToOpen addObject: file];
1668   
1669        [self application: NSApp openFiles: filesToOpen];
1670        [filesToOpen release];
1671    }
1672    else
1673    {
1674        //remember selected rows if needed
1675        NSArray * selectedTorrents = nil;
1676        int numSelected = [fTableView numberOfSelectedRows];
1677        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1678            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1679   
1680        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1681                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1682       
1683        //move torrent in array
1684        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
1685        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1686       
1687        //determine the insertion index now that transfers to move have been removed
1688        int i, decrease = 0;
1689        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1690            decrease++;
1691       
1692        //insert objects at new location
1693        for (i = 0; i < [movingTorrents count]; i++)
1694            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1695       
1696        [movingTorrents release];
1697       
1698        //redo order values
1699        int low = [indexes firstIndex], high = [indexes lastIndex];
1700        if (newRow < low)
1701            low = newRow;
1702        else if (newRow > high + 1)
1703            high = newRow - 1;
1704        else;
1705       
1706        for (i = low; i <= high; i++)
1707            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1708       
1709        [fTableView reloadData];
1710       
1711        //set selected rows if needed
1712        if (selectedTorrents)
1713        {
1714            Torrent * torrent;
1715            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1716            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1717            while ((torrent = [enumerator nextObject]))
1718                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1719           
1720            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1721            [indexSet release];
1722        }
1723    }
1724   
1725    return YES;
1726}
1727
1728- (void) tableViewSelectionDidChange: (NSNotification *) notification
1729{
1730    [fInfoController updateInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
1731}
1732
1733- (void) toggleSmallView: (id) sender
1734{
1735    BOOL makeSmall = [fDefaults boolForKey: @"SmallView"];
1736   
1737    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1738   
1739    //window min height
1740    NSSize contentMinSize = [fWindow contentMinSize],
1741            contentSize = [[fWindow contentView] frame].size;
1742    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1743                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1744    [fWindow setContentMinSize: contentMinSize];
1745   
1746    //resize for larger min height if not set to auto size
1747    if (![fDefaults boolForKey: @"AutoSize"])
1748    {
1749        if (!makeSmall && contentSize.height < contentMinSize.height)
1750        {
1751            NSRect frame = [fWindow frame];
1752            float heightChange = contentMinSize.height - contentSize.height;
1753            frame.size.height += heightChange;
1754            frame.origin.y -= heightChange;
1755           
1756            [fWindow setFrame: frame display: YES];
1757            [fTableView reloadData];
1758        }
1759    }
1760    else
1761        [self setWindowSizeToFit];
1762}
1763
1764- (void) toggleStatusBar: (id) sender
1765{
1766    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1767    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1768}
1769
1770- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1771{
1772    if (show != [fStatusBar isHidden])
1773        return;
1774
1775    if (show)
1776        [fStatusBar setHidden: NO];
1777
1778    NSRect frame = [fWindow frame];
1779    float heightChange = [fStatusBar frame].size.height;
1780    if (!show)
1781        heightChange *= -1;
1782   
1783    //allow bar to show even if not enough room
1784    if (show && ![fDefaults boolForKey: @"AutoSize"])
1785    {
1786        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1787        if (frame.size.height > maxHeight)
1788        {
1789            float change = maxHeight - frame.size.height;
1790            frame.size.height += change;
1791            frame.origin.y -= change;
1792           
1793            [fWindow setFrame: frame display: NO animate: NO];
1794        }
1795    }
1796
1797    frame.size.height += heightChange;
1798    frame.origin.y -= heightChange;
1799   
1800    [self updateUI: nil];
1801   
1802    //set views to not autoresize
1803    unsigned int statsMask = [fStatusBar autoresizingMask];
1804    unsigned int filterMask = [fFilterBar autoresizingMask];
1805    unsigned int scrollMask = [fScrollView autoresizingMask];
1806    [fStatusBar setAutoresizingMask: 0];
1807    [fFilterBar setAutoresizingMask: 0];
1808    [fScrollView setAutoresizingMask: 0];
1809   
1810    [fWindow setFrame: frame display: YES animate: animate];
1811   
1812    //re-enable autoresize
1813    [fStatusBar setAutoresizingMask: statsMask];
1814    [fFilterBar setAutoresizingMask: filterMask];
1815    [fScrollView setAutoresizingMask: scrollMask];
1816   
1817    //change min size
1818    NSSize minSize = [fWindow contentMinSize];
1819    minSize.height += heightChange;
1820    [fWindow setContentMinSize: minSize];
1821   
1822    if (!show)
1823        [fStatusBar setHidden: YES];
1824}
1825
1826- (void) toggleFilterBar: (id) sender
1827{
1828    //disable filtering when hiding
1829    if (![fFilterBar isHidden])
1830    {
1831        [fSearchFilterField setStringValue: @""];
1832        [self setFilter: fNoFilterButton];
1833    }
1834
1835    [self showFilterBar: [fFilterBar isHidden] animate: YES];
1836    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
1837}
1838
1839- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1840{
1841    if (show != [fFilterBar isHidden])
1842        return;
1843
1844    if (show)
1845        [fFilterBar setHidden: NO];
1846
1847    NSRect frame = [fWindow frame];
1848    float heightChange = [fFilterBar frame].size.height;
1849    if (!show)
1850        heightChange *= -1;
1851   
1852    //allow bar to show even if not enough room
1853    if (show && ![fDefaults boolForKey: @"AutoSize"])
1854    {
1855        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1856        if (frame.size.height > maxHeight)
1857        {
1858            float change = maxHeight - frame.size.height;
1859            frame.size.height += change;
1860            frame.origin.y -= change;
1861           
1862            [fWindow setFrame: frame display: NO animate: NO];
1863        }
1864    }
1865
1866    frame.size.height += heightChange;
1867    frame.origin.y -= heightChange;
1868   
1869    //set views to not autoresize
1870    unsigned int filterMask = [fFilterBar autoresizingMask];
1871    unsigned int scrollMask = [fScrollView autoresizingMask];
1872    [fFilterBar setAutoresizingMask: 0];
1873    [fScrollView setAutoresizingMask: 0];
1874   
1875    [fWindow setFrame: frame display: YES animate: animate];
1876   
1877    //re-enable autoresize
1878    [fFilterBar setAutoresizingMask: filterMask];
1879    [fScrollView setAutoresizingMask: scrollMask];
1880   
1881    //change min size
1882    NSSize minSize = [fWindow contentMinSize];
1883    minSize.height += heightChange;
1884    [fWindow setContentMinSize: minSize];
1885   
1886    if (!show)
1887    {
1888        [fFilterBar setHidden: YES];
1889        [fWindow makeFirstResponder: fTableView];
1890    }
1891}
1892
1893- (void) toggleAdvancedBar: (id) sender
1894{
1895    [fTableView display];
1896}
1897
1898- (void) doNothing: (id) sender {}
1899
1900- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1901    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1902{
1903    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1904
1905    if ([ident isEqualToString: TOOLBAR_OPEN])
1906    {
1907        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
1908        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
1909        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
1910        [item setImage: [NSImage imageNamed: @"Open.png"]];
1911        [item setTarget: self];
1912        [item setAction: @selector(openShowSheet:)];
1913    }
1914    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1915    {
1916        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
1917        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
1918        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
1919        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1920        [item setTarget: self];
1921        [item setAction: @selector(removeNoDelete:)];
1922    }
1923    else if ([ident isEqualToString: TOOLBAR_INFO])
1924    {
1925        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
1926        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
1927        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
1928        [item setImage: [NSImage imageNamed: @"Info.png"]];
1929        [item setTarget: self];
1930        [item setAction: @selector(showInfo:)];
1931    }
1932    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1933    {
1934        [item setLabel: NSLocalizedString(@"Pause All", "Pause All toolbar item -> label")];
1935        [item setPaletteLabel: [item label]];
1936        [item setToolTip: NSLocalizedString(@"Pause all transfers", "Pause All toolbar item -> tooltip")];
1937        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1938        [item setTarget: self];
1939        [item setAction: @selector(stopAllTorrents:)];
1940    }
1941    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1942    {
1943        [item setLabel: NSLocalizedString(@"Resume All", "Resume All toolbar item -> label")];
1944        [item setPaletteLabel: [item label]];
1945        [item setToolTip: NSLocalizedString(@"Resume all transfers", "Resume All toolbar item -> tooltip")];
1946        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1947        [item setTarget: self];
1948        [item setAction: @selector(resumeAllTorrents:)];
1949    }
1950    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1951    {
1952        [item setLabel: NSLocalizedString(@"Pause", "Pause toolbar item -> label")];
1953        [item setPaletteLabel: NSLocalizedString(@"Pause Selected", "Pause toolbar item -> palette label")];
1954        [item setToolTip: NSLocalizedString(@"Pause selected transfers", "Pause toolbar item -> tooltip")];
1955        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1956        [item setTarget: self];
1957        [item setAction: @selector(stopSelectedTorrents:)];
1958    }
1959    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1960    {
1961        [item setLabel: NSLocalizedString(@"Resume", "Resume toolbar item -> label")];
1962        [item setPaletteLabel: NSLocalizedString(@"Resume Selected", "Resume toolbar item -> palette label")];
1963        [item setToolTip: NSLocalizedString(@"Resume selected transfers", "Resume toolbar item -> tooltip")];
1964        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1965        [item setTarget: self];
1966        [item setAction: @selector(resumeSelectedTorrents:)];
1967    }
1968    else if ([ident isEqualToString: TOOLBAR_FILTER])
1969    {
1970        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
1971        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
1972        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
1973        [item setImage: [NSImage imageNamed: @"Filter.png"]];
1974        [item setTarget: self];
1975        [item setAction: @selector(toggleFilterBar:)];
1976    }
1977    else
1978    {
1979        [item release];
1980        return nil;
1981    }
1982
1983    return item;
1984}
1985
1986- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1987{
1988    return [NSArray arrayWithObjects:
1989            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1990            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1991            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
1992            NSToolbarSeparatorItemIdentifier,
1993            NSToolbarSpaceItemIdentifier,
1994            NSToolbarFlexibleSpaceItemIdentifier,
1995            NSToolbarCustomizeToolbarItemIdentifier, nil];
1996}
1997
1998- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1999{
2000    return [NSArray arrayWithObjects:
2001            TOOLBAR_OPEN, TOOLBAR_REMOVE,
2002            NSToolbarSeparatorItemIdentifier,
2003            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2004            NSToolbarFlexibleSpaceItemIdentifier,
2005            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2006}
2007
2008- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2009{
2010    NSString * ident = [toolbarItem itemIdentifier];
2011
2012    //enable remove item
2013    if ([ident isEqualToString: TOOLBAR_REMOVE])
2014        return [fTableView numberOfSelectedRows] > 0;
2015
2016    //enable pause all item
2017    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2018    {
2019        Torrent * torrent;
2020        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2021        while ((torrent = [enumerator nextObject]))
2022            if ([torrent isActive] || [torrent waitingToStart])
2023                return YES;
2024        return NO;
2025    }
2026
2027    //enable resume all item
2028    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2029    {
2030        Torrent * torrent;
2031        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2032        while ((torrent = [enumerator nextObject]))
2033            if ([torrent isPaused] && ![torrent waitingToStart])
2034                return YES;
2035        return NO;
2036    }
2037
2038    //enable pause item
2039    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2040    {
2041        Torrent * torrent;
2042        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2043        unsigned int i;
2044       
2045        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2046        {
2047            torrent = [fDisplayedTorrents objectAtIndex: i];
2048            if ([torrent isActive] || [torrent waitingToStart])
2049                return YES;
2050        }
2051        return NO;
2052    }
2053   
2054    //enable resume item
2055    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2056    {
2057        Torrent * torrent;
2058        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2059        unsigned int i;
2060       
2061        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2062        {
2063            torrent = [fDisplayedTorrents objectAtIndex: i];
2064            if ([torrent isPaused] && ![torrent waitingToStart])
2065                return YES;
2066        }
2067        return NO;
2068    }
2069
2070    return YES;
2071}
2072
2073- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2074{
2075    SEL action = [menuItem action];
2076
2077    //only enable some items if it is in a context menu or the window is useable
2078    BOOL canUseTable = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
2079
2080    //enable open items
2081    if (action == @selector(openShowSheet:))
2082        return [fWindow attachedSheet] == nil;
2083   
2084    //enable sort and advanced bar items
2085    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2086        return [fWindow isVisible];
2087
2088    //enable show info
2089    if (action == @selector(showInfo:))
2090    {
2091        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector",
2092                            "View menu -> Inspector") : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
2093        if (![[menuItem title] isEqualToString: title])
2094                [menuItem setTitle: title];
2095
2096        return YES;
2097    }
2098   
2099    //enable prev/next inspector tab
2100    if (action == @selector(setInfoTab:))
2101        return [[fInfoController window] isVisible];
2102   
2103    //enable toggle status bar
2104    if (action == @selector(toggleStatusBar:))
2105    {
2106        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
2107                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
2108        if (![[menuItem title] isEqualToString: title])
2109            [menuItem setTitle: title];
2110
2111        return [fWindow isVisible];
2112    }
2113   
2114    //enable toggle filter bar
2115    if (action == @selector(toggleFilterBar:))
2116    {
2117        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
2118                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
2119        if (![[menuItem title] isEqualToString: title])
2120            [menuItem setTitle: title];
2121
2122        return [fWindow isVisible];
2123    }
2124   
2125    //enable prev/next filter button
2126    if (action == @selector(switchFilter:))
2127        return [fWindow isVisible] && ![fFilterBar isHidden];
2128
2129    //enable reveal in finder
2130    if (action == @selector(revealFile:))
2131        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2132
2133    //enable remove items
2134    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2135        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2136    {
2137        BOOL warning = NO,
2138            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2139            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2140        Torrent * torrent;
2141        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2142        unsigned int i;
2143       
2144        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2145        {
2146            torrent = [fDisplayedTorrents objectAtIndex: i];
2147            if (!warning && [torrent isActive])
2148            {
2149                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2150                if (warning && canDelete)
2151                    break;
2152            }
2153            if (!canDelete && [torrent publicTorrent])
2154            {
2155                canDelete = YES;
2156                if (warning)
2157                    break;
2158            }
2159        }
2160   
2161        //append or remove ellipsis when needed
2162        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2163        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2164        {
2165            if (![title hasSuffix: ellipsis])
2166                [menuItem setTitle: [title stringByAppendingEllipsis]];
2167        }
2168        else
2169        {
2170            if ([title hasSuffix: ellipsis])
2171                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2172        }
2173       
2174        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2175    }
2176
2177    //enable pause all item
2178    if (action == @selector(stopAllTorrents:))
2179    {
2180        Torrent * torrent;
2181        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2182        while ((torrent = [enumerator nextObject]))
2183            if ([torrent isActive] || [torrent waitingToStart])
2184                return YES;
2185        return NO;
2186    }
2187   
2188    //enable resume all item
2189    if (action == @selector(resumeAllTorrents:))
2190    {
2191        Torrent * torrent;
2192        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2193        while ((torrent = [enumerator nextObject]))
2194            if ([torrent isPaused] && ![torrent waitingToStart])
2195                return YES;
2196        return NO;
2197    }
2198   
2199    //enable resume all waiting item
2200    if (action == @selector(resumeWaitingTorrents:))
2201    {
2202        if (![fDefaults boolForKey: @"Queue"])
2203            return NO;
2204   
2205        Torrent * torrent;
2206        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2207        while ((torrent = [enumerator nextObject]))
2208            if ([torrent waitingToStart])
2209                return YES;
2210        return NO;
2211    }
2212   
2213    //enable resume selected waiting item
2214    if (action == @selector(resumeSelectedTorrentsNoWait:))
2215    {
2216        if (![fDefaults boolForKey: @"Queue"])
2217            return NO;
2218   
2219        Torrent * torrent;
2220        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2221        unsigned int i;
2222       
2223        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2224        {
2225            torrent = [fDisplayedTorrents objectAtIndex: i];
2226            if ([torrent isPaused] && [torrent progress] < 1.0)
2227                return YES;
2228        }
2229        return NO;
2230    }
2231
2232    //enable pause item
2233    if (action == @selector(stopSelectedTorrents:))
2234    {
2235        if (!canUseTable)
2236            return NO;
2237   
2238        Torrent * torrent;
2239        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2240        unsigned int i;
2241       
2242        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2243        {
2244            torrent = [fDisplayedTorrents objectAtIndex: i];
2245            if ([torrent isActive] || [torrent waitingToStart])
2246                return YES;
2247        }
2248        return NO;
2249    }
2250   
2251    //enable resume item
2252    if (action == @selector(resumeSelectedTorrents:))
2253    {
2254        if (!canUseTable)
2255            return NO;
2256   
2257        Torrent * torrent;
2258        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2259        unsigned int i;
2260       
2261        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2262        {
2263            torrent = [fDisplayedTorrents objectAtIndex: i];
2264            if ([torrent isPaused] && ![torrent waitingToStart])
2265                return YES;
2266        }
2267        return NO;
2268    }
2269   
2270    //enable copy torrent file item
2271    if (action == @selector(copyTorrentFile:))
2272        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2273
2274    return YES;
2275}
2276
2277- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2278{
2279    NSEnumerator * enumerator;
2280    Torrent * torrent;
2281    BOOL active;
2282
2283    switch (messageType)
2284    {
2285        case kIOMessageSystemWillSleep:
2286            //close all connections before going to sleep and remember we should resume when we wake up
2287            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2288
2289            //wait for running transfers to stop (5 second timeout)
2290            NSDate * start = [NSDate date];
2291            BOOL timeUp = NO;
2292           
2293            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2294            Torrent * torrent;
2295            while (!timeUp && (torrent = [enumerator nextObject]))
2296                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2297                {
2298                    usleep(100000);
2299                    [torrent update];
2300                }
2301
2302            IOAllowPowerChange(fRootPort, (long) messageArgument);
2303            break;
2304
2305        case kIOMessageCanSystemSleep:
2306            //pevent idle sleep unless all paused
2307            active = NO;
2308            enumerator = [fTorrents objectEnumerator];
2309            while ((torrent = [enumerator nextObject]))
2310                if ([torrent isActive])
2311                {
2312                    active = YES;
2313                    break;
2314                }
2315
2316            if (active)
2317                IOCancelPowerChange(fRootPort, (long) messageArgument);
2318            else
2319                IOAllowPowerChange(fRootPort, (long) messageArgument);
2320            break;
2321
2322        case kIOMessageSystemHasPoweredOn:
2323            //resume sleeping transfers after we wake up
2324            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2325            break;
2326    }
2327}
2328
2329- (void) resetDockBadge: (NSNotification *) notification
2330{
2331    float downloadRate, uploadRate;
2332    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2333   
2334    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2335}
2336
2337- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2338{
2339    //if auto size is enabled, the current frame shouldn't need to change
2340    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2341   
2342    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2343    return frame;
2344}
2345
2346- (void) setWindowSizeToFit
2347{
2348    if ([fDefaults boolForKey: @"AutoSize"])
2349    {
2350        [fScrollView setHasVerticalScroller: NO];
2351        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2352        [fScrollView setHasVerticalScroller: YES];
2353    }
2354}
2355
2356- (NSRect) sizedWindowFrame
2357{
2358    NSRect frame = [fWindow frame];
2359    float newHeight = frame.size.height - [fScrollView frame].size.height
2360        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2361
2362    float minHeight = [fWindow minSize].height;
2363    if (newHeight < minHeight)
2364        newHeight = minHeight;
2365    else
2366    {
2367        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2368        if ([fStatusBar isHidden])
2369            maxHeight -= [fStatusBar frame].size.height;
2370        if ([fFilterBar isHidden])
2371            maxHeight -= [fFilterBar frame].size.height;
2372       
2373        if (newHeight > maxHeight)
2374            newHeight = maxHeight;
2375    }
2376
2377    frame.origin.y -= (newHeight - frame.size.height);
2378    frame.size.height = newHeight;
2379    return frame;
2380}
2381
2382- (void) showMainWindow: (id) sender
2383{
2384    [fWindow makeKeyAndOrderFront: nil];
2385}
2386
2387- (void) windowDidBecomeKey: (NSNotification *) notification
2388{
2389    //reset dock badge for completed
2390    if (fCompleted > 0)
2391    {
2392        fCompleted = 0;
2393        [self resetDockBadge: nil];
2394    }
2395}
2396
2397- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2398{
2399    //only resize horizontally if autosize is enabled
2400    if ([fDefaults boolForKey: @"AutoSize"])
2401        proposedFrameSize.height = [fWindow frame].size.height;
2402    return proposedFrameSize;
2403}
2404
2405- (void) windowDidResize: (NSNotification *) notification
2406{
2407    //hide search filter if it overlaps filter buttons
2408    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2409}
2410
2411- (void) linkHomepage: (id) sender
2412{
2413    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2414}
2415
2416- (void) linkForums: (id) sender
2417{
2418    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2419}
2420
2421- (void) prepareForUpdate: (NSNotification *) notification
2422{
2423    fUpdateInProgress = YES;
2424}
2425
2426- (NSDictionary *) registrationDictionaryForGrowl
2427{
2428    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2429                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2430    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2431                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2432}
2433
2434@end
Note: See TracBrowser for help on using the repository browser.