source: trunk/macosx/Controller.m @ 1026

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

Use localized strings where necessary. Also a fix for the port checker. Thanks to Cédric Luthi for these.

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