source: trunk/macosx/Controller.m @ 1034

Last change on this file since 1034 was 1034, checked in by livings124, 16 years ago

Partial use of bindings in prefs/action menu. This is still experimental and evolving, with the most obvious problem that entering an invalid value causes an annoying error sheet to appear.

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