source: trunk/macosx/Controller.m @ 852

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

Menu item to switch between filters.
Enable some menu items a little differently.

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