source: trunk/macosx/Controller.m @ 1046

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

autoimport can now tell if not opening was a result of the torrent already existing or not being supported

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