source: trunk/macosx/Controller.m @ 920

Last change on this file since 920 was 920, checked in by joshe, 15 years ago

Merge nat-traversal branch to trunk.

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