source: trunk/macosx/Controller.m @ 1041

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

actually toggle speed limit

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