source: trunk/macosx/Controller.m @ 676

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

Updated help with better icon.

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