source: trunk/macosx/Controller.m @ 465

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

I don't think these will be needed anymore.

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