source: trunk/macosx/Controller.m @ 571

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

Use a mutable array for autoimport.

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