source: trunk/macosx/Controller.m @ 1027

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

some cleanup from the previous commit

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