source: trunk/macosx/Controller.m @ 1048

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

only create temporary torrent if import failed

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