source: trunk/macosx/Controller.m @ 1013

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

use a mutable array

  • Property svn:keywords set to Date Rev Author Id
File size: 83.4 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 1013 2006-10-16 02:42:46Z livings124 $
3 *
4 * Copyright (c) 2005-2006 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import <IOKit/IOMessage.h>
26
27#import "Controller.h"
28#import "Torrent.h"
29#import "TorrentCell.h"
30#import "TorrentTableView.h"
31#import "StringAdditions.h"
32#import "UKKQueue.h"
33
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        fPrefsController = [[PrefsController alloc] initWithWindowNibName: @"PrefsWindow" handle: fLib];
90       
91        fBadger = [[Badger alloc] init];
92       
93        [GrowlApplicationBridge setGrowlDelegate: self];
94       
95        [[UKKQueue sharedFileWatcher] setDelegate: self];
96    }
97    return self;
98}
99
100- (void) dealloc
101{
102    [[NSNotificationCenter defaultCenter] removeObserver: self];
103   
104    [fInfoController release];
105    [fMessageController release];
106    [fPrefsController release];
107   
108    [fToolbar release];
109    [fTorrents release];
110    [fDisplayedTorrents release];
111    [fBadger release];
112   
113    [fSortType release];
114    [fFilterType release];
115   
116    [fAutoImportedNames 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(changeAutoImport)
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    //timer to auto toggle speed limit
363    [self autoSpeedLimitChange: nil];
364    fSpeedLimitTimer = [NSTimer scheduledTimerWithTimeInterval: AUTO_SPEED_LIMIT_SECONDS target: self
365        selector: @selector(autoSpeedLimit:) userInfo: nil repeats: YES];
366   
367    [self checkAutoImportDirectory];
368}
369
370- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
371{
372    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
373        [fWindow makeKeyAndOrderFront: nil];
374    return NO;
375}
376
377- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
378{
379    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
380    {
381        int active = 0, downloading = 0;
382        Torrent * torrent;
383        NSEnumerator * enumerator = [fTorrents objectEnumerator];
384        while ((torrent = [enumerator nextObject]))
385            if ([torrent isActive])
386            {
387                active++;
388                if (![torrent isSeeding])
389                    downloading++;
390            }
391
392        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
393        {
394            NSString * message = active == 1
395                ? @"There is an active transfer. Do you really want to quit?"
396                : [NSString stringWithFormat:
397                    @"There are %d active transfers. Do you really want to quit?", active];
398
399            NSBeginAlertSheet(@"Confirm Quit", @"Quit", @"Cancel", nil, fWindow, self,
400                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
401            return NSTerminateLater;
402        }
403    }
404
405    return NSTerminateNow;
406}
407
408- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
409{
410    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
411}
412
413- (void) applicationWillTerminate: (NSNotification *) notification
414{
415    //stop timers
416    [fSpeedLimitTimer invalidate];
417    [fTimer invalidate];
418   
419    //save history and stop running torrents
420    [self updateTorrentHistory];
421    [fTorrents makeObjectsPerformSelector: @selector(stopTransferForQuit)];
422   
423    //disable NAT traversal
424    tr_natTraversalDisable(fLib);
425   
426    //remember window states and close all windows
427    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
428    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
429    [self showStatusBar: NO animate: NO];
430    [self showFilterBar: NO animate: NO];
431   
432    //clear badge
433    [fBadger clearBadge];
434
435    //end quickly if the app is updating
436    if (fUpdateInProgress)
437        return;
438
439    //wait for running transfers to stop (5 second timeout) and for NAT to be disabled
440    NSDate * start = [NSDate date];
441    BOOL timeUp = NO;
442   
443    NSEnumerator * enumerator = [fTorrents objectEnumerator];
444    Torrent * torrent;
445    while (!timeUp && ((torrent = [enumerator nextObject]) || tr_natTraversalStatus(fLib) != TR_NAT_TRAVERSAL_DISABLED))
446        while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
447        {
448            usleep(100000);
449            [torrent update];
450        }
451}
452
453- (NSArray *) torrentsAtIndexes: (NSIndexSet *) indexSet
454{
455    if ([fDisplayedTorrents respondsToSelector: @selector(objectsAtIndexes:)])
456        return [fDisplayedTorrents objectsAtIndexes: indexSet];
457    else
458    {
459        NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [indexSet count]];
460        unsigned int i;
461        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
462            [torrents addObject: [fDisplayedTorrents objectAtIndex: i]];
463
464        return torrents;
465    }
466}
467
468- (void) application: (NSApplication *) sender openFiles: (NSArray *) filenames
469{
470    [self openFiles: filenames ignoreDownloadFolder: NO];
471}
472
473- (void) openFiles: (NSArray *) filenames ignoreDownloadFolder: (BOOL) ignore
474{
475    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"], * torrentPath;
476   
477    if (ignore || [downloadChoice isEqualToString: @"Ask"])
478    {
479        [self openFilesAsk: [filenames mutableCopy]];
480        return;
481    }
482   
483    Torrent * torrent;
484    NSEnumerator * enumerator = [filenames objectEnumerator];
485    while ((torrentPath = [enumerator nextObject]))
486    {
487        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
488            continue;
489
490        //add it to the "File > Open Recent" menu
491        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
492
493        NSString * folder = [downloadChoice isEqualToString: @"Constant"]
494            ? [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]
495            : [torrentPath stringByDeletingLastPathComponent];
496       
497        [torrent setDownloadFolder: folder];
498        [torrent update];
499        [self attemptToStartAuto: torrent];
500       
501        [fTorrents addObject: torrent];
502        [torrent release];
503    }
504
505    [self updateUI: nil];
506    [self applyFilter: nil];
507   
508    [self updateTorrentHistory];
509}
510
511//called by the main open method to show sheet for choosing download location
512- (void) openFilesAsk: (NSMutableArray *) files
513{
514    NSString * torrentPath;
515    Torrent * torrent;
516    do
517    {
518        if ([files count] == 0) //recursive base case
519        {
520            [files release];
521           
522            [self updateTorrentHistory];
523            return;
524        }
525   
526        torrentPath = [files objectAtIndex: 0];
527        torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib];
528       
529        [files removeObjectAtIndex: 0];
530    } while (!torrent);
531
532    //add it to the "File > Open Recent" menu
533    [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
534
535    NSOpenPanel * panel = [NSOpenPanel openPanel];
536
537    [panel setPrompt: @"Select"];
538    [panel setAllowsMultipleSelection: NO];
539    [panel setCanChooseFiles: NO];
540    [panel setCanChooseDirectories: YES];
541
542    [panel setMessage: [NSString stringWithFormat: @"Select the download folder for \"%@\"", [torrent name]]];
543   
544    NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: torrent, @"Torrent", files, @"Files", nil];
545
546    [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
547            didEndSelector: @selector(folderChoiceClosed:returnCode:contextInfo:) contextInfo: dictionary];
548}
549
550- (void) folderChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code
551    contextInfo: (NSDictionary *) dictionary
552{
553    Torrent * torrent = [dictionary objectForKey: @"Torrent"];
554
555    if (code == NSOKButton)
556    {
557        [torrent setDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
558        [torrent update];
559        [self attemptToStartAuto: torrent];
560       
561        [fTorrents addObject: torrent];
562       
563        [self updateUI: nil];
564        [self applyFilter: nil];
565    }
566   
567    [self performSelectorOnMainThread: @selector(openFilesAsk:) withObject: [dictionary objectForKey: @"Files"]
568                        waitUntilDone: NO];
569   
570    [torrent release];
571    [dictionary release];
572}
573
574//called on by applescript
575- (void) open: (NSArray *) files
576{
577    [self performSelectorOnMainThread: @selector(openFiles:) withObject: files waitUntilDone: NO];
578}
579
580- (void) openFiles: (NSArray *) filenames
581{
582    [self openFiles: filenames ignoreDownloadFolder: NO];
583}
584
585- (void) openShowSheet: (id) sender
586{
587    NSOpenPanel * panel = [NSOpenPanel openPanel];
588
589    [panel setAllowsMultipleSelection: YES];
590    [panel setCanChooseFiles: YES];
591    [panel setCanChooseDirectories: NO];
592
593    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
594        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
595        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
596}
597
598- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSNumber *) ignore
599{
600    if (code == NSOKButton)
601    {
602        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
603                                        [panel filenames], @"Files", ignore, @"Ignore", nil];
604        [self performSelectorOnMainThread: @selector(openFromSheet:) withObject: dictionary waitUntilDone: NO];
605    }
606}
607
608- (void) openFromSheet: (NSDictionary *) dictionary
609{
610    [self openFiles: [dictionary objectForKey: @"Files"]
611        ignoreDownloadFolder: [[dictionary objectForKey: @"Ignore"] boolValue]];
612   
613    [dictionary release];
614}
615
616- (void) resumeSelectedTorrents: (id) sender
617{
618    [self resumeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
619}
620
621- (void) resumeAllTorrents: (id) sender
622{
623    [self resumeTorrents: fTorrents];
624}
625
626- (void) resumeTorrents: (NSArray *) torrents
627{
628    NSEnumerator * enumerator = [torrents objectEnumerator];
629    Torrent * torrent;
630    while ((torrent = [enumerator nextObject]))
631        [torrent setWaitToStart: YES];
632   
633    [self attemptToStartMultipleAuto: torrents];
634   
635    [self updateUI: nil];
636    [self applyFilter: nil];
637    [self updateTorrentHistory];
638}
639
640- (void) resumeSelectedTorrentsNoWait:  (id) sender
641{
642    [self resumeTorrentsNoWait: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
643}
644
645- (void) resumeWaitingTorrents: (id) sender
646{
647    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
648   
649    NSEnumerator * enumerator = [fTorrents objectEnumerator];
650    Torrent * torrent;
651    while ((torrent = [enumerator nextObject]))
652        if ([torrent waitingToStart])
653            [torrents addObject: torrent];
654   
655    [self resumeTorrentsNoWait: torrents];
656}
657
658- (void) resumeTorrentsNoWait: (NSArray *) torrents
659{
660    //iterate through instead of all at once to ensure no conflicts
661    NSEnumerator * enumerator = [torrents objectEnumerator];
662    Torrent * torrent;
663    while ((torrent = [enumerator nextObject]))
664        [torrent 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) updateControlTint: (NSNotification *) notification
940{
941    if (fSpeedLimitEnabled)
942        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
943                                        ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage];
944}
945
946- (void) updateUI: (NSTimer *) timer
947{
948    [fTorrents makeObjectsPerformSelector: @selector(update)];
949
950    //resort if necessary or just update the table
951    if ([fSortType isEqualToString: @"Progress"] || [fSortType isEqualToString: @"State"])
952        [self sortTorrents];
953    else
954        [fTableView reloadData];
955   
956    //update the global DL/UL rates
957    float downloadRate, uploadRate;
958    tr_torrentRates(fLib, & downloadRate, & uploadRate);
959    if (![fStatusBar isHidden])
960    {
961        [fTotalDLField setStringValue: [@"Total DL: " stringByAppendingString: [NSString stringForSpeed: downloadRate]]];
962        [fTotalULField setStringValue: [@"Total UL: " stringByAppendingString: [NSString stringForSpeed: uploadRate]]];
963    }
964
965    //update non-constant parts of info window
966    if ([[fInfoController window] isVisible])
967        [fInfoController updateInfoStats];
968
969    //badge dock
970    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
971}
972
973- (void) torrentFinishedDownloading: (NSNotification *) notification
974{
975    Torrent * torrent = [notification object];
976
977    [self applyFilter: nil];
978    [self checkToStartWaiting: torrent];
979
980    if ([fDefaults boolForKey: @"PlayDownloadSound"])
981    {
982        NSSound * sound;
983        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
984            [sound play];
985    }
986
987    [GrowlApplicationBridge notifyWithTitle: @"Download Complete" description: [torrent name]
988        notificationName: GROWL_DOWNLOAD_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
989
990    if (![fWindow isKeyWindow])
991        fCompleted++;
992}
993
994- (void) updateTorrentHistory
995{
996    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
997
998    NSEnumerator * enumerator = [fTorrents objectEnumerator];
999    Torrent * torrent;
1000    while ((torrent = [enumerator nextObject]))
1001        [history addObject: [torrent history]];
1002
1003    [fDefaults setObject: history forKey: @"History"];
1004    [fDefaults synchronize];
1005}
1006
1007- (void) sortTorrents
1008{
1009    //remember selected rows if needed
1010    NSArray * selectedTorrents = nil;
1011    int numSelected = [fTableView numberOfSelectedRows];
1012    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1013        selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1014
1015    [self sortTorrentsIgnoreSelected]; //actually sort
1016   
1017    //set selected rows if needed
1018    if (selectedTorrents)
1019    {
1020        Torrent * torrent;
1021        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1022        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1023        while ((torrent = [enumerator nextObject]))
1024            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1025       
1026        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1027        [indexSet release];
1028    }
1029}
1030
1031//doesn't remember selected rows
1032- (void) sortTorrentsIgnoreSelected
1033{
1034    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1035                            ascending: YES selector: @selector(caseInsensitiveCompare:)] autorelease],
1036                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1037                                            ascending: YES] autorelease];
1038
1039    NSArray * descriptors;
1040    if ([fSortType isEqualToString: @"Name"])
1041        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1042    else if ([fSortType isEqualToString: @"State"])
1043    {
1044        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1045                                                @"stateSortKey" ascending: NO] autorelease],
1046                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1047                                            @"progressSortKey" ascending: NO] autorelease];
1048       
1049        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
1050                                                            nameDescriptor, orderDescriptor, nil];
1051    }
1052    else if ([fSortType isEqualToString: @"Progress"])
1053    {
1054        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1055                                            @"progressSortKey" ascending: YES] autorelease];
1056       
1057        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
1058    }
1059    else if ([fSortType isEqualToString: @"Date"])
1060    {
1061        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"date" ascending: YES] autorelease];
1062   
1063        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1064    }
1065    else
1066        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1067
1068    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1069    [descriptors release];
1070   
1071    [fTableView reloadData];
1072}
1073
1074- (void) setSort: (id) sender
1075{
1076    //get checked items
1077    NSMenuItem * prevSortItem, * prevSortActionItem;
1078    if ([fSortType isEqualToString: @"Name"])
1079    {
1080        prevSortItem = fNameSortItem;
1081        prevSortActionItem = fNameSortActionItem;
1082    }
1083    else if ([fSortType isEqualToString: @"State"])
1084    {
1085        prevSortItem = fStateSortItem;
1086        prevSortActionItem = fStateSortActionItem;
1087    }
1088    else if ([fSortType isEqualToString: @"Progress"])
1089    {
1090        prevSortItem = fProgressSortItem;
1091        prevSortActionItem = fProgressSortActionItem;
1092    }
1093    else if ([fSortType isEqualToString: @"Date"])
1094    {
1095        prevSortItem = fDateSortItem;
1096        prevSortActionItem = fDateSortActionItem;
1097    }
1098    else
1099    {
1100        prevSortItem = fOrderSortItem;
1101        prevSortActionItem = fOrderSortActionItem;
1102    }
1103   
1104    if (sender != prevSortItem && sender != prevSortActionItem)
1105    {
1106        [fSortType release];
1107       
1108        //get new items to check
1109        NSMenuItem * currentSortItem, * currentSortActionItem;
1110        if (sender == fNameSortItem || sender == fNameSortActionItem)
1111        {
1112            currentSortItem = fNameSortItem;
1113            currentSortActionItem = fNameSortActionItem;
1114            fSortType = [[NSString alloc] initWithString: @"Name"];
1115        }
1116        else if (sender == fStateSortItem || sender == fStateSortActionItem)
1117        {
1118            currentSortItem = fStateSortItem;
1119            currentSortActionItem = fStateSortActionItem;
1120            fSortType = [[NSString alloc] initWithString: @"State"];
1121        }
1122        else if (sender == fProgressSortItem || sender == fProgressSortActionItem)
1123        {
1124            currentSortItem = fProgressSortItem;
1125            currentSortActionItem = fProgressSortActionItem;
1126            fSortType = [[NSString alloc] initWithString: @"Progress"];
1127        }
1128        else if (sender == fDateSortItem || sender == fDateSortActionItem)
1129        {
1130            currentSortItem = fDateSortItem;
1131            currentSortActionItem = fDateSortActionItem;
1132            fSortType = [[NSString alloc] initWithString: @"Date"];
1133        }
1134        else
1135        {
1136            currentSortItem = fOrderSortItem;
1137            currentSortActionItem = fOrderSortActionItem;
1138            fSortType = [[NSString alloc] initWithString: @"Order"];
1139        }
1140   
1141        [prevSortItem setState: NSOffState];
1142        [prevSortActionItem setState: NSOffState];
1143        [currentSortItem setState: NSOnState];
1144        [currentSortActionItem setState: NSOnState];
1145       
1146        [fDefaults setObject: fSortType forKey: @"Sort"];
1147    }
1148
1149    [self sortTorrents];
1150}
1151
1152- (void) applyFilter: (id) sender
1153{
1154    //remember selected rows if needed
1155    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1156                ? [self torrentsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1157
1158    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1159
1160    BOOL filtering = YES;
1161    if ([fFilterType isEqualToString: @"Pause"])
1162    {
1163        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1164        Torrent * torrent;
1165        while ((torrent = [enumerator nextObject]))
1166            if (![torrent isActive])
1167                [tempTorrents addObject: torrent];
1168    }
1169    else if ([fFilterType isEqualToString: @"Seed"])
1170    {
1171        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1172        Torrent * torrent;
1173        while ((torrent = [enumerator nextObject]))
1174            if ([torrent isActive] && [torrent progress] >= 1.0)
1175                [tempTorrents addObject: torrent];
1176    }
1177    else if ([fFilterType isEqualToString: @"Download"])
1178    {
1179        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1180        Torrent * torrent;
1181        while ((torrent = [enumerator nextObject]))
1182            if ([torrent isActive] && [torrent progress] < 1.0)
1183                [tempTorrents addObject: torrent];
1184    }
1185    else
1186    {
1187        filtering = NO;
1188        [tempTorrents setArray: fTorrents];
1189    }
1190   
1191    NSString * searchString = [fSearchFilterField stringValue];
1192    if ([searchString length] > 0)
1193    {
1194        filtering = YES;
1195       
1196        int i;
1197        for (i = [tempTorrents count] - 1; i >= 0; i--)
1198            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1199                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1200                [tempTorrents removeObjectAtIndex: i];
1201    }
1202   
1203    [fDisplayedTorrents setArray: tempTorrents];
1204    [tempTorrents release];
1205   
1206    [self sortTorrentsIgnoreSelected];
1207   
1208    //set selected rows if needed
1209    if (selectedTorrents)
1210    {
1211        Torrent * torrent;
1212        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1213        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1214        unsigned index;
1215        while ((torrent = [enumerator nextObject]))
1216            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1217                [indexSet addIndex: index];
1218       
1219        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1220        [indexSet release];
1221    }
1222   
1223    //set status bar torrent count text
1224    NSMutableString * totalTorrentsString = [NSMutableString stringWithString: @""];
1225    if (filtering)
1226        [totalTorrentsString appendFormat: @"%d/", [fDisplayedTorrents count]];
1227   
1228    int totalCount = [fTorrents count];
1229    [totalTorrentsString appendFormat: @"%d Transfer%s", totalCount, totalCount == 1 ? "" : "s"];
1230   
1231    [fTotalTorrentsField setStringValue: totalTorrentsString];
1232
1233    [self setWindowSizeToFit];
1234}
1235
1236//resets filter and sorts torrents
1237- (void) setFilter: (id) sender
1238{
1239    BarButton * prevFilterButton;
1240    if ([fFilterType isEqualToString: @"Pause"])
1241        prevFilterButton = fPauseFilterButton;
1242    else if ([fFilterType isEqualToString: @"Seed"])
1243        prevFilterButton = fSeedFilterButton;
1244    else if ([fFilterType isEqualToString: @"Download"])
1245        prevFilterButton = fDownloadFilterButton;
1246    else
1247        prevFilterButton = fNoFilterButton;
1248   
1249    if (sender != prevFilterButton)
1250    {
1251        [prevFilterButton setEnabled: NO];
1252        [sender setEnabled: YES];
1253
1254        [fFilterType release];
1255        if (sender == fDownloadFilterButton)
1256            fFilterType = [[NSString alloc] initWithString: @"Download"];
1257        else if (sender == fPauseFilterButton)
1258            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1259        else if (sender == fSeedFilterButton)
1260            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1261        else
1262            fFilterType = [[NSString alloc] initWithString: @"None"];
1263
1264        [fDefaults setObject: fFilterType forKey: @"Filter"];
1265    }
1266
1267    [self applyFilter: nil];
1268}
1269
1270- (void) switchFilter: (id) sender
1271{
1272    NSButton * button;
1273    if ([fFilterType isEqualToString: @"None"])
1274        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1275    else if ([fFilterType isEqualToString: @"Download"])
1276        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1277    else if ([fFilterType isEqualToString: @"Seed"])
1278        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1279    else if ([fFilterType isEqualToString: @"Pause"])
1280        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1281    else
1282        button = fNoFilterButton;
1283   
1284    [self setFilter: button];
1285}
1286
1287- (void) toggleSpeedLimit: (id) sender
1288{
1289    fSpeedLimitEnabled = !fSpeedLimitEnabled;
1290    int state = fSpeedLimitEnabled ? NSOnState : NSOffState;
1291
1292    [fSpeedLimitItem setState: state];
1293    [fSpeedLimitDockItem setState: state];
1294   
1295    [fSpeedLimitButton setImage: !fSpeedLimitEnabled ? fSpeedLimitNormalImage
1296        : ([NSColor currentControlTint] == NSBlueControlTint ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage)];
1297   
1298    [fPrefsController enableSpeedLimit: fSpeedLimitEnabled];
1299}
1300
1301- (void) autoSpeedLimitChange: (NSNotification *) notification
1302{
1303    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1304        return;
1305 
1306    int onHour = [fDefaults integerForKey: @"SpeedLimitAutoOnHour"],
1307        offHour = [fDefaults integerForKey: @"SpeedLimitAutoOffHour"];
1308   
1309    //check if should be on if within range
1310    BOOL shouldBeOn;
1311    int hour = [[NSCalendarDate calendarDate] hourOfDay];
1312    if (onHour < offHour)
1313        shouldBeOn = hour >= onHour && hour < offHour;
1314    else
1315        shouldBeOn = hour < offHour || hour >= onHour;
1316   
1317    if (fSpeedLimitEnabled != shouldBeOn)
1318        [self toggleSpeedLimit: nil];
1319}
1320
1321- (void) autoSpeedLimit: (NSTimer *) timer
1322{
1323    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
1324        return;
1325 
1326    //toggle if within first few seconds of hour
1327    NSCalendarDate * currentDate = [NSCalendarDate calendarDate];
1328    if ([currentDate minuteOfHour] == 0 && [currentDate secondOfMinute] < AUTO_SPEED_LIMIT_SECONDS
1329            && [currentDate hourOfDay] == (fSpeedLimitEnabled ? [fDefaults integerForKey: @"SpeedLimitAutoOffHour"]
1330                                            : [fDefaults integerForKey: @"SpeedLimitAutoOnHour"]))
1331    {
1332        [self toggleSpeedLimit: nil];
1333       
1334        [GrowlApplicationBridge notifyWithTitle: [@"Speed Limit Auto " stringByAppendingString:
1335            fSpeedLimitEnabled ? @"Enabled" : @"Disabled"] description: @"Bandwidth settings changed"
1336            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
1337    }
1338}
1339
1340- (void) setLimitGlobalEnabled: (id) sender
1341{
1342    [fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
1343        type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem) ? @"Upload" : @"Download"];
1344}
1345
1346- (void) setQuickLimitGlobal: (id) sender
1347{
1348    [fPrefsController setQuickLimit: [[sender title] intValue]
1349        type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
1350}
1351
1352- (void) limitGlobalChange: (NSNotification *) notification
1353{
1354    NSDictionary * dict = [notification object];
1355   
1356    NSMenuItem * limitItem, * noLimitItem;
1357    if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
1358    {
1359        limitItem = fUploadLimitItem;
1360        noLimitItem = fUploadNoLimitItem;
1361    }
1362    else
1363    {
1364        limitItem = fDownloadLimitItem;
1365        noLimitItem = fDownloadNoLimitItem;
1366    }
1367   
1368    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1369    [limitItem setState: enable ? NSOnState : NSOffState];
1370    [noLimitItem setState: !enable ? NSOnState : NSOffState];
1371   
1372    [limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
1373                            [[dict objectForKey: @"Limit"] intValue]]];
1374
1375    [dict release];
1376}
1377
1378- (void) setRatioGlobalEnabled: (id) sender
1379{
1380    [fPrefsController setRatioEnabled: sender == fRatioSetItem];
1381}
1382
1383- (void) setQuickRatioGlobal: (id) sender
1384{
1385    [fPrefsController setQuickRatio: [[sender title] floatValue]];
1386}
1387
1388- (void) ratioGlobalChange: (NSNotification *) notification
1389{
1390    NSDictionary * dict = [notification object];
1391   
1392    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1393    [fRatioSetItem setState: enable ? NSOnState : NSOffState];
1394    [fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
1395   
1396    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
1397                            [[dict objectForKey: @"Ratio"] floatValue]]];
1398
1399    [dict release];
1400}
1401
1402- (void) checkWaitingForStopped: (NSNotification *) notification
1403{
1404    [self checkToStartWaiting: [notification object]];
1405   
1406    [self updateUI: nil];
1407    [self applyFilter: nil];
1408    [self updateTorrentHistory];
1409}
1410
1411- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1412{
1413    //don't try to start a transfer if there should be none waiting
1414    if (![fDefaults boolForKey: @"Queue"])
1415        return;
1416
1417    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1418   
1419    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1420    Torrent * torrent, * torrentToStart = nil;
1421    while ((torrent = [enumerator nextObject]))
1422    {
1423        //ignore the torrent just stopped
1424        if (torrent == finishedTorrent)
1425            continue;
1426   
1427        if ([torrent isActive])
1428        {
1429            if (![torrent isSeeding] && ![torrent isError])
1430            {
1431                desiredActive--;
1432                if (desiredActive <= 0)
1433                    return;
1434            }
1435        }
1436        else
1437        {
1438            //use as next if it is waiting to start and either no previous or order value is lower
1439            if ([torrent waitingToStart] && (!torrentToStart
1440                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1441                torrentToStart = torrent;
1442        }
1443    }
1444   
1445    //since it hasn't returned, the queue amount has not been met
1446    if (torrentToStart)
1447    {
1448        [torrentToStart startTransfer];
1449       
1450        [self updateUI: nil];
1451        [self applyFilter: nil];
1452        [self updateTorrentHistory];
1453    }
1454}
1455
1456- (void) torrentStartSettingChange: (NSNotification *) notification
1457{
1458    [self attemptToStartMultipleAuto: [notification object]];
1459
1460    [self updateUI: nil];
1461    [self applyFilter: nil];
1462    [self updateTorrentHistory];
1463}
1464
1465- (void) globalStartSettingChange: (NSNotification *) notification
1466{
1467    [self attemptToStartMultipleAuto: fTorrents];
1468   
1469    [self updateUI: nil];
1470    [self applyFilter: nil];
1471    [self updateTorrentHistory];
1472}
1473
1474- (void) torrentStoppedForRatio: (NSNotification *) notification
1475{
1476    [self applyFilter: nil];
1477    [fInfoController updateInfoStats];
1478    [fInfoController updateInfoSettings];
1479   
1480    if ([fDefaults boolForKey: @"PlaySeedingSound"])
1481    {
1482        NSSound * sound;
1483        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1484            [sound play];
1485    }
1486   
1487    [GrowlApplicationBridge notifyWithTitle: @"Seeding Complete" description: [[notification object] name]
1488        notificationName: GROWL_SEEDING_COMPLETE iconData: nil priority: 0 isSticky: NO clickContext: nil];
1489}
1490
1491- (void) attemptToStartAuto: (Torrent *) torrent
1492{
1493    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1494}
1495
1496//will try to start, taking into consideration the start preference
1497- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1498{
1499    if (![fDefaults boolForKey: @"Queue"])
1500    {
1501        NSEnumerator * enumerator = [torrents objectEnumerator];
1502        Torrent * torrent;
1503        while ((torrent = [enumerator nextObject]))
1504            if ([torrent waitingToStart])
1505                [torrent startTransfer];
1506       
1507        return;
1508    }
1509   
1510    //determine the number of downloads needed to start
1511    int desiredActive = [fDefaults integerForKey: @"QueueDownloadNumber"];
1512           
1513    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1514    Torrent * torrent;
1515    while ((torrent = [enumerator nextObject]))
1516        if ([torrent isActive] && ![torrent isSeeding] && ![torrent isError])
1517        {
1518            desiredActive--;
1519            if (desiredActive <= 0)
1520                break;
1521        }
1522   
1523    //sort torrents by order value
1524    NSArray * sortedTorrents;
1525    if ([torrents count] > 1 && desiredActive > 0)
1526    {
1527        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1528                                                    @"orderValue" ascending: YES] autorelease];
1529        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1530       
1531        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1532        [descriptors release];
1533    }
1534    else
1535        sortedTorrents = torrents;
1536
1537    enumerator = [sortedTorrents objectEnumerator];
1538    while ((torrent = [enumerator nextObject]))
1539    {
1540        if ([torrent waitingToStart])
1541        {
1542            if ([torrent progress] >= 1.0)
1543                [torrent startTransfer];
1544            else if (desiredActive > 0)
1545            {
1546                [torrent startTransfer];
1547                desiredActive--;
1548            }
1549            else
1550                continue;
1551           
1552            [torrent update];
1553        }
1554    }
1555}
1556
1557-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
1558{
1559    if ([notification isEqualToString: UKFileWatcherWriteNotification])
1560        [self checkAutoImportDirectory];
1561}
1562
1563- (void) changeAutoImport
1564{
1565    [fAutoImportedNames removeAllObjects];
1566   
1567    if ([fDefaults boolForKey: @"AutoImport"])
1568        [self checkAutoImportDirectory];
1569}
1570
1571- (void) checkAutoImportDirectory
1572{
1573    if (![fDefaults boolForKey: @"AutoImport"])
1574        return;
1575       
1576    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1577   
1578    NSArray * importedNames;
1579    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
1580        return;
1581   
1582    //only import those that have not been imported yet
1583    NSMutableArray * newNames = [importedNames mutableCopy];
1584    [newNames removeObjectsInArray: fAutoImportedNames];
1585    [fAutoImportedNames addObjectsFromArray: newNames];
1586   
1587    NSEnumerator * enumerator = [newNames objectEnumerator];
1588    NSString * file;
1589    unsigned oldCount;
1590    while ((file = [enumerator nextObject]))
1591    {
1592        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1593        {
1594            oldCount = [fTorrents count];
1595            [self openFiles: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1596           
1597            //import only actually happened if the torrent array is larger
1598            if (oldCount < [fTorrents count])
1599                [GrowlApplicationBridge notifyWithTitle: @"Torrent File Auto Added" description: file
1600                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
1601        }
1602    }
1603   
1604    [newNames release];
1605}
1606
1607- (int) numberOfRowsInTableView: (NSTableView *) t
1608{
1609    return [fDisplayedTorrents count];
1610}
1611
1612- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
1613{
1614    return [[fDisplayedTorrents objectAtIndex: row] infoForCurrentView];
1615}
1616
1617- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1618    toPasteboard: (NSPasteboard *) pasteboard
1619{
1620    //only allow reordering of rows if sorting by order with no filter
1621    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1622            && [[fSearchFilterField stringValue] length] == 0)
1623    {
1624        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1625        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1626                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1627        return YES;
1628    }
1629    return NO;
1630}
1631
1632- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1633    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1634{
1635    NSPasteboard * pasteboard = [info draggingPasteboard];
1636    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1637    {
1638        //check if any files to add have "torrent" as an extension
1639        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1640        NSString * file;
1641        while ((file = [enumerator nextObject]))
1642            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1643            {
1644                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1645                return NSDragOperationGeneric;
1646            }
1647    }
1648    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1649    {
1650        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1651        return NSDragOperationGeneric;
1652    }
1653    else
1654        return NSDragOperationNone;
1655}
1656
1657- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1658    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1659{
1660    NSPasteboard * pasteboard = [info draggingPasteboard];
1661    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1662    {
1663        //create an array of files with the "torrent" extension
1664        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1665        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1666        NSString * file;
1667        while ((file = [enumerator nextObject]))
1668            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1669                [filesToOpen addObject: file];
1670   
1671        [self application: NSApp openFiles: filesToOpen];
1672        [filesToOpen release];
1673    }
1674    else
1675    {
1676        //remember selected rows if needed
1677        NSArray * selectedTorrents = nil;
1678        int numSelected = [fTableView numberOfSelectedRows];
1679        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1680            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1681   
1682        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1683                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1684       
1685        //move torrent in array
1686        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1687        [fDisplayedTorrents removeObjectsInArray: movingTorrents];
1688       
1689        //determine the insertion index now that transfers to move have been removed
1690        int i, decrease = 0;
1691        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1692            decrease++;
1693       
1694        //insert objects at new location
1695        for (i = 0; i < [movingTorrents count]; i++)
1696            [fDisplayedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1697       
1698        [movingTorrents release];
1699       
1700        //redo order values
1701        int low = [indexes firstIndex], high = [indexes lastIndex];
1702        if (newRow < low)
1703            low = newRow;
1704        else if (newRow > high + 1)
1705            high = newRow - 1;
1706        else;
1707       
1708        for (i = low; i <= high; i++)
1709            [[fDisplayedTorrents objectAtIndex: i] setOrderValue: i];
1710       
1711        [fTableView reloadData];
1712       
1713        //set selected rows if needed
1714        if (selectedTorrents)
1715        {
1716            Torrent * torrent;
1717            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1718            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1719            while ((torrent = [enumerator nextObject]))
1720                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1721           
1722            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1723            [indexSet release];
1724        }
1725    }
1726   
1727    return YES;
1728}
1729
1730- (void) tableViewSelectionDidChange: (NSNotification *) notification
1731{
1732    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1733}
1734
1735- (void) toggleSmallView: (id) sender
1736{
1737    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
1738   
1739    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1740    [fSmallViewItem setState: makeSmall];
1741   
1742    [fDefaults setBool: makeSmall forKey: @"SmallView"];
1743   
1744    //window min height
1745    NSSize contentMinSize = [fWindow contentMinSize],
1746            contentSize = [[fWindow contentView] frame].size;
1747    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1748                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1749    [fWindow setContentMinSize: contentMinSize];
1750   
1751    //resize for larger min height if not set to auto size
1752    if (![fDefaults boolForKey: @"AutoSize"])
1753    {
1754        if (!makeSmall && contentSize.height < contentMinSize.height)
1755        {
1756            NSRect frame = [fWindow frame];
1757            float heightChange = contentMinSize.height - contentSize.height;
1758            frame.size.height += heightChange;
1759            frame.origin.y -= heightChange;
1760           
1761            [fWindow setFrame: frame display: YES];
1762            [fTableView reloadData];
1763        }
1764    }
1765    else
1766        [self setWindowSizeToFit];
1767}
1768
1769- (void) toggleStatusBar: (id) sender
1770{
1771    [self showStatusBar: [fStatusBar isHidden] animate: YES];
1772    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
1773}
1774
1775- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1776{
1777    if (show != [fStatusBar isHidden])
1778        return;
1779
1780    if (show)
1781        [fStatusBar setHidden: NO];
1782
1783    NSRect frame = [fWindow frame];
1784    float heightChange = [fStatusBar frame].size.height;
1785    if (!show)
1786        heightChange *= -1;
1787   
1788    //allow bar to show even if not enough room
1789    if (show && ![fDefaults boolForKey: @"AutoSize"])
1790    {
1791        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1792        if (frame.size.height > maxHeight)
1793        {
1794            float change = maxHeight - frame.size.height;
1795            frame.size.height += change;
1796            frame.origin.y -= change;
1797           
1798            [fWindow setFrame: frame display: NO animate: NO];
1799        }
1800    }
1801
1802    frame.size.height += heightChange;
1803    frame.origin.y -= heightChange;
1804   
1805    [self updateUI: nil];
1806   
1807    //set views to not autoresize
1808    unsigned int statsMask = [fStatusBar autoresizingMask];
1809    unsigned int filterMask = [fFilterBar autoresizingMask];
1810    unsigned int scrollMask = [fScrollView autoresizingMask];
1811    [fStatusBar setAutoresizingMask: 0];
1812    [fFilterBar setAutoresizingMask: 0];
1813    [fScrollView setAutoresizingMask: 0];
1814   
1815    [fWindow setFrame: frame display: YES animate: animate];
1816   
1817    //re-enable autoresize
1818    [fStatusBar setAutoresizingMask: statsMask];
1819    [fFilterBar setAutoresizingMask: filterMask];
1820    [fScrollView setAutoresizingMask: scrollMask];
1821   
1822    //change min size
1823    NSSize minSize = [fWindow contentMinSize];
1824    minSize.height += heightChange;
1825    [fWindow setContentMinSize: minSize];
1826   
1827    if (!show)
1828        [fStatusBar setHidden: YES];
1829}
1830
1831- (void) toggleFilterBar: (id) sender
1832{
1833    //disable filtering when hiding
1834    if (![fFilterBar isHidden])
1835    {
1836        [fSearchFilterField setStringValue: @""];
1837        [self setFilter: fNoFilterButton];
1838    }
1839
1840    [self showFilterBar: [fFilterBar isHidden] animate: YES];
1841    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
1842}
1843
1844- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1845{
1846    if (show != [fFilterBar isHidden])
1847        return;
1848
1849    if (show)
1850        [fFilterBar setHidden: NO];
1851
1852    NSRect frame = [fWindow frame];
1853    float heightChange = [fFilterBar frame].size.height;
1854    if (!show)
1855        heightChange *= -1;
1856   
1857    //allow bar to show even if not enough room
1858    if (show && ![fDefaults boolForKey: @"AutoSize"])
1859    {
1860        float maxHeight = [[fWindow screen] visibleFrame].size.height - heightChange;
1861        if (frame.size.height > maxHeight)
1862        {
1863            float change = maxHeight - frame.size.height;
1864            frame.size.height += change;
1865            frame.origin.y -= change;
1866           
1867            [fWindow setFrame: frame display: NO animate: NO];
1868        }
1869    }
1870
1871    frame.size.height += heightChange;
1872    frame.origin.y -= heightChange;
1873   
1874    //set views to not autoresize
1875    unsigned int filterMask = [fFilterBar autoresizingMask];
1876    unsigned int scrollMask = [fScrollView autoresizingMask];
1877    [fFilterBar setAutoresizingMask: 0];
1878    [fScrollView setAutoresizingMask: 0];
1879   
1880    [fWindow setFrame: frame display: YES animate: animate];
1881   
1882    //re-enable autoresize
1883    [fFilterBar setAutoresizingMask: filterMask];
1884    [fScrollView setAutoresizingMask: scrollMask];
1885   
1886    //change min size
1887    NSSize minSize = [fWindow contentMinSize];
1888    minSize.height += heightChange;
1889    [fWindow setContentMinSize: minSize];
1890   
1891    if (!show)
1892    {
1893        [fFilterBar setHidden: YES];
1894        [fWindow makeFirstResponder: fTableView];
1895    }
1896}
1897
1898- (void) toggleAdvancedBar: (id) sender
1899{
1900    int state = ![fAdvancedBarItem state];
1901    [fAdvancedBarItem setState: state];
1902    [fDefaults setBool: state forKey: @"UseAdvancedBar"];
1903   
1904    [fTableView display];
1905}
1906
1907- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1908    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1909{
1910    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1911
1912    if ([ident isEqualToString: TOOLBAR_OPEN])
1913    {
1914        [item setLabel: @"Open"];
1915        [item setPaletteLabel: @"Open Torrent Files"];
1916        [item setToolTip: @"Open torrent files"];
1917        [item setImage: [NSImage imageNamed: @"Open.png"]];
1918        [item setTarget: self];
1919        [item setAction: @selector(openShowSheet:)];
1920    }
1921    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1922    {
1923        [item setLabel: @"Remove"];
1924        [item setPaletteLabel: @"Remove Selected"];
1925        [item setToolTip: @"Remove selected transfers"];
1926        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1927        [item setTarget: self];
1928        [item setAction: @selector(removeNoDelete:)];
1929    }
1930    else if ([ident isEqualToString: TOOLBAR_INFO])
1931    {
1932        [item setLabel: @"Inspector"];
1933        [item setPaletteLabel: @"Toggle Inspector"];
1934        [item setToolTip: @"Toggle the torrent inspector"];
1935        [item setImage: [NSImage imageNamed: @"Info.png"]];
1936        [item setTarget: self];
1937        [item setAction: @selector(showInfo:)];
1938    }
1939    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1940    {
1941        [item setLabel: @"Pause All"];
1942        [item setPaletteLabel: [item label]];
1943        [item setToolTip: @"Pause all transfers"];
1944        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1945        [item setTarget: self];
1946        [item setAction: @selector(stopAllTorrents:)];
1947    }
1948    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1949    {
1950        [item setLabel: @"Resume All"];
1951        [item setPaletteLabel: [item label]];
1952        [item setToolTip: @"Resume all transfers"];
1953        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1954        [item setTarget: self];
1955        [item setAction: @selector(resumeAllTorrents:)];
1956    }
1957    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1958    {
1959        [item setLabel: @"Pause"];
1960        [item setPaletteLabel: @"Pause Selected"];
1961        [item setToolTip: @"Pause selected transfers"];
1962        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1963        [item setTarget: self];
1964        [item setAction: @selector(stopSelectedTorrents:)];
1965    }
1966    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1967    {
1968        [item setLabel: @"Resume"];
1969        [item setPaletteLabel: @"Resume Selected"];
1970        [item setToolTip: @"Resume selected transfers"];
1971        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1972        [item setTarget: self];
1973        [item setAction: @selector(resumeSelectedTorrents:)];
1974    }
1975    else if ([ident isEqualToString: TOOLBAR_FILTER])
1976    {
1977        [item setLabel: @"Filter"];
1978        [item setPaletteLabel: @"Toggle Filter"];
1979        [item setToolTip: @"Toggle the filter bar"];
1980        [item setImage: [NSImage imageNamed: @"Filter.png"]];
1981        [item setTarget: self];
1982        [item setAction: @selector(toggleFilterBar:)];
1983    }
1984    else
1985    {
1986        [item release];
1987        return nil;
1988    }
1989
1990    return item;
1991}
1992
1993- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1994{
1995    return [NSArray arrayWithObjects:
1996            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1997            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1998            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
1999            NSToolbarSeparatorItemIdentifier,
2000            NSToolbarSpaceItemIdentifier,
2001            NSToolbarFlexibleSpaceItemIdentifier,
2002            NSToolbarCustomizeToolbarItemIdentifier, nil];
2003}
2004
2005- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
2006{
2007    return [NSArray arrayWithObjects:
2008            TOOLBAR_OPEN, TOOLBAR_REMOVE,
2009            NSToolbarSeparatorItemIdentifier,
2010            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2011            NSToolbarFlexibleSpaceItemIdentifier,
2012            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2013}
2014
2015- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2016{
2017    NSString * ident = [toolbarItem itemIdentifier];
2018
2019    //enable remove item
2020    if ([ident isEqualToString: TOOLBAR_REMOVE])
2021        return [fTableView numberOfSelectedRows] > 0;
2022
2023    //enable pause all item
2024    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2025    {
2026        Torrent * torrent;
2027        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2028        while ((torrent = [enumerator nextObject]))
2029            if ([torrent isActive] || [torrent waitingToStart])
2030                return YES;
2031        return NO;
2032    }
2033
2034    //enable resume all item
2035    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2036    {
2037        Torrent * torrent;
2038        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2039        while ((torrent = [enumerator nextObject]))
2040            if ([torrent isPaused] && ![torrent waitingToStart])
2041                return YES;
2042        return NO;
2043    }
2044
2045    //enable pause item
2046    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2047    {
2048        Torrent * torrent;
2049        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2050        unsigned int i;
2051       
2052        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2053        {
2054            torrent = [fDisplayedTorrents objectAtIndex: i];
2055            if ([torrent isActive] || [torrent waitingToStart])
2056                return YES;
2057        }
2058        return NO;
2059    }
2060   
2061    //enable resume item
2062    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2063    {
2064        Torrent * torrent;
2065        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2066        unsigned int i;
2067       
2068        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2069        {
2070            torrent = [fDisplayedTorrents objectAtIndex: i];
2071            if ([torrent isPaused] && ![torrent waitingToStart])
2072                return YES;
2073        }
2074        return NO;
2075    }
2076
2077    return YES;
2078}
2079
2080- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2081{
2082    SEL action = [menuItem action];
2083
2084    //only enable some items if it is in a context menu or the window is useable
2085    BOOL canUseTable = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
2086
2087    //enable open items
2088    if (action == @selector(openShowSheet:))
2089        return [fWindow attachedSheet] == nil;
2090   
2091    //enable sort and advanced bar items
2092    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:) || action == @selector(toggleSmallView:))
2093        return [fWindow isVisible];
2094
2095    //enable show info
2096    if (action == @selector(showInfo:))
2097    {
2098        NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
2099        if (![[menuItem title] isEqualToString: title])
2100                [menuItem setTitle: title];
2101
2102        return YES;
2103    }
2104   
2105    //enable prev/next inspector tab
2106    if (action == @selector(setInfoTab:))
2107        return [[fInfoController window] isVisible];
2108   
2109    //enable toggle status bar
2110    if (action == @selector(toggleStatusBar:))
2111    {
2112        NSString * title = [fStatusBar isHidden] ? @"Show Status Bar" : @"Hide Status Bar";
2113        if (![[menuItem title] isEqualToString: title])
2114            [menuItem setTitle: title];
2115
2116        return [fWindow isVisible];
2117    }
2118   
2119    //enable toggle filter bar
2120    if (action == @selector(toggleFilterBar:))
2121    {
2122        NSString * title = [fFilterBar isHidden] ? @"Show Filter Bar" : @"Hide Filter Bar";
2123        if (![[menuItem title] isEqualToString: title])
2124            [menuItem setTitle: title];
2125
2126        return [fWindow isVisible];
2127    }
2128   
2129    //enable prev/next filter button
2130    if (action == @selector(switchFilter:))
2131        return [fWindow isVisible] && ![fFilterBar isHidden];
2132
2133    //enable reveal in finder
2134    if (action == @selector(revealFile:))
2135        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2136
2137    //enable remove items
2138    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
2139        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
2140    {
2141        BOOL warning = NO,
2142            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
2143            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
2144        Torrent * torrent;
2145        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2146        unsigned int i;
2147       
2148        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2149        {
2150            torrent = [fDisplayedTorrents objectAtIndex: i];
2151            if (!warning && [torrent isActive])
2152            {
2153                warning = onlyDownloading ? ![torrent isSeeding] : YES;
2154                if (warning && canDelete)
2155                    break;
2156            }
2157            if (!canDelete && [torrent publicTorrent])
2158            {
2159                canDelete = YES;
2160                if (warning)
2161                    break;
2162            }
2163        }
2164   
2165        //append or remove ellipsis when needed
2166        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2167        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2168        {
2169            if (![title hasSuffix: ellipsis])
2170                [menuItem setTitle: [title stringByAppendingEllipsis]];
2171        }
2172        else
2173        {
2174            if ([title hasSuffix: ellipsis])
2175                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2176        }
2177       
2178        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
2179    }
2180
2181    //enable pause all item
2182    if (action == @selector(stopAllTorrents:))
2183    {
2184        Torrent * torrent;
2185        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2186        while ((torrent = [enumerator nextObject]))
2187            if ([torrent isActive] || [torrent waitingToStart])
2188                return YES;
2189        return NO;
2190    }
2191   
2192    //enable resume all item
2193    if (action == @selector(resumeAllTorrents:))
2194    {
2195        Torrent * torrent;
2196        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2197        while ((torrent = [enumerator nextObject]))
2198            if ([torrent isPaused] && ![torrent waitingToStart])
2199                return YES;
2200        return NO;
2201    }
2202   
2203    //enable resume all waiting item
2204    if (action == @selector(resumeWaitingTorrents:))
2205    {
2206        if (![fDefaults boolForKey: @"Queue"])
2207            return NO;
2208   
2209        Torrent * torrent;
2210        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2211        while ((torrent = [enumerator nextObject]))
2212            if ([torrent waitingToStart])
2213                return YES;
2214        return NO;
2215    }
2216   
2217    //enable resume selected waiting item
2218    if (action == @selector(resumeSelectedTorrentsNoWait:))
2219    {
2220        if (![fDefaults boolForKey: @"Queue"])
2221            return NO;
2222   
2223        Torrent * torrent;
2224        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2225        unsigned int i;
2226       
2227        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2228        {
2229            torrent = [fDisplayedTorrents objectAtIndex: i];
2230            if ([torrent isPaused] && [torrent progress] < 1.0)
2231                return YES;
2232        }
2233        return NO;
2234    }
2235
2236    //enable pause item
2237    if (action == @selector(stopSelectedTorrents:))
2238    {
2239        if (!canUseTable)
2240            return NO;
2241   
2242        Torrent * torrent;
2243        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2244        unsigned int i;
2245       
2246        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2247        {
2248            torrent = [fDisplayedTorrents objectAtIndex: i];
2249            if ([torrent isActive] || [torrent waitingToStart])
2250                return YES;
2251        }
2252        return NO;
2253    }
2254   
2255    //enable resume item
2256    if (action == @selector(resumeSelectedTorrents:))
2257    {
2258        if (!canUseTable)
2259            return NO;
2260   
2261        Torrent * torrent;
2262        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2263        unsigned int i;
2264       
2265        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2266        {
2267            torrent = [fDisplayedTorrents objectAtIndex: i];
2268            if ([torrent isPaused] && ![torrent waitingToStart])
2269                return YES;
2270        }
2271        return NO;
2272    }
2273   
2274    //enable copy torrent file item
2275    if (action == @selector(copyTorrentFile:))
2276        return canUseTable && [fTableView numberOfSelectedRows] > 0;
2277
2278    return YES;
2279}
2280
2281- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2282{
2283    NSEnumerator * enumerator;
2284    Torrent * torrent;
2285    BOOL active;
2286
2287    switch (messageType)
2288    {
2289        case kIOMessageSystemWillSleep:
2290            //close all connections before going to sleep and remember we should resume when we wake up
2291            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2292
2293            //wait for running transfers to stop (5 second timeout)
2294            NSDate * start = [NSDate date];
2295            BOOL timeUp = NO;
2296           
2297            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2298            Torrent * torrent;
2299            while (!timeUp && (torrent = [enumerator nextObject]))
2300                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2301                {
2302                    usleep(100000);
2303                    [torrent update];
2304                }
2305
2306            IOAllowPowerChange(fRootPort, (long) messageArgument);
2307            break;
2308
2309        case kIOMessageCanSystemSleep:
2310            //pevent idle sleep unless all paused
2311            active = NO;
2312            enumerator = [fTorrents objectEnumerator];
2313            while ((torrent = [enumerator nextObject]))
2314                if ([torrent isActive])
2315                {
2316                    active = YES;
2317                    break;
2318                }
2319
2320            if (active)
2321                IOCancelPowerChange(fRootPort, (long) messageArgument);
2322            else
2323                IOAllowPowerChange(fRootPort, (long) messageArgument);
2324            break;
2325
2326        case kIOMessageSystemHasPoweredOn:
2327            //resume sleeping transfers after we wake up
2328            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2329            break;
2330    }
2331}
2332
2333- (void) resetDockBadge: (NSNotification *) notification
2334{
2335    float downloadRate, uploadRate;
2336    tr_torrentRates(fLib, & downloadRate, & uploadRate);
2337   
2338    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
2339}
2340
2341- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2342{
2343    //if auto size is enabled, the current frame shouldn't need to change
2344    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
2345   
2346    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2347    return frame;
2348}
2349
2350- (void) setWindowSizeToFit
2351{
2352    if ([fDefaults boolForKey: @"AutoSize"])
2353    {
2354        [fScrollView setHasVerticalScroller: NO];
2355        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
2356        [fScrollView setHasVerticalScroller: YES];
2357    }
2358}
2359
2360- (NSRect) sizedWindowFrame
2361{
2362    NSRect frame = [fWindow frame];
2363    float newHeight = frame.size.height - [fScrollView frame].size.height
2364        + [fDisplayedTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2365
2366    float minHeight = [fWindow minSize].height;
2367    if (newHeight < minHeight)
2368        newHeight = minHeight;
2369    else
2370    {
2371        float maxHeight = [[fWindow screen] visibleFrame].size.height;
2372        if ([fStatusBar isHidden])
2373            maxHeight -= [fStatusBar frame].size.height;
2374        if ([fFilterBar isHidden])
2375            maxHeight -= [fFilterBar frame].size.height;
2376       
2377        if (newHeight > maxHeight)
2378            newHeight = maxHeight;
2379    }
2380
2381    frame.origin.y -= (newHeight - frame.size.height);
2382    frame.size.height = newHeight;
2383    return frame;
2384}
2385
2386- (void) showMainWindow: (id) sender
2387{
2388    [fWindow makeKeyAndOrderFront: nil];
2389}
2390
2391- (void) windowDidBecomeKey: (NSNotification *) notification
2392{
2393    //reset dock badge for completed
2394    if (fCompleted > 0)
2395    {
2396        fCompleted = 0;
2397        [self resetDockBadge: nil];
2398    }
2399}
2400
2401- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2402{
2403    //only resize horizontally if autosize is enabled
2404    if ([fDefaults boolForKey: @"AutoSize"])
2405        proposedFrameSize.height = [fWindow frame].size.height;
2406    return proposedFrameSize;
2407}
2408
2409- (void) windowDidResize: (NSNotification *) notification
2410{
2411    //hide search filter if it overlaps filter buttons
2412    [fSearchFilterField setHidden: NSMaxX([fPauseFilterButton frame]) + 2.0 > [fSearchFilterField frame].origin.x];
2413}
2414
2415- (void) linkHomepage: (id) sender
2416{
2417    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2418}
2419
2420- (void) linkForums: (id) sender
2421{
2422    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2423}
2424
2425- (void) checkUpdate: (id) sender
2426{
2427    [fPrefsController checkUpdate];
2428}
2429
2430- (void) prepareForUpdate: (NSNotification *) notification
2431{
2432    fUpdateInProgress = YES;
2433}
2434
2435- (NSDictionary *) registrationDictionaryForGrowl
2436{
2437    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
2438                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
2439    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2440                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2441}
2442
2443@end
Note: See TracBrowser for help on using the repository browser.