source: trunk/macosx/Controller.m @ 570

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

Don't filter after removing.

  • Property svn:keywords set to Date Rev Author Id
File size: 66.8 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 570 2006-07-13 11:18:16Z 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 = [[NSArray 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) changeSelected
862{
863    //remember selected rows if needed
864    NSArray * selectedTorrents = nil;
865    if (changeSelected)
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 release];
1299    fAutoImportedNames = [allFileNames retain];
1300   
1301    NSEnumerator * enumerator = [newFileNames objectEnumerator];
1302    NSString * file;
1303    unsigned oldCount;
1304    while ((file = [enumerator nextObject]))
1305        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1306        {
1307            oldCount = [fTorrents count];
1308            [self openFromSheet: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1309           
1310            //import only actually happened if the torrent array is larger
1311            if (oldCount < [fTorrents count])
1312                [self notifyGrowl: @"Torrent File Auto Added" message: [file stringByAppendingString:
1313                                                    @" added to Transmission"] identifier: @"Torrent Auto Added"];
1314        }
1315}
1316
1317- (void) autoImportChange: (NSNotification *) notification
1318{
1319    [fAutoImportedNames release];
1320    fAutoImportedNames = [[NSArray alloc] init];
1321   
1322    [self checkAutoImportDirectory: nil];
1323}
1324
1325- (int) numberOfRowsInTableView: (NSTableView *) t
1326{
1327    return [fFilteredTorrents count];
1328}
1329
1330- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
1331    forTableColumn: (NSTableColumn *) tableColumn row: (int) row
1332{
1333    [cell setTorrent: [fFilteredTorrents objectAtIndex: row]];
1334}
1335
1336- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1337    toPasteboard: (NSPasteboard *) pasteboard
1338{
1339    //only allow reordering of rows if sorting by order with no filter
1340    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"])
1341    {
1342        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1343        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1344                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1345        return YES;
1346    }
1347    return NO;
1348}
1349
1350- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1351    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1352{
1353    NSPasteboard * pasteboard = [info draggingPasteboard];
1354    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1355    {
1356        //check if any files to add have "torrent" as an extension
1357        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1358        NSString * file;
1359        while ((file = [enumerator nextObject]))
1360            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1361            {
1362                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1363                return NSDragOperationGeneric;
1364            }
1365    }
1366    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1367    {
1368        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1369        return NSDragOperationGeneric;
1370    }
1371    else;
1372   
1373    return NSDragOperationNone;
1374}
1375
1376- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1377    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1378{
1379    NSPasteboard * pasteboard = [info draggingPasteboard];
1380    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1381    {
1382        //create an array of files with the "torrent" extension
1383        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1384        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1385        NSString * file;
1386        while ((file = [enumerator nextObject]))
1387            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1388                [filesToOpen addObject: file];
1389   
1390        [self application: NSApp openFiles: filesToOpen];
1391        [filesToOpen release];
1392    }
1393    else
1394    {
1395        //remember selected rows if needed
1396        NSArray * selectedTorrents = nil;
1397        int numSelected = [fTableView numberOfSelectedRows];
1398        if (numSelected > 0 && numSelected < [fFilteredTorrents count])
1399            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1400   
1401        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1402                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1403       
1404        //move torrent in array
1405        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1406        [fFilteredTorrents removeObjectsInArray: movingTorrents];
1407       
1408        //determine the insertion index now that transfers to move have been removed
1409        int i, decrease = 0;
1410        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1411            decrease++;
1412       
1413        //insert objects at new location
1414        for (i = 0; i < [movingTorrents count]; i++)
1415            [fFilteredTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1416       
1417        [movingTorrents release];
1418       
1419        //redo order values
1420        int low = [indexes firstIndex], high = [indexes lastIndex];
1421        if (newRow < low)
1422            low = newRow;
1423        else if (newRow > high + 1)
1424            high = newRow - 1;
1425        else;
1426       
1427        for (i = low; i <= high; i++)
1428            [[fFilteredTorrents objectAtIndex: i] setOrderValue: i];
1429       
1430        [fTableView reloadData];
1431       
1432        //set selected rows if needed
1433        if (selectedTorrents)
1434        {
1435            Torrent * torrent;
1436            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1437            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1438            while ((torrent = [enumerator nextObject]))
1439                [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
1440           
1441            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1442            [indexSet release];
1443        }
1444    }
1445   
1446    return YES;
1447}
1448
1449- (void) tableViewSelectionDidChange: (NSNotification *) notification
1450{
1451    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1452}
1453
1454- (void) toggleSmallView: (id) sender
1455{
1456    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
1457   
1458    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1459    [fSmallViewItem setState: makeSmall];
1460   
1461    [fDefaults setBool: makeSmall forKey: @"SmallView"];
1462}
1463
1464- (void) toggleStatusBar: (id) sender
1465{
1466    [self showStatusBar: !fStatusBarVisible animate: YES];
1467    [fDefaults setBool: fStatusBarVisible forKey: @"StatusBar"];
1468}
1469
1470- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1471{
1472    if (show == fStatusBarVisible)
1473        return;
1474
1475    NSRect frame = [fWindow frame];
1476    float heightChange = [fStatusBar frame].size.height;
1477    if (!show)
1478        heightChange *= -1;
1479
1480    frame.size.height += heightChange;
1481    frame.origin.y -= heightChange;
1482       
1483    fStatusBarVisible = !fStatusBarVisible;
1484   
1485    [self updateUI: nil];
1486   
1487    //set views to not autoresize
1488    unsigned int statsMask = [fStatusBar autoresizingMask];
1489    unsigned int scrollMask = [fScrollView autoresizingMask];
1490    [fStatusBar setAutoresizingMask: 0];
1491    [fScrollView setAutoresizingMask: 0];
1492   
1493    [fWindow setFrame: frame display: YES animate: animate];
1494   
1495    //re-enable autoresize
1496    [fStatusBar setAutoresizingMask: statsMask];
1497    [fScrollView setAutoresizingMask: scrollMask];
1498   
1499    //change min size
1500    NSSize minSize = [fWindow contentMinSize];
1501    minSize.height += heightChange;
1502    [fWindow setContentMinSize: minSize];
1503}
1504
1505- (void) toggleAdvancedBar: (id) sender
1506{
1507    int state = ![fAdvancedBarItem state];
1508    [fAdvancedBarItem setState: state];
1509    [fDefaults setBool: state forKey: @"UseAdvancedBar"];
1510
1511    [fTableView display];
1512}
1513
1514- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1515    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1516{
1517    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1518
1519    if ([ident isEqualToString: TOOLBAR_OPEN])
1520    {
1521        [item setLabel: @"Open"];
1522        [item setPaletteLabel: @"Open Torrent Files"];
1523        [item setToolTip: @"Open torrent files"];
1524        [item setImage: [NSImage imageNamed: @"Open.png"]];
1525        [item setTarget: self];
1526        [item setAction: @selector(openShowSheet:)];
1527    }
1528    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1529    {
1530        [item setLabel: @"Remove"];
1531        [item setPaletteLabel: @"Remove Selected"];
1532        [item setToolTip: @"Remove selected transfers"];
1533        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1534        [item setTarget: self];
1535        [item setAction: @selector(removeNoDelete:)];
1536    }
1537    else if ([ident isEqualToString: TOOLBAR_INFO])
1538    {
1539        [item setLabel: @"Inspector"];
1540        [item setPaletteLabel: @"Show/Hide Inspector"];
1541        [item setToolTip: @"Display torrent inspector"];
1542        [item setImage: [NSImage imageNamed: @"Info.png"]];
1543        [item setTarget: self];
1544        [item setAction: @selector(showInfo:)];
1545    }
1546    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1547    {
1548        [item setLabel: @"Pause All"];
1549        [item setPaletteLabel: [item label]];
1550        [item setToolTip: @"Pause all transfers"];
1551        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1552        [item setTarget: self];
1553        [item setAction: @selector(stopAllTorrents:)];
1554    }
1555    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1556    {
1557        [item setLabel: @"Resume All"];
1558        [item setPaletteLabel: [item label]];
1559        [item setToolTip: @"Resume all transfers"];
1560        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1561        [item setTarget: self];
1562        [item setAction: @selector(resumeAllTorrents:)];
1563    }
1564    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1565    {
1566        [item setLabel: @"Pause"];
1567        [item setPaletteLabel: @"Pause Selected"];
1568        [item setToolTip: @"Pause selected transfers"];
1569        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1570        [item setTarget: self];
1571        [item setAction: @selector(stopSelectedTorrents:)];
1572    }
1573    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1574    {
1575        [item setLabel: @"Resume"];
1576        [item setPaletteLabel: @"Resume Selected"];
1577        [item setToolTip: @"Resume selected transfers"];
1578        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1579        [item setTarget: self];
1580        [item setAction: @selector(resumeSelectedTorrents:)];
1581    }
1582    else
1583    {
1584        [item release];
1585        return nil;
1586    }
1587
1588    return item;
1589}
1590
1591- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1592{
1593    return [NSArray arrayWithObjects:
1594            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1595            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1596            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_INFO,
1597            NSToolbarSeparatorItemIdentifier,
1598            NSToolbarSpaceItemIdentifier,
1599            NSToolbarFlexibleSpaceItemIdentifier,
1600            NSToolbarCustomizeToolbarItemIdentifier, nil];
1601}
1602
1603- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1604{
1605    return [NSArray arrayWithObjects:
1606            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1607            NSToolbarSeparatorItemIdentifier,
1608            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1609            NSToolbarFlexibleSpaceItemIdentifier,
1610            TOOLBAR_INFO, nil];
1611}
1612
1613- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1614{
1615    NSString * ident = [toolbarItem itemIdentifier];
1616
1617    //enable remove item
1618    if ([ident isEqualToString: TOOLBAR_REMOVE])
1619        return [fTableView numberOfSelectedRows] > 0;
1620
1621    //enable pause all item
1622    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1623    {
1624        Torrent * torrent;
1625        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1626        while ((torrent = [enumerator nextObject]))
1627            if ([torrent isActive])
1628                return YES;
1629        return NO;
1630    }
1631
1632    //enable resume all item
1633    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1634    {
1635        Torrent * torrent;
1636        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1637        while ((torrent = [enumerator nextObject]))
1638            if ([torrent isPaused])
1639                return YES;
1640        return NO;
1641    }
1642
1643    //enable pause item
1644    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1645    {
1646        Torrent * torrent;
1647        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1648        unsigned int i;
1649       
1650        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1651            if ([[fFilteredTorrents objectAtIndex: i] isActive])
1652                return YES;
1653        return NO;
1654    }
1655   
1656    //enable resume item
1657    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1658    {
1659        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1660        unsigned int i;
1661       
1662        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1663            if ([[fFilteredTorrents objectAtIndex: i] isPaused])
1664                return YES;
1665        return NO;
1666    }
1667
1668    return YES;
1669}
1670
1671- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1672{
1673    SEL action = [menuItem action];
1674
1675    //only enable some items if it is in a context menu or the window is useable
1676    BOOL canUseMenu = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
1677
1678    //enable show info
1679    if (action == @selector(showInfo:))
1680    {
1681        NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
1682        if (![[menuItem title] isEqualToString: title])
1683                [menuItem setTitle: title];
1684
1685        return YES;
1686    }
1687   
1688    //enable prev/next inspector tab
1689    if (action == @selector(setInfoTab:))
1690        return [[fInfoController window] isVisible];
1691   
1692    //enable toggle status bar
1693    if (action == @selector(toggleStatusBar:))
1694    {
1695        NSString * title = fStatusBarVisible ? @"Hide Status Bar" : @"Show Status Bar";
1696        if (![[menuItem title] isEqualToString: title])
1697                [menuItem setTitle: title];
1698
1699        return canUseMenu;
1700    }
1701
1702    //enable resume all item
1703    if (action == @selector(resumeAllTorrents:))
1704    {
1705        Torrent * torrent;
1706        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1707        while ((torrent = [enumerator nextObject]))
1708            if ([torrent isPaused])
1709                return YES;
1710        return NO;
1711    }
1712
1713    //enable pause all item
1714    if (action == @selector(stopAllTorrents:))
1715    {
1716        Torrent * torrent;
1717        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1718        while ((torrent = [enumerator nextObject]))
1719            if ([torrent isActive])
1720                return YES;
1721        return NO;
1722    }
1723
1724    //enable reveal in finder
1725    if (action == @selector(revealFile:))
1726        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1727
1728    //enable remove items
1729    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
1730        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
1731    {
1732        BOOL warning = NO,
1733            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
1734            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
1735        Torrent * torrent;
1736        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1737        unsigned int i;
1738       
1739        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1740        {
1741            torrent = [fFilteredTorrents objectAtIndex: i];
1742            if (!warning && [torrent isActive])
1743            {
1744                warning = onlyDownloading ? ![torrent isSeeding] : YES;
1745                if (warning && canDelete)
1746                    break;
1747            }
1748            if (!canDelete && [torrent publicTorrent])
1749            {
1750                canDelete = YES;
1751                if (warning)
1752                    break;
1753            }
1754        }
1755   
1756        //append or remove ellipsis when needed
1757        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
1758        if (warning && [fDefaults boolForKey: @"CheckRemove"])
1759        {
1760            if (![title hasSuffix: ellipsis])
1761                [menuItem setTitle: [title stringByAppendingEllipsis]];
1762        }
1763        else
1764        {
1765            if ([title hasSuffix: ellipsis])
1766                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
1767        }
1768       
1769        return canUseMenu && canDelete && [fTableView numberOfSelectedRows] > 0;
1770    }
1771
1772    //enable pause item
1773    if (action == @selector(stopSelectedTorrents:))
1774    {
1775        if (!canUseMenu)
1776            return NO;
1777   
1778        Torrent * torrent;
1779        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1780        unsigned int i;
1781       
1782        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1783        {
1784            torrent = [fFilteredTorrents objectAtIndex: i];
1785            if ([torrent isActive])
1786                return YES;
1787        }
1788        return NO;
1789    }
1790   
1791    //enable resume item
1792    if (action == @selector(resumeSelectedTorrents:))
1793    {
1794        if (!canUseMenu)
1795            return NO;
1796   
1797        Torrent * torrent;
1798        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1799        unsigned int i;
1800       
1801        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1802        {
1803            torrent = [fFilteredTorrents objectAtIndex: i];
1804            if ([torrent isPaused])
1805                return YES;
1806        }
1807        return NO;
1808    }
1809   
1810    //enable sort and advanced bar items
1811    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:)
1812            || action == @selector(toggleSmallView:))
1813        return canUseMenu;
1814   
1815    //enable copy torrent file item
1816    if (action == @selector(copyTorrentFile:))
1817    {
1818        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1819    }
1820
1821    return YES;
1822}
1823
1824- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
1825{
1826    NSEnumerator * enumerator;
1827    Torrent * torrent;
1828    BOOL active;
1829
1830    switch (messageType)
1831    {
1832        case kIOMessageSystemWillSleep:
1833            //close all connections before going to sleep and remember we should resume when we wake up
1834            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
1835
1836            //wait for running transfers to stop (5 second timeout)
1837            NSDate * start = [NSDate date];
1838            BOOL timeUp = NO;
1839           
1840            NSEnumerator * enumerator = [fTorrents objectEnumerator];
1841            Torrent * torrent;
1842            while (!timeUp && (torrent = [enumerator nextObject]))
1843                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
1844                {
1845                    usleep(100000);
1846                    [torrent update];
1847                }
1848
1849            IOAllowPowerChange(fRootPort, (long) messageArgument);
1850            break;
1851
1852        case kIOMessageCanSystemSleep:
1853            /* Prevent idle sleep unless all paused */
1854            active = NO;
1855            enumerator = [fTorrents objectEnumerator];
1856            while ((torrent = [enumerator nextObject]))
1857                if ([torrent isActive])
1858                {
1859                    active = YES;
1860                    break;
1861                }
1862
1863            if (active)
1864                IOCancelPowerChange(fRootPort, (long) messageArgument);
1865            else
1866                IOAllowPowerChange(fRootPort, (long) messageArgument);
1867            break;
1868
1869        case kIOMessageSystemHasPoweredOn:
1870            //resume sleeping transfers after we wake up
1871            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
1872            break;
1873    }
1874}
1875
1876- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
1877{
1878    NSRect windowRect = [fWindow frame];
1879    float newHeight = windowRect.size.height - [fScrollView frame].size.height
1880        + [fFilteredTorrents count] * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
1881
1882    float minHeight = [fWindow minSize].height;
1883    if (newHeight < minHeight)
1884        newHeight = minHeight;
1885
1886    windowRect.origin.y -= (newHeight - windowRect.size.height);
1887    windowRect.size.height = newHeight;
1888
1889    return windowRect;
1890}
1891
1892- (void) showMainWindow: (id) sender
1893{
1894    [fWindow makeKeyAndOrderFront: nil];
1895}
1896
1897- (void) windowDidBecomeKey: (NSNotification *) notification
1898{
1899    fCompleted = 0;
1900}
1901
1902- (void) linkHomepage: (id) sender
1903{
1904    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
1905}
1906
1907- (void) linkForums: (id) sender
1908{
1909    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
1910}
1911
1912- (void) notifyGrowl: (NSString *) title message: (NSString *) message identifier: (NSString *) ident
1913{
1914    if (!fHasGrowl)
1915        return;
1916
1917    NSString * growlScript = [NSString stringWithFormat:
1918        @"tell application \"System Events\"\n"
1919         "  if exists application process \"GrowlHelperApp\" then\n"
1920         "    tell application \"GrowlHelperApp\"\n "
1921         "      notify with name \"%@\""
1922         "        title \"%@\""
1923         "        description \"%@\""
1924         "        application name \"Transmission\"\n"
1925         "    end tell\n"
1926         "  end if\n"
1927         "end tell", ident, title, message];
1928   
1929    NSAppleScript * appleScript = [[NSAppleScript alloc] initWithSource: growlScript];
1930    NSDictionary * error;
1931    if (![appleScript executeAndReturnError: & error])
1932        NSLog(@"Growl notify failed");
1933    [appleScript release];
1934}
1935
1936- (void) growlRegister
1937{
1938    if (!fHasGrowl)
1939        return;
1940
1941    NSString * growlScript = @"tell application \"System Events\"\n"
1942         "  if exists application process \"GrowlHelperApp\" then\n"
1943         "    tell application \"GrowlHelperApp\"\n"
1944         "      register as application \"Transmission\" "
1945         "        all notifications {\"Download Complete\", \"Seeding Complete\", \"Torrent Auto Added\"}"
1946         "        default notifications {\"Download Complete\", \"Seeding Complete\", \"Torrent Auto Added\"}"
1947         "        icon of application \"Transmission\"\n"
1948         "    end tell\n"
1949         "  end if\n"
1950         "end tell";
1951
1952    NSAppleScript * appleScript = [[NSAppleScript alloc] initWithSource: growlScript];
1953    NSDictionary * error;
1954    if (![appleScript executeAndReturnError: & error])
1955        NSLog(@"Growl registration failed");
1956    [appleScript release];
1957}
1958
1959- (void) checkUpdate: (id) sender
1960{
1961    [fPrefsController checkUpdate];
1962}
1963
1964- (void) prepareForUpdate: (NSNotification *) notification
1965{
1966    fUpdateInProgress = YES;
1967}
1968
1969@end
Note: See TracBrowser for help on using the repository browser.