source: trunk/macosx/Controller.m @ 1049

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

Use an NSDatePicker for the speed limit scheduler...this will require 10.4 for now.

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