source: trunk/macosx/Controller.m @ 357

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

Get rid of unnecessary class by merging ellipsis code into StringAdditions?.

  • Property svn:keywords set to Date Rev Author Id
File size: 48.0 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 357 2006-06-14 20:08:51Z 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 WEBSITE_URL         @"http://transmission.m0k.org/"
44#define FORUM_URL           @"http://transmission.m0k.org/forum/"
45#define VERSION_PLIST_URL   @"http://transmission.m0k.org/version.plist"
46
47#define GROWL_PATH  @"/Library/PreferencePanes/Growl.prefPane/Contents/Resources/GrowlHelperApp.app"
48
49static void sleepCallBack( void * controller, io_service_t y,
50        natural_t messageType, void * messageArgument )
51{
52    Controller * c = controller;
53    [c sleepCallBack: messageType argument: messageArgument];
54}
55
56
57@implementation Controller
58
59- (id) init
60{
61    if ((self = [super init]))
62    {
63        fLib = tr_init();
64        fTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
65        fDefaults = [NSUserDefaults standardUserDefaults];
66        fInfoController = [[InfoWindowController alloc] initWithWindowNibName: @"InfoWindow"];
67        fPrefsController = [[PrefsController alloc] initWithWindowNibName: @"PrefsWindow"];
68    }
69    return self;
70}
71
72- (void) dealloc
73{
74    [[NSNotificationCenter defaultCenter] removeObserver: self];
75
76    [fTorrents release];
77    [fToolbar release];
78    [fInfoController release];
79    [fBadger release];
80    [fSortType release];
81   
82    tr_close( fLib );
83    [super dealloc];
84}
85
86- (void) awakeFromNib
87{
88    [fPrefsController setPrefsWindow: fLib];
89   
90    [fAdvancedBarItem setState: [fDefaults
91        boolForKey: @"UseAdvancedBar"] ? NSOnState : NSOffState];
92
93    fToolbar = [[NSToolbar alloc] initWithIdentifier: @"Transmission Toolbar"];
94    [fToolbar setDelegate: self];
95    [fToolbar setAllowsUserCustomization: YES];
96    [fToolbar setAutosavesConfiguration: YES];
97    [fWindow setToolbar: fToolbar];
98    [fWindow setDelegate: self];
99   
100    //window min height
101    NSSize contentMinSize = [fWindow contentMinSize];
102    contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
103                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
104    [fWindow setContentMinSize: contentMinSize];
105   
106    //set info keyboard shortcuts
107    unichar ch = NSRightArrowFunctionKey;
108    [fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
109    ch = NSLeftArrowFunctionKey;
110    [fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
111   
112    //set up status bar
113    NSRect statusBarFrame = [fStatusBar frame];
114    statusBarFrame.size.width = [fWindow frame].size.width;
115    [fStatusBar setFrame: statusBarFrame];
116   
117    NSView * contentView = [fWindow contentView];
118    [contentView addSubview: fStatusBar];
119    [fStatusBar setFrameOrigin: NSMakePoint(0, [fScrollView frame].origin.y
120                                                + [fScrollView frame].size.height)];
121    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
122   
123    [fActionButton setToolTip: @"Shortcuts for changing global settings."];
124
125    [fTableView setTorrents: fTorrents];
126    [[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell:
127        [[TorrentCell alloc] init]];
128
129    [fTableView registerForDraggedTypes:
130        [NSArray arrayWithObject: NSFilenamesPboardType]];
131
132    //Register for sleep notifications
133    IONotificationPortRef notify;
134    io_object_t anIterator;
135    if (fRootPort = IORegisterForSystemPower(self, & notify,
136                                sleepCallBack, & anIterator))
137    {
138        CFRunLoopAddSource( CFRunLoopGetCurrent(),
139                            IONotificationPortGetRunLoopSource( notify ),
140                            kCFRunLoopCommonModes );
141    }
142    else
143        NSLog( @"Could not IORegisterForSystemPower" );
144
145    //load torrents from history
146    Torrent * torrent;
147    NSDictionary * historyItem;
148    NSEnumerator * enumerator = [[fDefaults arrayForKey: @"History"] objectEnumerator];
149    while ((historyItem = [enumerator nextObject]))
150        if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
151        {
152            [fTorrents addObject: torrent];
153            [torrent release];
154        }
155   
156    [self torrentNumberChanged];
157   
158    //set sort
159    fSortType = [[fDefaults stringForKey: @"Sort"] retain];
160   
161    NSMenuItem * currentSortItem;
162    if ([fSortType isEqualToString: @"Name"])
163        currentSortItem = fNameSortItem;
164    else if ([fSortType isEqualToString: @"State"])
165        currentSortItem = fStateSortItem;
166    else if ([fSortType isEqualToString: @"Progress"])
167        currentSortItem = fProgressSortItem;
168    else
169        currentSortItem = fDateSortItem;
170    [currentSortItem setState: NSOnState];
171
172    //check and register Growl if it is installed for this user or all users
173    NSFileManager * manager = [NSFileManager defaultManager];
174    fHasGrowl = [manager fileExistsAtPath: GROWL_PATH]
175                || [manager fileExistsAtPath: [[NSString stringWithFormat: @"~%@",
176                GROWL_PATH] stringByExpandingTildeInPath]];
177    [self growlRegister: self];
178
179    //initialize badging
180    fBadger = [[Badger alloc] init];
181   
182    //set upload limit action button
183    [fUploadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
184                    [fDefaults integerForKey: @"UploadLimit"]]];
185    if ([fDefaults boolForKey: @"CheckUpload"])
186        [fUploadLimitItem setState: NSOnState];
187    else
188        [fUploadNoLimitItem setState: NSOnState];
189
190        //set download limit action menu
191    [fDownloadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
192                    [fDefaults integerForKey: @"DownloadLimit"]]];
193    if ([fDefaults boolForKey: @"CheckDownload"])
194        [fDownloadLimitItem setState: NSOnState];
195    else
196        [fDownloadNoLimitItem setState: NSOnState];
197   
198    //set ratio action menu
199    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
200                                [fDefaults floatForKey: @"RatioLimit"]]];
201    if ([fDefaults boolForKey: @"RatioCheck"])
202        [fRatioSetItem setState: NSOnState];
203    else
204        [fRatioNotSetItem setState: NSOnState];
205   
206    //observe notifications
207    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
208   
209    [nc addObserver: self selector: @selector(prepareForUpdate:)
210                    name: SUUpdaterWillRestartNotification object: nil];
211    fUpdateInProgress = NO;
212   
213    [nc addObserver: self selector: @selector(ratioSingleChange:)
214                    name: @"TorrentRatioChanged" object: nil];
215   
216    [nc addObserver: self selector: @selector(limitGlobalChange:)
217                    name: @"LimitGlobalChange" object: nil];
218   
219    [nc addObserver: self selector: @selector(ratioGlobalChange:)
220                    name: @"RatioGlobalChange" object: nil];
221
222    //timer to update the interface
223    fCompleted = 0;
224    [self updateUI: nil];
225    fTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
226        selector: @selector( updateUI: ) userInfo: nil repeats: YES];
227    [[NSRunLoop currentRunLoop] addTimer: fTimer
228        forMode: NSModalPanelRunLoopMode];
229    [[NSRunLoop currentRunLoop] addTimer: fTimer
230        forMode: NSEventTrackingRunLoopMode];
231   
232    [self sortTorrents];
233   
234    //show windows
235    [fWindow makeKeyAndOrderFront: nil];
236
237    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes:
238                                    [fTableView selectedRowIndexes]]];
239    if ([fDefaults boolForKey: @"InfoVisible"])
240        [self showInfo: nil];
241}
242
243- (BOOL) applicationShouldHandleReopen: (NSApplication *) app
244    hasVisibleWindows: (BOOL) flag
245{
246    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
247        [self showMainWindow: nil];
248    return NO;
249}
250
251- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
252{
253    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
254    {
255        int active = 0;
256        Torrent * torrent;
257        NSEnumerator * enumerator = [fTorrents objectEnumerator];
258        while ((torrent = [enumerator nextObject]))
259            if ([torrent isActive])
260                active++;
261
262        if (active > 0)
263        {
264            NSString * message = active == 1
265                ? @"There is an active transfer. Do you really want to quit?"
266                : [NSString stringWithFormat:
267                    @"There are %d active transfers. Do you really want to quit?",
268                    active];
269
270            NSBeginAlertSheet(@"Confirm Quit",
271                                @"Quit", @"Cancel", nil,
272                                fWindow, self,
273                                @selector(quitSheetDidEnd:returnCode:contextInfo:),
274                                nil, nil, message);
275            return NSTerminateLater;
276        }
277    }
278
279    return NSTerminateNow;
280}
281
282- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
283                        contextInfo: (void *) contextInfo
284{
285    [NSApp stopModal];
286    [NSApp replyToApplicationShouldTerminate:
287        (returnCode == NSAlertDefaultReturn)];
288}
289
290- (void) applicationWillTerminate: (NSNotification *) notification
291{
292    // Stop updating the interface
293    [fTimer invalidate];
294   
295    //save history
296    [self updateTorrentHistory];
297   
298    //remember window states
299    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
300    [fWindow close];
301    [self showStatusBar: NO animate: NO];
302   
303    //clear badge
304    [fBadger clearBadge];
305
306    //end quickly if updated version will open
307    if (fUpdateInProgress)
308        return;
309
310    //stop running torrents and wait for them to stop (5 seconds timeout)
311    [fTorrents makeObjectsPerformSelector: @selector(stop)];
312   
313    NSDate * start = [NSDate date];
314    Torrent * torrent;
315    while ([fTorrents count] > 0)
316    {
317        torrent = [fTorrents objectAtIndex: 0];
318        while( [[NSDate date] timeIntervalSinceDate: start] < 5 &&
319                ![torrent isPaused] )
320        {
321            usleep( 100000 );
322            [torrent update];
323        }
324        [fTorrents removeObject: torrent];
325    }
326}
327
328- (void) folderChoiceClosed: (NSOpenPanel *) s returnCode: (int) code
329    contextInfo: (Torrent *) torrent
330{
331    if (code == NSOKButton)
332    {
333        [torrent setDownloadFolder: [[s filenames] objectAtIndex: 0]];
334        if ([fDefaults boolForKey: @"AutoStartDownload"])
335            [torrent start];
336        [fTorrents addObject: torrent];
337       
338        [self torrentNumberChanged];
339    }
340   
341    [NSApp stopModal];
342}
343
344- (void) application: (NSApplication *) sender
345         openFiles: (NSArray *) filenames
346{
347    BOOL autoStart = [fDefaults boolForKey: @"AutoStartDownload"];
348   
349    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"],
350            * torrentPath;
351    Torrent * torrent;
352    NSEnumerator * enumerator = [filenames objectEnumerator];
353    while ((torrentPath = [enumerator nextObject]))
354    {
355        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
356            continue;
357
358        /* Add it to the "File > Open Recent" menu */
359        [[NSDocumentController sharedDocumentController]
360            noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
361
362        if ([downloadChoice isEqualToString: @"Ask"])
363        {
364            NSOpenPanel * panel = [NSOpenPanel openPanel];
365
366            [panel setPrompt: @"Select Download Folder"];
367            [panel setAllowsMultipleSelection: NO];
368            [panel setCanChooseFiles: NO];
369            [panel setCanChooseDirectories: YES];
370
371            [panel setMessage: [@"Select the download folder for "
372                    stringByAppendingString: [torrentPath lastPathComponent]]];
373
374            [panel beginSheetForDirectory: nil file: nil types: nil
375                modalForWindow: fWindow modalDelegate: self didEndSelector:
376                @selector( folderChoiceClosed:returnCode:contextInfo: )
377                contextInfo: torrent];
378            [NSApp runModalForWindow: panel];
379        }
380        else
381        {
382            NSString * folder = [downloadChoice isEqualToString: @"Constant"]
383                                ? [[fDefaults stringForKey: @"DownloadFolder"]
384                                        stringByExpandingTildeInPath]
385                                : [torrentPath stringByDeletingLastPathComponent];
386
387            [torrent setDownloadFolder: folder];
388            if (autoStart)
389                [torrent start];
390            [fTorrents addObject: torrent];
391        }
392       
393        [torrent release];
394    }
395
396    [self torrentNumberChanged];
397
398    [self updateUI: nil];
399    [self sortTorrents];
400    [self updateTorrentHistory];
401}
402
403- (NSArray *) torrentsAtIndexes: (NSIndexSet *) indexSet
404{
405    if ([fTorrents respondsToSelector: @selector(objectsAtIndexes:)])
406        return [fTorrents objectsAtIndexes: indexSet];
407    else
408    {
409        NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [indexSet count]];
410        unsigned int i;
411        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
412            [torrents addObject: [fTorrents objectAtIndex: i]];
413
414        return torrents;
415    }
416}
417
418- (void) torrentNumberChanged
419{
420    if (fStatusBarVisible)
421    {
422        int count = [fTorrents count];
423        [fTotalTorrentsField setStringValue: [NSString stringWithFormat:
424                    @"%d Transfer%s", count, count == 1 ? "" : "s"]];
425    }
426}
427
428- (void) advancedChanged: (id) sender
429{
430    [fAdvancedBarItem setState: ![fAdvancedBarItem state]];
431    [fDefaults setBool: [fAdvancedBarItem state] forKey: @"UseAdvancedBar"];
432
433    [fTableView display];
434}
435
436//called on by applescript
437- (void) open: (NSArray *) files
438{
439    [self performSelectorOnMainThread: @selector(cantFindAName:)
440                withObject: files waitUntilDone: NO];
441}
442
443- (void) openShowSheet: (id) sender
444{
445    NSOpenPanel * panel = [NSOpenPanel openPanel];
446    NSArray * fileTypes = [NSArray arrayWithObject: @"torrent"];
447
448    [panel setAllowsMultipleSelection: YES];
449    [panel setCanChooseFiles: YES];
450    [panel setCanChooseDirectories: NO];
451
452    [panel beginSheetForDirectory: nil file: nil types: fileTypes
453        modalForWindow: fWindow modalDelegate: self didEndSelector:
454        @selector( openSheetClosed:returnCode:contextInfo: )
455        contextInfo: nil];
456}
457
458- (void) cantFindAName: (NSArray *) filenames
459{
460    [self application: NSApp openFiles: filenames];
461}
462
463- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code
464    contextInfo: (void *) info
465{
466    if( code == NSOKButton )
467        [self performSelectorOnMainThread: @selector(cantFindAName:)
468                    withObject: [panel filenames] waitUntilDone: NO];
469}
470
471- (void) resumeTorrent: (id) sender
472{
473    [self resumeTorrentWithIndex: [fTableView selectedRowIndexes]];
474}
475
476- (void) resumeAllTorrents: (id) sender
477{
478    [self resumeTorrentWithIndex: [NSIndexSet indexSetWithIndexesInRange:
479                                    NSMakeRange(0, [fTorrents count])]];
480}
481
482- (void) resumeTorrentWithIndex: (NSIndexSet *) indexSet
483{
484    Torrent * torrent;
485    unsigned int i;
486    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
487    {
488        torrent = [fTorrents objectAtIndex: i];
489        [torrent start];
490    }
491   
492    [self updateUI: nil];
493    if ([fSortType isEqualToString: @"State"])
494        [self sortTorrents];
495    [self updateTorrentHistory];
496}
497
498- (void) stopTorrent: (id) sender
499{
500    [self stopTorrentWithIndex: [fTableView selectedRowIndexes]];
501}
502
503- (void) stopAllTorrents: (id) sender
504{
505    [self stopTorrentWithIndex: [NSIndexSet indexSetWithIndexesInRange:
506                                    NSMakeRange(0, [fTorrents count])]];
507}
508
509- (void) stopTorrentWithIndex: (NSIndexSet *) indexSet
510{
511    Torrent * torrent;
512    unsigned int i;
513    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
514    {
515        torrent = [fTorrents objectAtIndex: i];
516        [torrent stop];
517    }
518   
519    [self updateUI: nil];
520    if ([fSortType isEqualToString: @"State"])
521        [self sortTorrents];
522    [self updateTorrentHistory];
523}
524
525- (void) removeTorrentWithIndex: (NSIndexSet *) indexSet
526                     deleteData: (BOOL) deleteData
527{
528    NSArray * torrents = [[self torrentsAtIndexes: indexSet] retain];
529    int active = 0;
530
531    Torrent * torrent;
532    NSEnumerator * enumerator = [torrents objectEnumerator];
533    while ((torrent = [enumerator nextObject]))
534        if ([torrent isActive])
535            active++;
536
537    if( active > 0 && [fDefaults boolForKey: @"CheckRemove"] )
538    {
539        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
540            torrents, @"Torrents",
541            [NSNumber numberWithBool: deleteData], @"DeleteData",
542            nil];
543
544        NSString * title, * message;
545       
546        int selected = [fTableView numberOfSelectedRows];
547        if (selected == 1)
548        {
549            title = [NSString stringWithFormat: @"Comfirm Removal of \"%@\"",
550                        [[fTorrents objectAtIndex: [fTableView selectedRow]] name]];
551            message = @"This transfer is active."
552                        " Once removed, continuing the transfer will require the torrent file."
553                        " Do you really want to remove it?";
554        }
555        else
556        {
557            title = [NSString stringWithFormat: @"Comfirm Removal of %d Transfers", selected];
558            if (selected == active)
559                message = [NSString stringWithFormat:
560                    @"There are %d active transfers.", active];
561            else
562                message = [NSString stringWithFormat:
563                    @"There are %d transfers (%d active).", selected, active];
564            message = [message stringByAppendingString:
565                @" Once removed, continuing the transfers will require the torrent files."
566                " Do you really want to remove them?"];
567        }
568
569        NSBeginAlertSheet(title,
570            @"Remove", @"Cancel", nil, fWindow, self,
571            @selector(removeSheetDidEnd:returnCode:contextInfo:),
572            nil, dict, message);
573    }
574    else
575    {
576        [self confirmRemoveTorrents: torrents
577                deleteData: deleteData];
578    }
579}
580
581- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
582                        contextInfo: (NSDictionary *) dict
583{
584    [NSApp stopModal];
585
586    NSArray * torrents = [dict objectForKey: @"Torrents"];
587    BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue];
588    [dict release];
589   
590    if (returnCode == NSAlertDefaultReturn)
591    {
592        [self confirmRemoveTorrents: torrents
593            deleteData: deleteData];
594    }
595    else
596        [torrents release];
597}
598
599- (void) confirmRemoveTorrents: (NSArray *) torrents
600            deleteData: (BOOL) deleteData
601{
602    Torrent * torrent;
603    NSEnumerator * enumerator = [torrents objectEnumerator];
604    while ((torrent = [enumerator nextObject]))
605    {
606        [torrent stop];
607
608        if( deleteData )
609            [torrent trashData];
610
611        [torrent removeForever];
612        [fTorrents removeObject: torrent];
613    }
614    [torrents release];
615   
616    [self torrentNumberChanged];
617    [fTableView deselectAll: nil];
618    [self updateUI: nil];
619    [self updateTorrentHistory];
620}
621
622- (void) removeTorrent: (id) sender
623{
624    [self removeTorrentWithIndex: [fTableView selectedRowIndexes] deleteData: NO];
625}
626
627- (void) removeTorrentDeleteData: (id) sender
628{
629    [self removeTorrentWithIndex: [fTableView selectedRowIndexes] deleteData: YES];
630}
631
632- (void) copyTorrentFile: (id) sender
633{
634    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
635            [self torrentsAtIndexes: [fTableView selectedRowIndexes]]]];
636}
637
638- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
639{
640    if ([torrents count] == 0)
641    {
642        [torrents release];
643        return;
644    }
645
646    Torrent * torrent = [torrents objectAtIndex: 0];
647
648    //warn user if torrent file can't be found
649    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
650    {
651        NSAlert * alert = [[NSAlert alloc] init];
652        [alert addButtonWithTitle: @"OK"];
653        [alert setMessageText: [NSString stringWithFormat:
654                @"Copy of \"%@\" Cannot Be Created", [torrent name]]];
655        [alert setInformativeText: [NSString stringWithFormat:
656                @"The torrent file (%@) cannot be found.", [torrent torrentLocation]]];
657        [alert setAlertStyle: NSWarningAlertStyle];
658       
659        [alert runModal];
660       
661        [torrents removeObjectAtIndex: 0];
662        [self copyTorrentFileForTorrents: torrents];
663    }
664    else
665    {
666        NSSavePanel * panel = [NSSavePanel savePanel];
667        [panel setRequiredFileType: @"torrent"];
668        [panel setExtensionHidden: NO];
669        [panel setCanSelectHiddenExtension: NO];
670       
671        [panel beginSheetForDirectory: nil file: [torrent name]
672            modalForWindow: fWindow modalDelegate: self didEndSelector:
673            @selector( saveTorrentCopySheetClosed:returnCode:contextInfo: )
674            contextInfo: torrents];
675    }
676}
677
678- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code
679    contextInfo: (NSMutableArray *) torrents
680{
681    //if save successful, copy torrent to new location with name of data file
682    if (code == NSOKButton)
683        [[NSFileManager defaultManager] copyPath: [[torrents objectAtIndex: 0] torrentLocation]
684                toPath: [panel filename] handler: nil];
685   
686    [torrents removeObjectAtIndex: 0];
687    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:)
688                withObject: torrents waitUntilDone: NO];
689}
690
691- (void) revealFile: (id) sender
692{
693    Torrent * torrent;
694    NSIndexSet * indexSet = [fTableView selectedRowIndexes];
695    unsigned int i;
696   
697    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
698    {
699        torrent = [fTorrents objectAtIndex: i];
700        [torrent reveal];
701    }
702}
703
704- (void) showPreferenceWindow: (id) sender
705{
706    NSWindow * window = [fPrefsController window];
707    if (![window isVisible])
708        [window center];
709
710    [window makeKeyAndOrderFront: nil];
711}
712
713- (void) showInfo: (id) sender
714{
715    if ([[fInfoController window] isVisible])
716        [[fInfoController window] performClose: nil];
717    else
718    {
719        [fInfoController updateInfoStats];
720        [[fInfoController window] orderFront: nil];
721    }
722}
723
724- (void) setInfoTab: (id) sender
725{
726    if (sender == fNextInfoTabItem)
727        [fInfoController setNextTab];
728    else
729        [fInfoController setPreviousTab];
730}
731
732- (void) updateUI: (NSTimer *) t
733{
734    NSEnumerator * enumerator = [fTorrents objectEnumerator];
735    Torrent * torrent;
736    while( ( torrent = [enumerator nextObject] ) )
737    {
738        [torrent update];
739
740        if( [torrent justFinished] )
741        {
742            /* Notifications */
743            [self notifyGrowl: [torrent name]];
744            if( ![fWindow isKeyWindow] )
745                fCompleted++;
746           
747            if ([fSortType isEqualToString: @"State"])
748                [self sortTorrents];
749        }
750    }
751
752    if ([fSortType isEqualToString: @"Progress"])
753        [self sortTorrents];
754    else
755        [fTableView reloadData];
756   
757    //Update the global DL/UL rates
758    float downloadRate, uploadRate;
759    tr_torrentRates(fLib, & downloadRate, & uploadRate);
760    if (fStatusBarVisible)
761    {
762        [fTotalDLField setStringValue: [NSString stringForSpeed: downloadRate]];
763        [fTotalULField setStringValue: [NSString stringForSpeed: uploadRate]];
764    }
765
766    if ([[fInfoController window] isVisible])
767        [fInfoController updateInfoStats];
768
769    //badge dock
770    [fBadger updateBadgeWithCompleted: fCompleted
771        uploadRate: uploadRate downloadRate: downloadRate];
772}
773
774- (void) updateTorrentHistory
775{
776    NSMutableArray * history = [NSMutableArray
777        arrayWithCapacity: [fTorrents count]];
778
779    NSEnumerator * enumerator = [fTorrents objectEnumerator];
780    Torrent * torrent;
781    while( ( torrent = [enumerator nextObject] ) )
782        [history addObject: [torrent history]];
783
784    [fDefaults setObject: history forKey: @"History"];
785}
786
787- (void) sortTorrents
788{
789    //remember selected rows if needed
790    NSArray * selectedTorrents = nil;
791    int numSelected = [fTableView numberOfSelectedRows];
792    if (numSelected > 0 && numSelected < [fTorrents count])
793        selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
794
795    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:
796                                            @"name" ascending: YES] autorelease],
797                    * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
798                                            @"date" ascending: YES] autorelease];
799    NSArray * descriptors;
800    if ([fSortType isEqualToString: @"Name"])
801        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, dateDescriptor, nil];
802    else if ([fSortType isEqualToString: @"State"])
803    {
804        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
805                                                @"stateSortKey" ascending: NO] autorelease];
806        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, nameDescriptor, dateDescriptor, nil];
807    }
808    else if ([fSortType isEqualToString: @"Progress"])
809    {
810        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
811                                                @"progressSortKey" ascending: YES] autorelease];
812        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, dateDescriptor, nil];
813    }
814    else
815        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
816
817    [fTorrents sortUsingDescriptors: descriptors];
818   
819    [descriptors release];
820   
821    [fTableView reloadData];
822   
823    //set selected rows if needed
824    if (selectedTorrents)
825    {
826        Torrent * torrent;
827        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
828        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
829        while ((torrent = [enumerator nextObject]))
830            [indexSet addIndex: [fTorrents indexOfObject: torrent]];
831       
832        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
833        [indexSet release];
834    }
835}
836
837- (void) setSort: (id) sender
838{
839    NSMenuItem * prevSortItem;
840    if ([fSortType isEqualToString: @"Name"])
841        prevSortItem = fNameSortItem;
842    else if ([fSortType isEqualToString: @"State"])
843        prevSortItem = fStateSortItem;
844    else if ([fSortType isEqualToString: @"Progress"])
845        prevSortItem = fProgressSortItem;
846    else
847        prevSortItem = fDateSortItem;
848   
849    if (sender == prevSortItem)
850        return;
851   
852    [prevSortItem setState: NSOffState];
853    [sender setState: NSOnState];
854
855    [fSortType release];
856    if (sender == fNameSortItem)
857        fSortType = [[NSString alloc] initWithString: @"Name"];
858    else if (sender == fStateSortItem)
859        fSortType = [[NSString alloc] initWithString: @"State"];
860    else if (sender == fProgressSortItem)
861        fSortType = [[NSString alloc] initWithString: @"Progress"];
862    else
863        fSortType = [[NSString alloc] initWithString: @"Date"];
864       
865    [fDefaults setObject: fSortType forKey: @"Sort"];
866
867    [self sortTorrents];
868}
869
870- (void) setLimitGlobalEnabled: (id) sender
871{
872    [fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
873                        type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem)
874                            ? @"Upload" : @"Download"];
875}
876
877- (void) setQuickLimitGlobal: (id) sender
878{
879    NSString * title = [sender title];
880    [fPrefsController setQuickLimit: [[title substringToIndex: [title length]
881                                                    - [@" KB/s" length]] intValue]
882                    type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
883}
884
885- (void) limitGlobalChange: (NSNotification *) notification
886{
887    NSDictionary * dict = [notification object];
888   
889    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
890    int limit = [[dict objectForKey: @"Limit"] intValue];
891   
892    NSMenuItem * limitItem, * noLimitItem;
893    if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
894    {
895        limitItem = fUploadLimitItem;
896        noLimitItem = fUploadNoLimitItem;
897    }
898    else
899    {
900        limitItem = fDownloadLimitItem;
901        noLimitItem = fDownloadNoLimitItem;
902    }
903    [limitItem setState: enable ? NSOnState : NSOffState];
904    [noLimitItem setState: !enable ? NSOnState : NSOffState];
905   
906    [limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
907                            [[dict objectForKey: @"Limit"] intValue]]];
908
909    [dict release];
910}
911
912- (void) setRatioGlobalEnabled: (id) sender
913{
914    [fPrefsController setRatioEnabled: sender == fRatioSetItem];
915}
916
917- (void) setQuickRatioGlobal: (id) sender
918{
919    [fPrefsController setQuickRatio: [[sender title] floatValue]];
920}
921
922- (void) ratioGlobalChange: (NSNotification *) notification
923{
924    NSDictionary * dict = [notification object];
925   
926    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
927    [fRatioSetItem setState: enable ? NSOnState : NSOffState];
928    [fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
929   
930    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
931                            [[dict objectForKey: @"Ratio"] floatValue]]];
932
933    [dict release];
934}
935
936- (void) ratioSingleChange: (NSNotification *) notification
937{
938    if ([fSortType isEqualToString: @"State"])
939        [self sortTorrents];
940   
941    //update info for changed ratio setting
942    NSArray * torrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
943    if ([torrents containsObject: [notification object]])
944        [fInfoController updateInfoForTorrents: torrents];
945}
946
947- (int) numberOfRowsInTableView: (NSTableView *) t
948{
949    return [fTorrents count];
950}
951
952- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
953    forTableColumn: (NSTableColumn *) tableColumn row: (int) row
954{
955    [cell setTorrent: [fTorrents objectAtIndex: row]];
956}
957
958- (BOOL) tableView: (NSTableView *) t acceptDrop:
959    (id <NSDraggingInfo>) info row: (int) row dropOperation:
960    (NSTableViewDropOperation) operation
961{
962    [self application: NSApp openFiles: [[[info draggingPasteboard]
963        propertyListForType: NSFilenamesPboardType]
964        pathsMatchingExtensions: [NSArray arrayWithObject: @"torrent"]]];
965    return YES;
966}
967
968- (NSDragOperation) tableView: (NSTableView *) t validateDrop:
969    (id <NSDraggingInfo>) info proposedRow: (int) row
970    proposedDropOperation: (NSTableViewDropOperation) operation
971{
972    NSPasteboard * pasteboard = [info draggingPasteboard];
973    if (![[pasteboard types] containsObject: NSFilenamesPboardType]
974            || [[[pasteboard propertyListForType: NSFilenamesPboardType]
975                pathsMatchingExtensions: [NSArray arrayWithObject: @"torrent"]]
976                count] == 0)
977        return NSDragOperationNone;
978
979    [fTableView setDropRow: [fTableView numberOfRows] dropOperation: NSTableViewDropAbove];
980    return NSDragOperationGeneric;
981}
982
983- (void) tableViewSelectionDidChange: (NSNotification *) notification
984{
985    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes:
986                                    [fTableView selectedRowIndexes]]];
987}
988
989- (void) toggleStatusBar: (id) sender
990{
991    [self showStatusBar: !fStatusBarVisible animate: YES];
992    [fDefaults setBool: fStatusBarVisible forKey: @"StatusBar"];
993}
994
995- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
996{
997    if (show == fStatusBarVisible)
998        return;
999
1000    NSRect frame = [fWindow frame];
1001    float heightChange = [fStatusBar frame].size.height;
1002    if (!show)
1003        heightChange *= -1;
1004
1005    frame.size.height += heightChange;
1006    frame.origin.y -= heightChange;
1007       
1008    fStatusBarVisible = !fStatusBarVisible;
1009   
1010    //reloads stats
1011    [self torrentNumberChanged];
1012    [self updateUI: nil];
1013   
1014    //set views to not autoresize
1015    unsigned int statsMask = [fStatusBar autoresizingMask];
1016    unsigned int scrollMask = [fScrollView autoresizingMask];
1017    [fStatusBar setAutoresizingMask: 0];
1018    [fScrollView setAutoresizingMask: 0];
1019   
1020    [fWindow setFrame: frame display: YES animate: animate];
1021   
1022    //re-enable autoresize
1023    [fStatusBar setAutoresizingMask: statsMask];
1024    [fScrollView setAutoresizingMask: scrollMask];
1025   
1026    //change min size
1027    NSSize minSize = [fWindow contentMinSize];
1028    minSize.height += heightChange;
1029    [fWindow setContentMinSize: minSize];
1030}
1031
1032- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1033    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1034{
1035    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1036
1037    if( [ident isEqualToString: TOOLBAR_OPEN] )
1038    {
1039        [item setLabel: @"Open"];
1040        [item setPaletteLabel: @"Open Torrent Files"];
1041        [item setToolTip: @"Open torrent files"];
1042        [item setImage: [NSImage imageNamed: @"Open.png"]];
1043        [item setTarget: self];
1044        [item setAction: @selector( openShowSheet: )];
1045    }
1046    else if( [ident isEqualToString: TOOLBAR_REMOVE] )
1047    {
1048        [item setLabel: @"Remove"];
1049        [item setPaletteLabel: @"Remove Selected"];
1050        [item setToolTip: @"Remove selected torrents"];
1051        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1052        [item setTarget: self];
1053        [item setAction: @selector( removeTorrent: )];
1054    }
1055    else if( [ident isEqualToString: TOOLBAR_INFO] )
1056    {
1057        [item setLabel: @"Inspector"];
1058        [item setPaletteLabel: @"Show/Hide Inspector"];
1059        [item setToolTip: @"Display torrent inspector"];
1060        [item setImage: [NSImage imageNamed: @"Info.png"]];
1061        [item setTarget: self];
1062        [item setAction: @selector( showInfo: )];
1063    }
1064    else if( [ident isEqualToString: TOOLBAR_PAUSE_ALL] )
1065    {
1066        [item setLabel: @"Pause All"];
1067        [item setPaletteLabel: [item label]];
1068        [item setToolTip: @"Pause all torrents"];
1069        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1070        [item setTarget: self];
1071        [item setAction: @selector( stopAllTorrents: )];
1072    }
1073    else if( [ident isEqualToString: TOOLBAR_RESUME_ALL] )
1074    {
1075        [item setLabel: @"Resume All"];
1076        [item setPaletteLabel: [item label]];
1077        [item setToolTip: @"Resume all torrents"];
1078        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1079        [item setTarget: self];
1080        [item setAction: @selector( resumeAllTorrents: )];
1081    }
1082    else if( [ident isEqualToString: TOOLBAR_PAUSE_SELECTED] )
1083    {
1084        [item setLabel: @"Pause"];
1085        [item setPaletteLabel: @"Pause Selected"];
1086        [item setToolTip: @"Pause selected torrents"];
1087        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1088        [item setTarget: self];
1089        [item setAction: @selector( stopTorrent: )];
1090    }
1091    else if( [ident isEqualToString: TOOLBAR_RESUME_SELECTED] )
1092    {
1093        [item setLabel: @"Resume"];
1094        [item setPaletteLabel: @"Resume Selected"];
1095        [item setToolTip: @"Resume selected torrents"];
1096        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1097        [item setTarget: self];
1098        [item setAction: @selector( resumeTorrent: )];
1099    }
1100    else
1101    {
1102        [item release];
1103        return nil;
1104    }
1105
1106    return item;
1107}
1108
1109- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1110{
1111    return [NSArray arrayWithObjects:
1112            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1113            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1114            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1115            TOOLBAR_INFO,
1116            NSToolbarSeparatorItemIdentifier,
1117            NSToolbarSpaceItemIdentifier,
1118            NSToolbarFlexibleSpaceItemIdentifier,
1119            NSToolbarCustomizeToolbarItemIdentifier, nil];
1120}
1121
1122- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1123{
1124    return [NSArray arrayWithObjects:
1125            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1126            NSToolbarSeparatorItemIdentifier,
1127            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1128            NSToolbarFlexibleSpaceItemIdentifier,
1129            TOOLBAR_INFO, nil];
1130}
1131
1132- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1133{
1134    SEL action = [toolbarItem action];
1135
1136    //enable remove item
1137    if (action == @selector(removeTorrent:))
1138        return [fTableView numberOfSelectedRows] > 0;
1139
1140    //enable pause all item
1141    if (action == @selector(stopAllTorrents:))
1142    {
1143        Torrent * torrent;
1144        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1145        while( ( torrent = [enumerator nextObject] ) )
1146            if( [torrent isActive] )
1147                return YES;
1148        return NO;
1149    }
1150
1151    //enable resume all item
1152    if (action == @selector(resumeAllTorrents:))
1153    {
1154        Torrent * torrent;
1155        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1156        while( ( torrent = [enumerator nextObject] ) )
1157            if( [torrent isPaused] )
1158                return YES;
1159        return NO;
1160    }
1161
1162    //enable pause item
1163    if( action == @selector(stopTorrent:) )
1164    {
1165        Torrent * torrent;
1166        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1167        unsigned int i;
1168       
1169        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1170        {
1171            torrent = [fTorrents objectAtIndex: i];
1172            if ([torrent isActive])
1173                return YES;
1174        }
1175        return NO;
1176    }
1177   
1178    //enable resume item
1179    if( action == @selector(resumeTorrent:) )
1180    {
1181        Torrent * torrent;
1182        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1183        unsigned int i;
1184       
1185        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1186        {
1187            torrent = [fTorrents objectAtIndex: i];
1188            if ([torrent isPaused])
1189                return YES;
1190        }
1191        return NO;
1192    }
1193
1194    return YES;
1195}
1196
1197- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1198{
1199    SEL action = [menuItem action];
1200
1201    //only enable some items if it is in a context menu or the window is useable
1202    BOOL canUseMenu = [[[menuItem menu] title] isEqualToString: @"Context"]
1203                        || [fWindow isKeyWindow];
1204
1205    //enable show info
1206    if (action == @selector(showInfo:))
1207    {
1208        NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
1209        if (![[menuItem title] isEqualToString: title])
1210                [menuItem setTitle: title];
1211
1212        return YES;
1213    }
1214   
1215    if (action == @selector(setInfoTab:))
1216        return [[fInfoController window] isVisible];
1217   
1218    //enable toggle status bar
1219    if (action == @selector(toggleStatusBar:))
1220    {
1221        NSString * title = fStatusBarVisible ? @"Hide Status Bar" : @"Show Status Bar";
1222        if (![[menuItem title] isEqualToString: title])
1223                [menuItem setTitle: title];
1224
1225        return canUseMenu;
1226    }
1227
1228    //enable resume all item
1229    if (action == @selector(resumeAllTorrents:))
1230    {
1231        Torrent * torrent;
1232        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1233        while( ( torrent = [enumerator nextObject] ) )
1234            if( [torrent isPaused] )
1235                return YES;
1236        return NO;
1237    }
1238
1239    //enable pause all item
1240    if (action == @selector(stopAllTorrents:))
1241    {
1242        Torrent * torrent;
1243        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1244        while( ( torrent = [enumerator nextObject] ) )
1245            if( [torrent isActive] )
1246                return YES;
1247        return NO;
1248    }
1249
1250    if (action == @selector(revealFile:))
1251    {
1252        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1253    }
1254
1255    //enable remove items
1256    if (action == @selector(removeTorrent:) || action == @selector(removeTorrentDeleteData:))
1257    {
1258        BOOL active = NO;
1259        Torrent * torrent;
1260        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1261        unsigned int i;
1262       
1263        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1264        {
1265            torrent = [fTorrents objectAtIndex: i];
1266            if ([torrent isActive])
1267            {
1268                active = YES;
1269                break;
1270            }
1271        }
1272   
1273        //append or remove ellipsis when needed
1274        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
1275        if (active && [fDefaults boolForKey: @"CheckRemove"])
1276        {
1277            if (![title hasSuffix: ellipsis])
1278                [menuItem setTitle: [title stringByAppendingEllipsis]];
1279        }
1280        else
1281        {
1282            if ([title hasSuffix: ellipsis])
1283                [menuItem setTitle: [title substringToIndex:
1284                            [title rangeOfString: ellipsis].location]];
1285        }
1286        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1287    }
1288
1289    //enable pause item
1290    if( action == @selector(stopTorrent:) )
1291    {
1292        if (!canUseMenu)
1293            return NO;
1294   
1295        Torrent * torrent;
1296        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1297        unsigned int i;
1298       
1299        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1300        {
1301            torrent = [fTorrents objectAtIndex: i];
1302            if ([torrent isActive])
1303                return YES;
1304        }
1305        return NO;
1306    }
1307   
1308    //enable resume item
1309    if( action == @selector(resumeTorrent:) )
1310    {
1311        if (!canUseMenu)
1312            return NO;
1313   
1314        Torrent * torrent;
1315        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1316        unsigned int i;
1317       
1318        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1319        {
1320            torrent = [fTorrents objectAtIndex: i];
1321            if ([torrent isPaused])
1322                return YES;
1323        }
1324        return NO;
1325    }
1326   
1327    //enable resume item
1328    if (action == @selector(setSort:) || (action == @selector(advancedChanged:)))
1329        return canUseMenu;
1330   
1331    //enable copy torrent file item
1332    if( action == @selector(copyTorrentFile:) )
1333    {
1334        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1335    }
1336
1337    return YES;
1338}
1339
1340- (void) sleepCallBack: (natural_t) messageType argument:
1341                          (void *) messageArgument
1342{
1343    NSEnumerator * enumerator;
1344    Torrent * torrent;
1345    BOOL active;
1346
1347    switch( messageType )
1348    {
1349        case kIOMessageSystemWillSleep:
1350            /* Close all connections before going to sleep and remember
1351               we should resume when we wake up */
1352            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
1353
1354            /* Wait for torrents to stop (5 seconds timeout) */
1355            NSDate * start = [NSDate date];
1356            enumerator = [fTorrents objectEnumerator];
1357            while( ( torrent = [enumerator nextObject] ) )
1358            {
1359                while( [[NSDate date] timeIntervalSinceDate: start] < 5 &&
1360                        ![torrent isPaused] )
1361                {
1362                    usleep( 100000 );
1363                    [torrent update];
1364                }
1365            }
1366
1367            IOAllowPowerChange( fRootPort, (long) messageArgument );
1368            break;
1369
1370        case kIOMessageCanSystemSleep:
1371            /* Prevent idle sleep unless all paused */
1372            active = NO;
1373            enumerator = [fTorrents objectEnumerator];
1374            while ((torrent = [enumerator nextObject]))
1375                if ([torrent isActive])
1376                {
1377                    active = YES;
1378                    break;
1379                }
1380
1381            if (active)
1382                IOCancelPowerChange( fRootPort, (long) messageArgument );
1383            else
1384                IOAllowPowerChange( fRootPort, (long) messageArgument );
1385            break;
1386
1387        case kIOMessageSystemHasPoweredOn:
1388            /* Resume download after we wake up */
1389            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
1390            break;
1391    }
1392}
1393
1394- (NSRect) windowWillUseStandardFrame: (NSWindow *) w
1395    defaultFrame: (NSRect) defaultFrame
1396{
1397    NSRect windowRect = [fWindow frame];
1398    int count = [fTorrents count];
1399    float newHeight = windowRect.size.height - [fScrollView frame].size.height
1400            + count * ([fTableView rowHeight] + [fTableView intercellSpacing].height) + 30.0;
1401
1402    float minHeight = [fWindow minSize].height;
1403    if (newHeight < minHeight)
1404        newHeight = minHeight;
1405
1406    windowRect.origin.y -= (newHeight - windowRect.size.height);
1407    windowRect.size.height = newHeight;
1408
1409    return windowRect;
1410}
1411
1412- (void) showMainWindow: (id) sender
1413{
1414    [fWindow makeKeyAndOrderFront: nil];
1415}
1416
1417- (void) windowDidBecomeKey: (NSNotification *) notification
1418{
1419    fCompleted = 0;
1420}
1421
1422- (void) linkHomepage: (id) sender
1423{
1424    [[NSWorkspace sharedWorkspace] openURL: [NSURL
1425        URLWithString: WEBSITE_URL]];
1426}
1427
1428- (void) linkForums: (id) sender
1429{
1430    [[NSWorkspace sharedWorkspace] openURL: [NSURL
1431        URLWithString: FORUM_URL]];
1432}
1433
1434- (void) notifyGrowl: (NSString * ) file
1435{
1436    NSString * growlScript;
1437    NSAppleScript * appleScript;
1438    NSDictionary * error;
1439
1440    if( !fHasGrowl )
1441        return;
1442
1443    growlScript = [NSString stringWithFormat:
1444        @"tell application \"System Events\"\n"
1445         "  if exists application process \"GrowlHelperApp\" then\n"
1446         "    tell application \"GrowlHelperApp\"\n "
1447         "      notify with name \"Download Complete\""
1448         "        title \"Download Complete\""
1449         "        description \"%@\""
1450         "        application name \"Transmission\"\n"
1451         "    end tell\n"
1452         "  end if\n"
1453         "end tell", file];
1454    appleScript = [[NSAppleScript alloc] initWithSource: growlScript];
1455    if( ![appleScript executeAndReturnError: &error] )
1456    {
1457        NSLog( @"Growl notify failed" );
1458    }
1459    [appleScript release];
1460}
1461
1462- (void) growlRegister: (id) sender
1463{
1464    NSString * growlScript;
1465    NSAppleScript * appleScript;
1466    NSDictionary * error;
1467
1468    if( !fHasGrowl )
1469        return;
1470
1471    growlScript = [NSString stringWithFormat:
1472        @"tell application \"System Events\"\n"
1473         "  if exists application process \"GrowlHelperApp\" then\n"
1474         "    tell application \"GrowlHelperApp\"\n"
1475         "      register as application \"Transmission\" "
1476         "        all notifications {\"Download Complete\"}"
1477         "        default notifications {\"Download Complete\"}"
1478         "        icon of application \"Transmission\"\n"
1479         "    end tell\n"
1480         "  end if\n"
1481         "end tell"];
1482
1483    appleScript = [[NSAppleScript alloc] initWithSource: growlScript];
1484    if( ![appleScript executeAndReturnError: &error] )
1485    {
1486        NSLog( @"Growl registration failed" );
1487    }
1488    [appleScript release];
1489}
1490
1491- (void) checkUpdate: (id) sender
1492{
1493    [fPrefsController checkUpdate];
1494}
1495
1496- (void) prepareForUpdate: (NSNotification *) notification
1497{
1498    fUpdateInProgress = YES;
1499}
1500
1501@end
Note: See TracBrowser for help on using the repository browser.