source: trunk/macosx/Controller.m @ 389

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

cleanup

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