transmission/macosx/Controller.m

1480 lines
47 KiB
Mathematica
Raw Normal View History

2006-01-12 17:43:21 +00:00
/******************************************************************************
* $Id$
*
2006-03-23 12:39:39 +00:00
* Copyright (c) 2005-2006 Transmission authors and contributors
2006-01-12 17:43:21 +00:00
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*****************************************************************************/
#import <IOKit/IOMessage.h>
2006-01-12 17:43:21 +00:00
2006-03-23 12:39:39 +00:00
#import "Controller.h"
#import "Torrent.h"
#import "TorrentCell.h"
#import "TorrentTableView.h"
#import "StringAdditions.h"
#import "Utils.h"
2006-01-12 17:43:21 +00:00
#import <Sparkle/Sparkle.h>
2006-01-12 18:57:23 +00:00
#define TOOLBAR_OPEN @"Toolbar Open"
#define TOOLBAR_REMOVE @"Toolbar Remove"
#define TOOLBAR_INFO @"Toolbar Info"
#define TOOLBAR_PAUSE_ALL @"Toolbar Pause All"
#define TOOLBAR_RESUME_ALL @"Toolbar Resume All"
#define TOOLBAR_PAUSE_SELECTED @"Toolbar Pause Selected"
#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected"
2006-01-12 17:43:21 +00:00
2006-01-29 22:01:08 +00:00
#define WEBSITE_URL @"http://transmission.m0k.org/"
#define FORUM_URL @"http://transmission.m0k.org/forum/"
#define VERSION_PLIST_URL @"http://transmission.m0k.org/version.plist"
2006-01-12 18:57:23 +00:00
#define GROWL_PATH @"/Library/PreferencePanes/Growl.prefPane/Contents/Resources/GrowlHelperApp.app"
2006-01-12 18:29:20 +00:00
2006-01-12 17:43:21 +00:00
static void sleepCallBack( void * controller, io_service_t y,
natural_t messageType, void * messageArgument )
{
Controller * c = controller;
[c sleepCallBack: messageType argument: messageArgument];
}
2006-01-12 21:45:45 +00:00
2006-01-12 17:43:21 +00:00
@implementation Controller
2006-03-23 12:39:39 +00:00
- (id) init
{
if ((self = [super init]))
{
fLib = tr_init();
fTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
fDefaults = [NSUserDefaults standardUserDefaults];
fInfoController = [[InfoWindowController alloc] initWithWindowNibName: @"InfoWindow"];
fPrefsController = [[PrefsController alloc] initWithWindowNibName: @"PrefsWindow"];
}
2006-03-23 12:39:39 +00:00
return self;
}
- (void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
2006-03-23 12:39:39 +00:00
[fTorrents release];
[fToolbar release];
[fInfoController release];
[fBadger release];
[fSortType release];
2006-03-23 12:39:39 +00:00
tr_close( fLib );
[super dealloc];
}
2006-01-12 17:43:21 +00:00
- (void) awakeFromNib
{
2006-03-23 12:39:39 +00:00
[fPrefsController setPrefsWindow: fLib];
2006-01-12 18:57:23 +00:00
[fAdvancedBarItem setState: [fDefaults
boolForKey: @"UseAdvancedBar"] ? NSOnState : NSOffState];
2006-03-23 12:39:39 +00:00
2006-01-12 17:43:21 +00:00
fToolbar = [[NSToolbar alloc] initWithIdentifier: @"Transmission Toolbar"];
[fToolbar setDelegate: self];
[fToolbar setAllowsUserCustomization: YES];
[fToolbar setAutosavesConfiguration: YES];
2006-01-12 18:57:23 +00:00
[fWindow setToolbar: fToolbar];
[fWindow setDelegate: self];
//window min height
NSSize contentMinSize = [fWindow contentMinSize];
contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
+ [fTableView rowHeight] + [fTableView intercellSpacing].height;
[fWindow setContentMinSize: contentMinSize];
//set info keyboard shortcuts
unichar ch = NSRightArrowFunctionKey;
[fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
ch = NSLeftArrowFunctionKey;
[fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
//set up status bar
NSRect statusBarFrame = [fStatusBar frame];
statusBarFrame.size.width = [fWindow frame].size.width;
[fStatusBar setFrame: statusBarFrame];
NSView * contentView = [fWindow contentView];
[contentView addSubview: fStatusBar];
[fStatusBar setFrameOrigin: NSMakePoint(0, [fScrollView frame].origin.y
+ [fScrollView frame].size.height)];
[self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
[fActionButton setToolTip: @"Shortcuts for changing global settings."];
2006-01-12 17:43:21 +00:00
2006-03-23 12:39:39 +00:00
[fTableView setTorrents: fTorrents];
[[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell:
[[TorrentCell alloc] init]];
2006-01-12 17:43:21 +00:00
[fTableView registerForDraggedTypes:
[NSArray arrayWithObject: NSFilenamesPboardType]];
2006-01-12 17:43:21 +00:00
2006-01-12 18:57:23 +00:00
//Register for sleep notifications
IONotificationPortRef notify;
io_object_t anIterator;
if (fRootPort = IORegisterForSystemPower(self, & notify,
sleepCallBack, & anIterator))
2006-01-12 17:43:21 +00:00
{
CFRunLoopAddSource( CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource( notify ),
kCFRunLoopCommonModes );
}
2006-01-12 18:57:23 +00:00
else
NSLog( @"Could not IORegisterForSystemPower" );
2006-01-12 17:43:21 +00:00
//load torrents from history
2006-03-23 12:39:39 +00:00
Torrent * torrent;
NSDictionary * historyItem;
2006-01-12 18:57:23 +00:00
NSEnumerator * enumerator = [[fDefaults arrayForKey: @"History"] objectEnumerator];
while ((historyItem = [enumerator nextObject]))
if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
{
[fTorrents addObject: torrent];
[torrent release];
}
[self torrentNumberChanged];
//set sort
fSortType = [[fDefaults stringForKey: @"Sort"] retain];
NSMenuItem * currentSortItem;
if ([fSortType isEqualToString: @"Name"])
currentSortItem = fNameSortItem;
else if ([fSortType isEqualToString: @"State"])
currentSortItem = fStateSortItem;
else if ([fSortType isEqualToString: @"Progress"])
currentSortItem = fProgressSortItem;
else
currentSortItem = fDateSortItem;
[currentSortItem setState: NSOnState];
2006-01-12 18:57:23 +00:00
//check and register Growl if it is installed for this user or all users
NSFileManager * manager = [NSFileManager defaultManager];
fHasGrowl = [manager fileExistsAtPath: GROWL_PATH]
|| [manager fileExistsAtPath: [[NSString stringWithFormat: @"~%@",
GROWL_PATH] stringByExpandingTildeInPath]];
2006-01-12 18:40:47 +00:00
[self growlRegister: self];
2006-01-20 01:51:07 +00:00
//initialize badging
fBadger = [[Badger alloc] init];
//set upload limit action button
[fUploadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
[fDefaults integerForKey: @"UploadLimit"]]];
if ([fDefaults boolForKey: @"CheckUpload"])
[fUploadLimitItem setState: NSOnState];
else
[fUploadNoLimitItem setState: NSOnState];
//set download limit action menu
[fDownloadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
[fDefaults integerForKey: @"DownloadLimit"]]];
if ([fDefaults boolForKey: @"CheckDownload"])
[fDownloadLimitItem setState: NSOnState];
else
[fDownloadNoLimitItem setState: NSOnState];
//set ratio action menu
[fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
[fDefaults floatForKey: @"RatioLimit"]]];
if ([fDefaults boolForKey: @"RatioCheck"])
[fRatioSetItem setState: NSOnState];
else
[fRatioNotSetItem setState: NSOnState];
//observe notifications
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
[nc addObserver: self selector: @selector(prepareForUpdate:)
name: SUUpdaterWillRestartNotification object: nil];
fUpdateInProgress = NO;
[nc addObserver: self selector: @selector(ratioSingleChange:)
name: @"TorrentRatioChanged" object: nil];
[nc addObserver: self selector: @selector(limitGlobalChange:)
name: @"LimitGlobalChange" object: nil];
[nc addObserver: self selector: @selector(ratioGlobalChange:)
name: @"RatioGlobalChange" object: nil];
2006-03-23 12:39:39 +00:00
//timer to update the interface
fCompleted = 0;
[self updateUI: nil];
fTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
selector: @selector( updateUI: ) userInfo: nil repeats: YES];
2006-01-29 22:01:08 +00:00
[[NSRunLoop currentRunLoop] addTimer: fTimer
forMode: NSModalPanelRunLoopMode];
2006-01-12 17:43:21 +00:00
[[NSRunLoop currentRunLoop] addTimer: fTimer
2006-01-12 18:20:48 +00:00
forMode: NSEventTrackingRunLoopMode];
[self sortTorrents];
//show windows
[fWindow makeKeyAndOrderFront: nil];
[fInfoController updateInfoForTorrents: [self torrentsAtIndexes:
[fTableView selectedRowIndexes]]];
if ([fDefaults boolForKey: @"InfoVisible"])
[self showInfo: nil];
2006-01-12 18:20:48 +00:00
}
2006-01-12 17:43:21 +00:00
- (BOOL) applicationShouldHandleReopen: (NSApplication *) app
hasVisibleWindows: (BOOL) flag
{
if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
[self showMainWindow: nil];
2006-01-12 17:43:21 +00:00
return NO;
}
- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
2006-01-12 18:57:23 +00:00
{
if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
{
int active = 0;
Torrent * torrent;
NSEnumerator * enumerator = [fTorrents objectEnumerator];
while ((torrent = [enumerator nextObject]))
if ([torrent isActive])
active++;
if (active > 0)
{
NSString * message = active == 1
? @"There is an active torrent. Do you really want to quit?"
: [NSString stringWithFormat:
@"There are %d active torrents. Do you really want to quit?",
active];
NSBeginAlertSheet(@"Confirm Quit",
@"Quit", @"Cancel", nil,
fWindow, self,
@selector(quitSheetDidEnd:returnCode:contextInfo:),
nil, nil, message);
return NSTerminateLater;
}
2006-03-23 12:39:39 +00:00
}
2006-01-12 18:57:23 +00:00
return NSTerminateNow;
}
- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
contextInfo: (void *) contextInfo
2006-01-12 17:43:21 +00:00
{
2006-01-12 18:57:23 +00:00
[NSApp stopModal];
[NSApp replyToApplicationShouldTerminate:
(returnCode == NSAlertDefaultReturn)];
2006-01-12 18:57:23 +00:00
}
- (void) applicationWillTerminate: (NSNotification *) notification
2006-01-12 18:57:23 +00:00
{
// Stop updating the interface
2006-01-12 17:43:21 +00:00
[fTimer invalidate];
//save history
[self updateTorrentHistory];
//remember window states
[fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
[fWindow close];
[self showStatusBar: NO animate: NO];
//clear badge
[fBadger clearBadge];
2006-03-23 12:39:39 +00:00
//end quickly if updated version will open
if (fUpdateInProgress)
return;
2006-01-12 17:43:21 +00:00
//stop running torrents and wait for them to stop (5 seconds timeout)
[fTorrents makeObjectsPerformSelector: @selector(stop)];
2006-01-12 17:43:21 +00:00
NSDate * start = [NSDate date];
Torrent * torrent;
while ([fTorrents count] > 0)
2006-01-12 17:43:21 +00:00
{
2006-03-23 12:39:39 +00:00
torrent = [fTorrents objectAtIndex: 0];
while( [[NSDate date] timeIntervalSinceDate: start] < 5 &&
2006-03-23 12:39:39 +00:00
![torrent isPaused] )
2006-01-12 17:43:21 +00:00
{
usleep( 100000 );
2006-03-23 12:39:39 +00:00
[torrent update];
2006-01-12 17:43:21 +00:00
}
2006-03-23 12:39:39 +00:00
[fTorrents removeObject: torrent];
2006-01-12 17:43:21 +00:00
}
2006-01-12 18:57:23 +00:00
}
2006-01-12 17:43:21 +00:00
- (void) folderChoiceClosed: (NSOpenPanel *) s returnCode: (int) code
contextInfo: (Torrent *) torrent
2006-01-12 17:43:21 +00:00
{
2006-01-12 18:57:23 +00:00
if (code == NSOKButton)
{
[torrent setDownloadFolder: [[s filenames] objectAtIndex: 0]];
if ([fDefaults boolForKey: @"AutoStartDownload"])
[torrent start];
[fTorrents addObject: torrent];
[self torrentNumberChanged];
2006-01-12 17:43:21 +00:00
}
2006-01-12 17:43:21 +00:00
[NSApp stopModal];
}
- (void) application: (NSApplication *) sender
openFiles: (NSArray *) filenames
{
BOOL autoStart = [fDefaults boolForKey: @"AutoStartDownload"];
NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"],
* torrentPath;
2006-03-23 12:39:39 +00:00
Torrent * torrent;
2006-01-12 18:57:23 +00:00
NSEnumerator * enumerator = [filenames objectEnumerator];
while ((torrentPath = [enumerator nextObject]))
2006-01-12 17:43:21 +00:00
{
if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
2006-01-12 17:43:21 +00:00
continue;
2006-01-12 18:58:57 +00:00
/* Add it to the "File > Open Recent" menu */
[[NSDocumentController sharedDocumentController]
noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
if ([downloadChoice isEqualToString: @"Ask"])
2006-01-12 18:58:57 +00:00
{
NSOpenPanel * panel = [NSOpenPanel openPanel];
2006-03-23 12:39:39 +00:00
2006-01-12 18:58:57 +00:00
[panel setPrompt: @"Select Download Folder"];
[panel setAllowsMultipleSelection: NO];
[panel setCanChooseFiles: NO];
[panel setCanChooseDirectories: YES];
[panel setMessage: [@"Select the download folder for "
stringByAppendingString: [torrentPath lastPathComponent]]];
[panel beginSheetForDirectory: nil file: nil types: nil
2006-01-12 18:58:57 +00:00
modalForWindow: fWindow modalDelegate: self didEndSelector:
@selector( folderChoiceClosed:returnCode:contextInfo: )
contextInfo: torrent];
2006-01-12 18:58:57 +00:00
[NSApp runModalForWindow: panel];
}
else
{
NSString * folder = [downloadChoice isEqualToString: @"Constant"]
? [[fDefaults stringForKey: @"DownloadFolder"]
stringByExpandingTildeInPath]
: [torrentPath stringByDeletingLastPathComponent];
[torrent setDownloadFolder: folder];
if (autoStart)
[torrent start];
[fTorrents addObject: torrent];
}
[torrent release];
2006-01-12 17:43:21 +00:00
}
[self torrentNumberChanged];
[self updateUI: nil];
[self sortTorrents];
[self updateTorrentHistory];
2006-01-12 17:43:21 +00:00
}
- (NSArray *) torrentsAtIndexes: (NSIndexSet *) indexSet
{
if ([fTorrents respondsToSelector: @selector(objectsAtIndexes:)])
return [fTorrents objectsAtIndexes: indexSet];
else
{
NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [indexSet count]];
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
[torrents addObject: [fTorrents objectAtIndex: i]];
return torrents;
}
}
- (void) torrentNumberChanged
{
if (fStatusBarVisible)
{
int count = [fTorrents count];
[fTotalTorrentsField setStringValue: [NSString stringWithFormat:
@"%d Torrent%s", count, count == 1 ? "" : "s"]];
}
}
2006-01-12 17:43:21 +00:00
- (void) advancedChanged: (id) sender
{
2006-01-12 18:57:23 +00:00
[fAdvancedBarItem setState: ![fAdvancedBarItem state]];
[fDefaults setBool: [fAdvancedBarItem state] forKey: @"UseAdvancedBar"];
2006-01-12 18:57:23 +00:00
2006-01-12 18:33:20 +00:00
[fTableView display];
}
2006-01-12 18:57:23 +00:00
//called on by applescript
2006-01-12 18:33:20 +00:00
- (void) open: (NSArray *) files
{
[self performSelectorOnMainThread: @selector(cantFindAName:)
withObject: files waitUntilDone: NO];
2006-01-12 17:43:21 +00:00
}
- (void) openShowSheet: (id) sender
{
NSOpenPanel * panel = [NSOpenPanel openPanel];
NSArray * fileTypes = [NSArray arrayWithObject: @"torrent"];
2006-03-23 12:39:39 +00:00
2006-01-12 17:43:21 +00:00
[panel setAllowsMultipleSelection: YES];
[panel setCanChooseFiles: YES];
[panel setCanChooseDirectories: NO];
2006-01-12 17:43:21 +00:00
[panel beginSheetForDirectory: nil file: nil types: fileTypes
2006-01-12 17:43:21 +00:00
modalForWindow: fWindow modalDelegate: self didEndSelector:
@selector( openSheetClosed:returnCode:contextInfo: )
contextInfo: nil];
2006-01-12 17:43:21 +00:00
}
- (void) cantFindAName: (NSArray *) filenames
2006-01-12 17:43:21 +00:00
{
[self application: NSApp openFiles: filenames];
2006-01-12 17:43:21 +00:00
}
- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code
2006-01-12 17:43:21 +00:00
contextInfo: (void *) info
{
if( code == NSOKButton )
[self performSelectorOnMainThread: @selector(cantFindAName:)
withObject: [panel filenames] waitUntilDone: NO];
2006-01-12 17:43:21 +00:00
}
- (void) resumeTorrent: (id) sender
{
2006-04-07 13:09:19 +00:00
[self resumeTorrentWithIndex: [fTableView selectedRowIndexes]];
2006-01-12 18:20:48 +00:00
}
2006-01-12 18:33:20 +00:00
- (void) resumeAllTorrents: (id) sender
{
2006-04-07 13:09:19 +00:00
[self resumeTorrentWithIndex: [NSIndexSet indexSetWithIndexesInRange:
NSMakeRange(0, [fTorrents count])]];
2006-01-12 18:33:20 +00:00
}
2006-04-07 13:09:19 +00:00
- (void) resumeTorrentWithIndex: (NSIndexSet *) indexSet
2006-01-12 18:20:48 +00:00
{
Torrent * torrent;
2006-04-07 13:09:19 +00:00
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
[torrent start];
}
2006-03-23 12:39:39 +00:00
[self updateUI: nil];
if ([fSortType isEqualToString: @"State"])
[self sortTorrents];
[self updateTorrentHistory];
2006-01-12 17:43:21 +00:00
}
- (void) stopTorrent: (id) sender
{
2006-04-07 13:09:19 +00:00
[self stopTorrentWithIndex: [fTableView selectedRowIndexes]];
2006-01-12 18:20:48 +00:00
}
2006-01-12 18:33:20 +00:00
- (void) stopAllTorrents: (id) sender
{
2006-04-07 13:09:19 +00:00
[self stopTorrentWithIndex: [NSIndexSet indexSetWithIndexesInRange:
NSMakeRange(0, [fTorrents count])]];
2006-01-12 18:33:20 +00:00
}
2006-04-07 13:09:19 +00:00
- (void) stopTorrentWithIndex: (NSIndexSet *) indexSet
2006-01-12 18:20:48 +00:00
{
Torrent * torrent;
2006-04-07 13:09:19 +00:00
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
[torrent stop];
}
2006-03-23 12:39:39 +00:00
[self updateUI: nil];
if ([fSortType isEqualToString: @"State"])
[self sortTorrents];
[self updateTorrentHistory];
2006-01-12 17:43:21 +00:00
}
2006-04-07 13:09:19 +00:00
- (void) removeTorrentWithIndex: (NSIndexSet *) indexSet
2006-01-12 18:29:20 +00:00
deleteData: (BOOL) deleteData
2006-01-12 18:57:23 +00:00
{
NSArray * torrents = [[self torrentsAtIndexes: indexSet] retain];
int active = 0;
Torrent * torrent;
NSEnumerator * enumerator = [torrents objectEnumerator];
while ((torrent = [enumerator nextObject]))
if ([torrent isActive])
active++;
2006-03-23 12:39:39 +00:00
2006-04-07 13:09:19 +00:00
if( active > 0 && [fDefaults boolForKey: @"CheckRemove"] )
2006-01-12 18:57:23 +00:00
{
NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
torrents, @"Torrents",
2006-04-05 13:52:00 +00:00
[NSNumber numberWithBool: deleteData], @"DeleteData",
2006-03-23 12:39:39 +00:00
nil];
NSString * title, * message;
int selected = [fTableView numberOfSelectedRows];
if (selected == 1)
{
title = [NSString stringWithFormat: @"Comfirm Removal of \"%@\"",
[[fTorrents objectAtIndex: [fTableView selectedRow]] name]];
message = @"This transfer is active."
" Onced removed, continuing the transfer will require the torrent file."
" Do you really want to remove it?";
}
else
{
title = [NSString stringWithFormat: @"Comfirm Removal of %d Torrents", selected];
if (selected == active)
message = [NSString stringWithFormat:
@"There are %d active transfers.", active];
else
message = [NSString stringWithFormat:
@"There are %d transfers (%d active).", selected, active];
message = [message stringByAppendingString:
@" Onced removed, continuing the transfers will require the torrent files."
" Do you really want to remove them?"];
}
2006-04-07 13:09:19 +00:00
NSBeginAlertSheet(title,
2006-03-23 12:39:39 +00:00
@"Remove", @"Cancel", nil, fWindow, self,
2006-04-07 13:09:19 +00:00
@selector(removeSheetDidEnd:returnCode:contextInfo:),
nil, dict, message);
2006-03-23 12:39:39 +00:00
}
else
{
[self confirmRemoveTorrents: torrents
2006-03-23 12:39:39 +00:00
deleteData: deleteData];
2006-01-12 18:57:23 +00:00
}
}
- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
contextInfo: (NSDictionary *) dict
2006-01-12 18:57:23 +00:00
{
[NSApp stopModal];
2006-03-23 12:39:39 +00:00
NSArray * torrents = [dict objectForKey: @"Torrents"];
BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue];
[dict release];
if (returnCode == NSAlertDefaultReturn)
2006-01-12 18:57:23 +00:00
{
[self confirmRemoveTorrents: torrents
deleteData: deleteData];
2006-01-12 18:57:23 +00:00
}
else
[torrents release];
2006-01-12 18:57:23 +00:00
}
2006-03-23 12:39:39 +00:00
- (void) confirmRemoveTorrents: (NSArray *) torrents
2006-01-12 18:57:23 +00:00
deleteData: (BOOL) deleteData
2006-01-12 17:43:21 +00:00
{
2006-04-07 13:09:19 +00:00
Torrent * torrent;
NSEnumerator * enumerator = [torrents objectEnumerator];
while ((torrent = [enumerator nextObject]))
{
[torrent stop];
if( deleteData )
[torrent trashData];
[torrent removeForever];
[fTorrents removeObject: torrent];
}
[torrents release];
[self torrentNumberChanged];
[fTableView deselectAll: nil];
2006-03-23 12:39:39 +00:00
[self updateUI: nil];
[self updateTorrentHistory];
2006-01-12 17:43:21 +00:00
}
2006-01-12 18:29:20 +00:00
- (void) removeTorrent: (id) sender
{
[self removeTorrentWithIndex: [fTableView selectedRowIndexes] deleteData: NO];
2006-01-12 18:29:20 +00:00
}
- (void) removeTorrentDeleteData: (id) sender
{
[self removeTorrentWithIndex: [fTableView selectedRowIndexes] deleteData: YES];
2006-01-12 18:29:20 +00:00
}
- (void) copyTorrentFile: (id) sender
{
Torrent * torrent;
NSEnumerator * enumerator = [[self torrentsAtIndexes:
[fTableView selectedRowIndexes]] objectEnumerator];
while ((torrent = [enumerator nextObject]))
{
//warn user if torrent file can't be found
if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
{
NSAlert * alert = [[NSAlert alloc] init];
[alert addButtonWithTitle: @"OK"];
[alert setMessageText: [NSString stringWithFormat:
@"Copy of \"%@\" Cannot Be Created", [torrent name]]];
[alert setInformativeText: [NSString stringWithFormat:
@"The torrent file (%@) cannot be found.", [torrent torrentLocation]]];
[alert setAlertStyle: NSWarningAlertStyle];
[alert runModal];
continue;
}
//save with extension
NSSavePanel * savePanel = [NSSavePanel savePanel];
[savePanel setRequiredFileType: @"torrent"];
[savePanel setCanSelectHiddenExtension: YES];
//if save successful, copy torrent to new location with name of data file
if ([savePanel runModalForDirectory: nil file: [torrent name]] == NSOKButton)
[[NSFileManager defaultManager] copyPath: [torrent torrentLocation]
toPath: [savePanel filename] handler: nil];
}
}
- (void) revealFile: (id) sender
{
Torrent * torrent;
NSIndexSet * indexSet = [fTableView selectedRowIndexes];
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
[torrent reveal];
}
}
- (void) showPreferenceWindow: (id) sender
{
NSWindow * window = [fPrefsController window];
if (![window isVisible])
[window center];
[window makeKeyAndOrderFront: nil];
}
- (void) showInfo: (id) sender
{
if ([[fInfoController window] isVisible])
[[fInfoController window] performClose: nil];
else
{
[fInfoController updateInfoStats];
[[fInfoController window] orderFront: nil];
}
}
- (void) setInfoTab: (id) sender
{
if (sender == fNextInfoTabItem)
[fInfoController setNextTab];
else
[fInfoController setPreviousTab];
}
2006-01-12 17:43:21 +00:00
- (void) updateUI: (NSTimer *) t
{
NSEnumerator * enumerator = [fTorrents objectEnumerator];
2006-03-23 12:39:39 +00:00
Torrent * torrent;
while( ( torrent = [enumerator nextObject] ) )
{
[torrent update];
if( [torrent justFinished] )
{
/* Notifications */
[self notifyGrowl: [torrent name]];
if( ![fWindow isKeyWindow] )
fCompleted++;
if ([fSortType isEqualToString: @"State"])
[self sortTorrents];
2006-03-23 12:39:39 +00:00
}
}
if ([fSortType isEqualToString: @"Progress"])
[self sortTorrents];
else
[fTableView reloadData];
2006-01-12 18:57:23 +00:00
//Update the global DL/UL rates
float downloadRate, uploadRate;
tr_torrentRates(fLib, & downloadRate, & uploadRate);
if (fStatusBarVisible)
{
[fTotalDLField setStringValue: [NSString stringForSpeed: downloadRate]];
[fTotalULField setStringValue: [NSString stringForSpeed: uploadRate]];
}
2006-01-12 17:43:21 +00:00
if ([[fInfoController window] isVisible])
[fInfoController updateInfoStats];
2006-01-20 01:51:07 +00:00
//badge dock
[fBadger updateBadgeWithCompleted: fCompleted
uploadRate: uploadRate downloadRate: downloadRate];
2006-01-12 17:43:21 +00:00
}
- (void) updateTorrentHistory
{
2006-03-23 12:39:39 +00:00
NSMutableArray * history = [NSMutableArray
arrayWithCapacity: [fTorrents count]];
2006-03-23 12:39:39 +00:00
NSEnumerator * enumerator = [fTorrents objectEnumerator];
Torrent * torrent;
while( ( torrent = [enumerator nextObject] ) )
[history addObject: [torrent history]];
[fDefaults setObject: history forKey: @"History"];
}
- (void) sortTorrents
{
//remember selected rows if needed
NSArray * selectedTorrents = nil;
int numSelected = [fTableView numberOfSelectedRows];
if (numSelected > 0 && numSelected < [fTorrents count])
selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:
@"name" ascending: YES] autorelease],
* dateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
@"date" ascending: YES] autorelease];
NSArray * descriptors;
if ([fSortType isEqualToString: @"Name"])
descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, dateDescriptor, nil];
else if ([fSortType isEqualToString: @"State"])
{
NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
@"stateSortKey" ascending: NO] autorelease];
descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, nameDescriptor, dateDescriptor, nil];
}
else if ([fSortType isEqualToString: @"Progress"])
{
NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
@"progressSortKey" ascending: YES] autorelease];
descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, dateDescriptor, nil];
}
else
descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
[fTorrents sortUsingDescriptors: descriptors];
[descriptors release];
[fTableView reloadData];
//set selected rows if needed
if (selectedTorrents)
{
Torrent * torrent;
NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
while ((torrent = [enumerator nextObject]))
[indexSet addIndex: [fTorrents indexOfObject: torrent]];
[fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
[indexSet release];
}
}
- (void) setSort: (id) sender
{
NSMenuItem * prevSortItem;
if ([fSortType isEqualToString: @"Name"])
prevSortItem = fNameSortItem;
else if ([fSortType isEqualToString: @"State"])
prevSortItem = fStateSortItem;
else if ([fSortType isEqualToString: @"Progress"])
prevSortItem = fProgressSortItem;
else
prevSortItem = fDateSortItem;
if (sender == prevSortItem)
return;
[prevSortItem setState: NSOffState];
[sender setState: NSOnState];
[fSortType release];
if (sender == fNameSortItem)
fSortType = [[NSString alloc] initWithString: @"Name"];
else if (sender == fStateSortItem)
fSortType = [[NSString alloc] initWithString: @"State"];
else if (sender == fProgressSortItem)
fSortType = [[NSString alloc] initWithString: @"Progress"];
else
fSortType = [[NSString alloc] initWithString: @"Date"];
[fDefaults setObject: fSortType forKey: @"Sort"];
[self sortTorrents];
2006-01-12 17:43:21 +00:00
}
- (void) setLimitGlobalEnabled: (id) sender
{
[fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem)
? @"Upload" : @"Download"];
}
- (void) setQuickLimitGlobal: (id) sender
{
NSString * title = [sender title];
[fPrefsController setQuickLimit: [[title substringToIndex: [title length]
- [@" KB/s" length]] intValue]
type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
}
- (void) limitGlobalChange: (NSNotification *) notification
{
NSDictionary * dict = [notification object];
BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
int limit = [[dict objectForKey: @"Limit"] intValue];
NSMenuItem * limitItem, * noLimitItem;
if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
{
limitItem = fUploadLimitItem;
noLimitItem = fUploadNoLimitItem;
}
else
{
limitItem = fDownloadLimitItem;
noLimitItem = fDownloadNoLimitItem;
}
[limitItem setState: enable ? NSOnState : NSOffState];
[noLimitItem setState: !enable ? NSOnState : NSOffState];
[limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
[[dict objectForKey: @"Limit"] intValue]]];
[dict release];
}
- (void) setRatioGlobalEnabled: (id) sender
{
[fPrefsController setRatioEnabled: sender == fRatioSetItem];
}
- (void) setQuickRatioGlobal: (id) sender
{
[fPrefsController setQuickRatio: [[sender title] floatValue]];
}
- (void) ratioGlobalChange: (NSNotification *) notification
{
NSDictionary * dict = [notification object];
BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
[fRatioSetItem setState: enable ? NSOnState : NSOffState];
[fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
[fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
[[dict objectForKey: @"Ratio"] floatValue]]];
[dict release];
}
- (void) ratioSingleChange: (NSNotification *) notification
{
if ([fSortType isEqualToString: @"State"])
[self sortTorrents];
//update info for changed ratio setting
NSArray * torrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
if ([torrents containsObject: [notification object]])
[fInfoController updateInfoForTorrents: torrents];
}
- (int) numberOfRowsInTableView: (NSTableView *) t
2006-01-12 17:43:21 +00:00
{
return [fTorrents count];
2006-01-12 17:43:21 +00:00
}
- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
forTableColumn: (NSTableColumn *) tableColumn row: (int) row
2006-01-12 17:43:21 +00:00
{
[cell setTorrent: [fTorrents objectAtIndex: row]];
2006-01-12 17:43:21 +00:00
}
- (BOOL) tableView: (NSTableView *) t acceptDrop:
(id <NSDraggingInfo>) info row: (int) row dropOperation:
(NSTableViewDropOperation) operation
{
[self application: NSApp openFiles: [[[info draggingPasteboard]
propertyListForType: NSFilenamesPboardType]
pathsMatchingExtensions: [NSArray arrayWithObject: @"torrent"]]];
2006-01-12 17:43:21 +00:00
return YES;
}
- (NSDragOperation) tableView: (NSTableView *) t validateDrop:
(id <NSDraggingInfo>) info proposedRow: (int) row
proposedDropOperation: (NSTableViewDropOperation) operation
{
NSPasteboard * pasteboard = [info draggingPasteboard];
if (![[pasteboard types] containsObject: NSFilenamesPboardType]
|| [[[pasteboard propertyListForType: NSFilenamesPboardType]
pathsMatchingExtensions: [NSArray arrayWithObject: @"torrent"]]
count] == 0)
return NSDragOperationNone;
[fTableView setDropRow: [fTableView numberOfRows] dropOperation: NSTableViewDropAbove];
2006-01-12 17:43:21 +00:00
return NSDragOperationGeneric;
}
- (void) tableViewSelectionDidChange: (NSNotification *) notification
{
[fInfoController updateInfoForTorrents: [self torrentsAtIndexes:
[fTableView selectedRowIndexes]]];
}
- (void) toggleStatusBar: (id) sender
{
[self showStatusBar: !fStatusBarVisible animate: YES];
[fDefaults setBool: fStatusBarVisible forKey: @"StatusBar"];
}
- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2006-01-12 17:43:21 +00:00
{
if (show == fStatusBarVisible)
return;
NSRect frame = [fWindow frame];
float heightChange = [fStatusBar frame].size.height;
if (!show)
heightChange *= -1;
frame.size.height += heightChange;
frame.origin.y -= heightChange;
fStatusBarVisible = !fStatusBarVisible;
//reloads stats
[self torrentNumberChanged];
[self updateUI: nil];
//set views to not autoresize
unsigned int statsMask = [fStatusBar autoresizingMask];
unsigned int scrollMask = [fScrollView autoresizingMask];
[fStatusBar setAutoresizingMask: 0];
[fScrollView setAutoresizingMask: 0];
[fWindow setFrame: frame display: YES animate: animate];
//re-enable autoresize
[fStatusBar setAutoresizingMask: statsMask];
[fScrollView setAutoresizingMask: scrollMask];
//change min size
NSSize minSize = [fWindow contentMinSize];
minSize.height += heightChange;
[fWindow setContentMinSize: minSize];
2006-01-12 17:43:21 +00:00
}
- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
(NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
{
2006-01-12 18:57:23 +00:00
NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
2006-01-12 17:43:21 +00:00
if( [ident isEqualToString: TOOLBAR_OPEN] )
{
[item setLabel: @"Open"];
[item setPaletteLabel: @"Open Torrent Files"];
[item setToolTip: @"Open torrent files"];
2006-01-12 18:20:48 +00:00
[item setImage: [NSImage imageNamed: @"Open.png"]];
[item setTarget: self];
[item setAction: @selector( openShowSheet: )];
2006-01-12 17:43:21 +00:00
}
else if( [ident isEqualToString: TOOLBAR_REMOVE] )
{
[item setLabel: @"Remove"];
[item setPaletteLabel: @"Remove Selected"];
[item setToolTip: @"Remove selected torrents"];
2006-01-12 18:20:48 +00:00
[item setImage: [NSImage imageNamed: @"Remove.png"]];
[item setTarget: self];
2006-01-12 18:54:46 +00:00
[item setAction: @selector( removeTorrent: )];
2006-01-12 18:20:48 +00:00
}
2006-01-12 17:43:21 +00:00
else if( [ident isEqualToString: TOOLBAR_INFO] )
{
[item setLabel: @"Inspector"];
[item setPaletteLabel: @"Show/Hide Inspector"];
[item setToolTip: @"Display torrent inspector"];
2006-01-12 18:20:48 +00:00
[item setImage: [NSImage imageNamed: @"Info.png"]];
[item setTarget: self];
[item setAction: @selector( showInfo: )];
}
else if( [ident isEqualToString: TOOLBAR_PAUSE_ALL] )
{
[item setLabel: @"Pause All"];
[item setPaletteLabel: [item label]];
[item setToolTip: @"Pause all torrents"];
[item setImage: [NSImage imageNamed: @"PauseAll.png"]];
[item setTarget: self];
[item setAction: @selector( stopAllTorrents: )];
2006-01-12 17:43:21 +00:00
}
2006-01-12 18:54:46 +00:00
else if( [ident isEqualToString: TOOLBAR_RESUME_ALL] )
{
[item setLabel: @"Resume All"];
[item setPaletteLabel: [item label]];
[item setToolTip: @"Resume all torrents"];
[item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
2006-01-12 18:54:46 +00:00
[item setTarget: self];
[item setAction: @selector( resumeAllTorrents: )];
}
else if( [ident isEqualToString: TOOLBAR_PAUSE_SELECTED] )
2006-01-12 18:54:46 +00:00
{
[item setLabel: @"Pause"];
[item setPaletteLabel: @"Pause Selected"];
[item setToolTip: @"Pause selected torrents"];
2006-06-07 20:10:15 +00:00
[item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
2006-01-12 18:54:46 +00:00
[item setTarget: self];
[item setAction: @selector( stopTorrent: )];
}
else if( [ident isEqualToString: TOOLBAR_RESUME_SELECTED] )
{
[item setLabel: @"Resume"];
[item setPaletteLabel: @"Resume Selected"];
[item setToolTip: @"Resume selected torrents"];
2006-06-07 20:10:15 +00:00
[item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
[item setTarget: self];
[item setAction: @selector( resumeTorrent: )];
2006-01-12 18:54:46 +00:00
}
2006-01-12 17:43:21 +00:00
else
{
[item release];
2006-04-07 13:09:19 +00:00
return nil;
2006-01-12 17:43:21 +00:00
}
return item;
}
- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
{
2006-01-12 18:54:46 +00:00
return [NSArray arrayWithObjects:
TOOLBAR_OPEN, TOOLBAR_REMOVE,
TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2006-01-12 18:57:23 +00:00
TOOLBAR_INFO,
2006-01-12 18:54:46 +00:00
NSToolbarSeparatorItemIdentifier,
NSToolbarSpaceItemIdentifier,
NSToolbarFlexibleSpaceItemIdentifier,
NSToolbarCustomizeToolbarItemIdentifier, nil];
2006-01-12 17:43:21 +00:00
}
- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
{
2006-01-12 18:54:46 +00:00
return [NSArray arrayWithObjects:
TOOLBAR_OPEN, TOOLBAR_REMOVE,
2006-01-12 18:57:23 +00:00
NSToolbarSeparatorItemIdentifier,
TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
2006-01-12 18:54:46 +00:00
NSToolbarFlexibleSpaceItemIdentifier,
TOOLBAR_INFO, nil];
2006-01-12 18:54:46 +00:00
}
- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2006-01-12 18:57:23 +00:00
{
SEL action = [toolbarItem action];
2006-01-12 18:57:23 +00:00
//enable remove item
if (action == @selector(removeTorrent:))
2006-04-07 13:09:19 +00:00
return [fTableView numberOfSelectedRows] > 0;
2006-03-23 12:39:39 +00:00
//enable pause all item
if (action == @selector(stopAllTorrents:))
{
Torrent * torrent;
NSEnumerator * enumerator = [fTorrents objectEnumerator];
while( ( torrent = [enumerator nextObject] ) )
if( [torrent isActive] )
return YES;
return NO;
}
//enable resume all item
if (action == @selector(resumeAllTorrents:))
2006-03-23 12:39:39 +00:00
{
Torrent * torrent;
NSEnumerator * enumerator = [fTorrents objectEnumerator];
2006-03-23 12:39:39 +00:00
while( ( torrent = [enumerator nextObject] ) )
if( [torrent isPaused] )
return YES;
return NO;
}
//enable pause item
if( action == @selector(stopTorrent:) )
2006-03-23 12:39:39 +00:00
{
Torrent * torrent;
NSIndexSet * indexSet = [fTableView selectedRowIndexes];
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
if ([torrent isActive])
return YES;
}
return NO;
}
//enable resume item
if( action == @selector(resumeTorrent:) )
{
Torrent * torrent;
NSIndexSet * indexSet = [fTableView selectedRowIndexes];
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
if ([torrent isPaused])
2006-03-23 12:39:39 +00:00
return YES;
}
2006-03-23 12:39:39 +00:00
return NO;
}
2006-01-12 18:57:23 +00:00
return YES;
}
- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
2006-01-12 18:54:46 +00:00
{
SEL action = [menuItem action];
2006-06-10 04:12:40 +00:00
//only enable some items if it is in a context menu or the window is useable
BOOL canUseMenu = [[[menuItem menu] title] isEqualToString: @"Context"]
|| [fWindow isKeyWindow];
2006-03-23 12:39:39 +00:00
2006-01-12 18:54:46 +00:00
//enable show info
if (action == @selector(showInfo:))
2006-01-12 18:54:46 +00:00
{
NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
if (![[menuItem title] isEqualToString: title])
[menuItem setTitle: title];
2006-01-12 18:57:23 +00:00
return YES;
2006-01-12 18:54:46 +00:00
}
if (action == @selector(setInfoTab:))
return [[fInfoController window] isVisible];
//enable toggle status bar
if (action == @selector(toggleStatusBar:))
{
NSString * title = fStatusBarVisible ? @"Hide Status Bar" : @"Show Status Bar";
if (![[menuItem title] isEqualToString: title])
[menuItem setTitle: title];
2006-06-10 04:12:40 +00:00
return canUseMenu;
}
//enable resume all item
if (action == @selector(resumeAllTorrents:))
2006-03-23 12:39:39 +00:00
{
Torrent * torrent;
2006-04-07 13:09:19 +00:00
NSEnumerator * enumerator = [fTorrents objectEnumerator];
2006-03-23 12:39:39 +00:00
while( ( torrent = [enumerator nextObject] ) )
if( [torrent isPaused] )
return YES;
return NO;
}
//enable pause all item
if (action == @selector(stopAllTorrents:))
2006-03-23 12:39:39 +00:00
{
2006-04-07 13:09:19 +00:00
Torrent * torrent;
NSEnumerator * enumerator = [fTorrents objectEnumerator];
2006-03-23 12:39:39 +00:00
while( ( torrent = [enumerator nextObject] ) )
if( [torrent isActive] )
return YES;
return NO;
}
if (action == @selector(revealFile:))
2006-03-23 12:39:39 +00:00
{
2006-06-10 04:12:40 +00:00
return canUseMenu && [fTableView numberOfSelectedRows] > 0;
2006-03-23 12:39:39 +00:00
}
2006-01-12 18:54:46 +00:00
//enable remove items
if (action == @selector(removeTorrent:) || action == @selector(removeTorrentDeleteData:))
2006-01-12 18:57:23 +00:00
{
BOOL active = NO;
Torrent * torrent;
NSIndexSet * indexSet = [fTableView selectedRowIndexes];
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
if ([torrent isActive])
{
active = YES;
break;
}
}
2006-01-12 18:57:23 +00:00
//append or remove ellipsis when needed
NSString * title = [menuItem title];
if (active && [fDefaults boolForKey: @"CheckRemove"])
2006-01-12 18:57:23 +00:00
{
if (![title hasSuffix: NS_ELLIPSIS])
[menuItem setTitle: [title stringByAppendingString: NS_ELLIPSIS]];
2006-01-12 18:57:23 +00:00
}
else
{
if ([title hasSuffix: NS_ELLIPSIS])
[menuItem setTitle: [title substringToIndex:
[title rangeOfString: NS_ELLIPSIS].location]];
2006-01-12 18:57:23 +00:00
}
2006-06-10 04:12:40 +00:00
return canUseMenu && [fTableView numberOfSelectedRows] > 0;
2006-04-07 13:09:19 +00:00
}
//enable pause item
if( action == @selector(stopTorrent:) )
{
2006-06-10 04:12:40 +00:00
if (!canUseMenu)
return NO;
Torrent * torrent;
NSIndexSet * indexSet = [fTableView selectedRowIndexes];
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
if ([torrent isActive])
return YES;
}
return NO;
}
//enable resume item
2006-04-07 13:09:19 +00:00
if( action == @selector(resumeTorrent:) )
{
2006-06-10 04:12:40 +00:00
if (!canUseMenu)
return NO;
Torrent * torrent;
NSIndexSet * indexSet = [fTableView selectedRowIndexes];
unsigned int i;
for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
{
torrent = [fTorrents objectAtIndex: i];
if ([torrent isPaused])
return YES;
}
return NO;
2006-01-12 18:54:46 +00:00
}
//enable resume item
if (action == @selector(setSort:) || (action == @selector(advancedChanged:)))
2006-06-10 04:12:40 +00:00
return canUseMenu;
//enable copy torrent file item
if( action == @selector(copyTorrentFile:) )
{
return canUseMenu && [fTableView numberOfSelectedRows] > 0;
}
2006-03-23 12:39:39 +00:00
2006-01-12 18:57:23 +00:00
return YES;
2006-01-12 17:43:21 +00:00
}
- (void) sleepCallBack: (natural_t) messageType argument:
(void *) messageArgument
{
NSEnumerator * enumerator;
2006-03-23 12:39:39 +00:00
Torrent * torrent;
BOOL active;
2006-01-12 17:43:21 +00:00
switch( messageType )
{
case kIOMessageSystemWillSleep:
/* Close all connections before going to sleep and remember
we should resume when we wake up */
[fTorrents makeObjectsPerformSelector: @selector(sleep)];
2006-03-23 12:39:39 +00:00
/* Wait for torrents to stop (5 seconds timeout) */
NSDate * start = [NSDate date];
enumerator = [fTorrents objectEnumerator];
while( ( torrent = [enumerator nextObject] ) )
{
while( [[NSDate date] timeIntervalSinceDate: start] < 5 &&
![torrent isPaused] )
2006-01-12 17:43:21 +00:00
{
2006-03-23 12:39:39 +00:00
usleep( 100000 );
[torrent update];
2006-01-12 17:43:21 +00:00
}
}
IOAllowPowerChange( fRootPort, (long) messageArgument );
break;
case kIOMessageCanSystemSleep:
/* Prevent idle sleep unless all paused */
active = NO;
enumerator = [fTorrents objectEnumerator];
while ((torrent = [enumerator nextObject]))
if ([torrent isActive])
{
active = YES;
break;
}
if (active)
IOCancelPowerChange( fRootPort, (long) messageArgument );
else
IOAllowPowerChange( fRootPort, (long) messageArgument );
2006-01-12 17:43:21 +00:00
break;
case kIOMessageSystemHasPoweredOn:
/* Resume download after we wake up */
[fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2006-01-12 17:43:21 +00:00
break;
}
}
- (NSRect) windowWillUseStandardFrame: (NSWindow *) w
defaultFrame: (NSRect) defaultFrame
{
NSRect windowRect = [fWindow frame];
int count = [fTorrents count];
float newHeight = windowRect.size.height - [fScrollView frame].size.height
+ count * ([fTableView rowHeight] + [fTableView intercellSpacing].height) + 30.0;
2006-01-12 17:43:21 +00:00
float minHeight = [fWindow minSize].height;
if (newHeight < minHeight)
newHeight = minHeight;
2006-01-12 17:43:21 +00:00
windowRect.origin.y -= (newHeight - windowRect.size.height);
windowRect.size.height = newHeight;
2006-01-12 17:43:21 +00:00
return windowRect;
2006-01-12 17:43:21 +00:00
}
- (void) showMainWindow: (id) sender
{
2006-01-12 18:57:23 +00:00
[fWindow makeKeyAndOrderFront: nil];
2006-01-12 17:43:21 +00:00
}
- (void) windowDidBecomeKey: (NSNotification *) notification
{
fCompleted = 0;
}
2006-01-12 17:43:21 +00:00
- (void) linkHomepage: (id) sender
{
[[NSWorkspace sharedWorkspace] openURL: [NSURL
2006-01-12 18:57:23 +00:00
URLWithString: WEBSITE_URL]];
2006-01-12 17:43:21 +00:00
}
- (void) linkForums: (id) sender
{
[[NSWorkspace sharedWorkspace] openURL: [NSURL
2006-01-12 18:57:23 +00:00
URLWithString: FORUM_URL]];
2006-01-12 18:47:30 +00:00
}
2006-01-12 18:40:47 +00:00
- (void) notifyGrowl: (NSString * ) file
2006-01-12 18:33:20 +00:00
{
2006-01-12 18:40:47 +00:00
NSString * growlScript;
NSAppleScript * appleScript;
NSDictionary * error;
2006-01-12 18:47:30 +00:00
2006-01-12 18:57:23 +00:00
if( !fHasGrowl )
2006-01-12 18:47:30 +00:00
return;
2006-03-23 12:39:39 +00:00
2006-01-12 18:40:47 +00:00
growlScript = [NSString stringWithFormat:
@"tell application \"System Events\"\n"
" if exists application process \"GrowlHelperApp\" then\n"
" tell application \"GrowlHelperApp\"\n "
" notify with name \"Download Complete\""
" title \"Download Complete\""
" description \"%@\""
" application name \"Transmission\"\n"
" end tell\n"
" end if\n"
"end tell", file];
appleScript = [[NSAppleScript alloc] initWithSource: growlScript];
if( ![appleScript executeAndReturnError: &error] )
{
NSLog( @"Growl notify failed" );
2006-01-12 18:40:47 +00:00
}
[appleScript release];
2006-01-12 18:33:20 +00:00
}
2006-01-12 18:40:47 +00:00
- (void) growlRegister: (id) sender
2006-03-23 12:39:39 +00:00
{
2006-01-12 18:40:47 +00:00
NSString * growlScript;
NSAppleScript * appleScript;
NSDictionary * error;
2006-01-12 18:47:30 +00:00
2006-01-12 18:57:23 +00:00
if( !fHasGrowl )
2006-01-12 18:47:30 +00:00
return;
2006-03-23 12:39:39 +00:00
2006-01-12 18:40:47 +00:00
growlScript = [NSString stringWithFormat:
@"tell application \"System Events\"\n"
" if exists application process \"GrowlHelperApp\" then\n"
" tell application \"GrowlHelperApp\"\n"
" register as application \"Transmission\" "
" all notifications {\"Download Complete\"}"
" default notifications {\"Download Complete\"}"
" icon of application \"Transmission\"\n"
" end tell\n"
" end if\n"
"end tell"];
2006-03-23 12:39:39 +00:00
2006-01-12 18:40:47 +00:00
appleScript = [[NSAppleScript alloc] initWithSource: growlScript];
if( ![appleScript executeAndReturnError: &error] )
{
NSLog( @"Growl registration failed" );
2006-01-12 18:40:47 +00:00
}
[appleScript release];
2006-01-12 18:33:20 +00:00
}
- (void) checkUpdate: (id) sender
2006-01-29 22:01:08 +00:00
{
[fPrefsController checkUpdate];
2006-01-29 22:01:08 +00:00
}
- (void) prepareForUpdate: (NSNotification *) notification
2006-01-29 22:01:08 +00:00
{
fUpdateInProgress = YES;
2006-01-29 22:01:08 +00:00
}
2006-01-12 17:43:21 +00:00
@end