source: branches/1.5x/macosx/Controller.m @ 7756

Last change on this file since 7756 was 7756, checked in by livings124, 12 years ago

(1.5x) streamline the filter button resize code a bit

  • Property svn:keywords set to Date Rev Author Id
File size: 159.6 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 7756 2009-01-19 22:16:19Z livings124 $
3 *
4 * Copyright (c) 2005-2008 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#import <IOKit/pwr_mgt/IOPMLib.h>
27
28#import "Controller.h"
29#import "Torrent.h"
30#import "TorrentGroup.h"
31#import "TorrentCell.h"
32#import "TorrentTableView.h"
33#import "CreatorWindowController.h"
34#import "StatsWindowController.h"
35#import "QuickLookController.h"
36#import "GroupsWindowController.h"
37#import "GroupsController.h"
38#import "AboutWindowController.h"
39#import "ButtonToolbarItem.h"
40#import "GroupToolbarItem.h"
41#import "ToolbarSegmentedCell.h"
42#import "BlocklistDownloader.h"
43#import "StatusBarView.h"
44#import "FilterButton.h"
45#import "MenuLabel.h"
46#import "NSApplicationAdditions.h"
47#import "NSStringAdditions.h"
48#import "NSMenuAdditions.h"
49#import "ExpandedPathToPathTransformer.h"
50#import "ExpandedPathToIconTransformer.h"
51#import "SpeedLimitToTurtleIconTransformer.h"
52
53#import "bencode.h"
54#import "utils.h"
55
56#import "UKKQueue.h"
57#import <Sparkle/Sparkle.h>
58
59#define TOOLBAR_CREATE                  @"Toolbar Create"
60#define TOOLBAR_OPEN_FILE               @"Toolbar Open"
61#define TOOLBAR_OPEN_WEB                @"Toolbar Open Web"
62#define TOOLBAR_REMOVE                  @"Toolbar Remove"
63#define TOOLBAR_INFO                    @"Toolbar Info"
64#define TOOLBAR_PAUSE_ALL               @"Toolbar Pause All"
65#define TOOLBAR_RESUME_ALL              @"Toolbar Resume All"
66#define TOOLBAR_PAUSE_RESUME_ALL        @"Toolbar Pause / Resume All"
67#define TOOLBAR_PAUSE_SELECTED          @"Toolbar Pause Selected"
68#define TOOLBAR_RESUME_SELECTED         @"Toolbar Resume Selected"
69#define TOOLBAR_PAUSE_RESUME_SELECTED   @"Toolbar Pause / Resume Selected"
70#define TOOLBAR_FILTER                  @"Toolbar Toggle Filter"
71#define TOOLBAR_QUICKLOOK               @"Toolbar QuickLook"
72
73typedef enum
74{
75    TOOLBAR_PAUSE_TAG = 0,
76    TOOLBAR_RESUME_TAG = 1
77} toolbarGroupTag;
78
79#define SORT_DATE       @"Date"
80#define SORT_NAME       @"Name"
81#define SORT_STATE      @"State"
82#define SORT_PROGRESS   @"Progress"
83#define SORT_TRACKER    @"Tracker"
84#define SORT_ORDER      @"Order"
85#define SORT_ACTIVITY   @"Activity"
86
87typedef enum
88{
89    SORT_ORDER_TAG = 0,
90    SORT_DATE_TAG = 1,
91    SORT_NAME_TAG = 2,
92    SORT_PROGRESS_TAG = 3,
93    SORT_STATE_TAG = 4,
94    SORT_TRACKER_TAG = 5,
95    SORT_ACTIVITY_TAG = 6
96} sortTag;
97
98#define FILTER_NONE     @"None"
99#define FILTER_ACTIVE   @"Active"
100#define FILTER_DOWNLOAD @"Download"
101#define FILTER_SEED     @"Seed"
102#define FILTER_PAUSE    @"Pause"
103
104#define FILTER_TYPE_NAME    @"Name"
105#define FILTER_TYPE_TRACKER @"Tracker"
106
107#define FILTER_TYPE_TAG_NAME    401
108#define FILTER_TYPE_TAG_TRACKER 402
109
110#define GROUP_FILTER_ALL_TAG    -2
111
112#define STATUS_RATIO_TOTAL      @"RatioTotal"
113#define STATUS_RATIO_SESSION    @"RatioSession"
114#define STATUS_TRANSFER_TOTAL   @"TransferTotal"
115#define STATUS_TRANSFER_SESSION @"TransferSession"
116
117typedef enum
118{
119    STATUS_RATIO_TOTAL_TAG = 0,
120    STATUS_RATIO_SESSION_TAG = 1,
121    STATUS_TRANSFER_TOTAL_TAG = 2,
122    STATUS_TRANSFER_SESSION_TAG = 3
123} statusTag;
124
125#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
126#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
127#define GROWL_AUTO_ADD          @"Torrent Auto Added"
128#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
129
130#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
131
132#define ROW_HEIGHT_REGULAR      62.0
133#define ROW_HEIGHT_SMALL        38.0
134#define WINDOW_REGULAR_WIDTH    468.0
135
136#define SEARCH_FILTER_MIN_WIDTH 48.0
137#define SEARCH_FILTER_MAX_WIDTH 95.0
138
139#define UPDATE_UI_SECONDS   1.0
140
141#define DOCK_SEEDING_TAG        101
142#define DOCK_DOWNLOADING_TAG    102
143
144#define SUPPORT_FOLDER  @"/Library/Application Support/Transmission/Transfers.plist"
145
146#define WEBSITE_URL @"http://www.transmissionbt.com/"
147#define FORUM_URL   @"http://forum.transmissionbt.com/"
148#define TRAC_URL   @"http://trac.transmissionbt.com/"
149#define DONATE_URL  @"http://www.transmissionbt.com/donate.php"
150
151static tr_rpc_callback_status rpcCallback(tr_session * handle UNUSED, tr_rpc_callback_type type, struct tr_torrent * torrentStruct, void * controller)
152{
153    [(Controller *)controller rpcCallback: type forTorrentStruct: torrentStruct];
154    return TR_RPC_NOREMOVE; //we'll do the remove manually
155}
156
157static void sleepCallback(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
158{
159    [(Controller *)controller sleepCallback: messageType argument: messageArgument];
160}
161
162@implementation Controller
163
164+ (void) initialize
165{
166    //make sure another Transmission.app isn't running already
167    NSString * bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
168    int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
169
170    NSDictionary * dic;
171    NSEnumerator * enumerator = [[[NSWorkspace sharedWorkspace] launchedApplications] objectEnumerator];
172    while ((dic = [enumerator nextObject]))
173    {
174        if ([[dic objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]
175            && [[dic objectForKey: @"NSApplicationProcessIdentifier"] intValue] != processIdentifier)
176        {
177            NSAlert * alert = [[NSAlert alloc] init];
178            [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Transmission already running alert -> button")];
179            [alert setMessageText: NSLocalizedString(@"Transmission is already running.",
180                                                    "Transmission already running alert -> title")];
181            [alert setInformativeText: NSLocalizedString(@"There is already a copy of Transmission running. "
182                "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message")];
183            [alert setAlertStyle: NSWarningAlertStyle];
184           
185            [alert runModal];
186            [alert release];
187           
188            //kill ourselves right away
189            exit(0);
190        }
191    }
192   
193    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
194        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
195   
196    //set custom value transformers
197    ExpandedPathToPathTransformer * pathTransformer = [[[ExpandedPathToPathTransformer alloc] init] autorelease];
198    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
199   
200    ExpandedPathToIconTransformer * iconTransformer = [[[ExpandedPathToIconTransformer alloc] init] autorelease];
201    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
202   
203    SpeedLimitToTurtleIconTransformer * speedLimitIconTransformer = [[[SpeedLimitToTurtleIconTransformer alloc] init] autorelease];
204    [NSValueTransformer setValueTransformer: speedLimitIconTransformer forName: @"SpeedLimitToTurtleIconTransformer"];
205}
206
207- (id) init
208{
209    if ((self = [super init]))
210    {
211        fDefaults = [NSUserDefaults standardUserDefaults];
212       
213        tr_benc settings;
214        tr_bencInitDict(&settings, 21);
215        tr_sessionGetDefaultSettings(&settings);
216       
217        tr_bencDictAddInt(&settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, [fDefaults boolForKey: @"Blocklist"]);
218       
219        #warning update when changing in prefs
220        tr_bencDictAddStr(&settings, TR_PREFS_KEY_DOWNLOAD_DIR, [[[fDefaults stringForKey: @"DownloadFolder"]
221                                                                    stringByExpandingTildeInPath] UTF8String]);
222       
223        tr_bencDictAddInt(&settings, TR_PREFS_KEY_MSGLEVEL, [fDefaults boolForKey: @"MessageLevel"]);
224        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, [fDefaults integerForKey: @"PeersTotal"]);
225        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_TORRENT, [fDefaults integerForKey: @"PeersTorrent"]);
226       
227        const BOOL randomPort = /*[fDefaults boolForKey: @"RandomPort"]*/NO;
228        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_PORT_RANDOM_ENABLED, randomPort);
229        if (!randomPort)
230            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_PORT, [fDefaults integerForKey: @"BindPort"]);
231       
232        //hidden pref
233        if ([fDefaults objectForKey: @"PeerSocketTOS"])
234            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_SOCKET_TOS, [fDefaults integerForKey: @"PeerSocketTOS"]);
235       
236        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEX_ENABLED, [fDefaults boolForKey: @"PEXGlobal"]);
237        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PORT_FORWARDING, [fDefaults boolForKey: @"NatTraversal"]);
238        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PROXY_AUTH_ENABLED, [fDefaults boolForKey: @"ProxyAuthorize"]);
239        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PROXY_ENABLED, [fDefaults boolForKey: @"Proxy"]);
240        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PROXY_PORT, [fDefaults integerForKey: @"ProxyPort"]);
241        tr_bencDictAddStr(&settings, TR_PREFS_KEY_PROXY, [[fDefaults stringForKey: @"ProxyAddress"] UTF8String]);
242        tr_bencDictAddStr(&settings, TR_PREFS_KEY_PROXY_USERNAME,  [[fDefaults stringForKey: @"ProxyUsername"] UTF8String]);
243        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED,  [fDefaults boolForKey: @"RPCAuthorize"]);
244        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_ENABLED,  [fDefaults boolForKey: @"RPC"]);
245        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_PORT,  [fDefaults integerForKey: @"RPCPort"]);
246        tr_bencDictAddStr(&settings, TR_PREFS_KEY_RPC_USERNAME,  [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
247        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_WHITELIST_ENABLED,  [fDefaults boolForKey: @"RPCUseWhitelist"]);
248       
249        fLib = tr_sessionInit("macosx", tr_getDefaultConfigDir("Transmission"), YES, &settings);
250        tr_bencFree(&settings);       
251        [NSApp setDelegate: self];
252       
253        fTorrents = [[NSMutableArray alloc] init];
254        fDisplayedTorrents = [[NSMutableArray alloc] init];
255       
256        fMessageController = [[MessageWindowController alloc] init];
257        fInfoController = [[InfoWindowController alloc] init];
258       
259        [PrefsController setHandle: fLib];
260        fPrefsController = [[PrefsController alloc] init];
261       
262        [QuickLookController quickLookControllerInitializeWithController: self infoController: fInfoController];
263       
264        fSoundPlaying = NO;
265       
266        tr_sessionSetRPCCallback(fLib, rpcCallback, self);
267       
268        [GrowlApplicationBridge setGrowlDelegate: self];
269       
270        [[UKKQueue sharedFileWatcher] setDelegate: self];
271       
272        SUUpdater * updater = [SUUpdater sharedUpdater];
273        [updater setDelegate: self];
274        fUpdateInProgress = NO;
275       
276        //reset old Sparkle settings from previous versions
277        [fDefaults removeObjectForKey: @"SUScheduledCheckInterval"];
278        if ([fDefaults objectForKey: @"CheckForUpdates"])
279        {
280            [updater setAutomaticallyChecksForUpdates: [fDefaults boolForKey: @"CheckForUpdates"]];
281            [fDefaults removeObjectForKey: @"CheckForUpdates"];
282        }
283    }
284    return self;
285}
286
287- (void) awakeFromNib
288{
289    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"TRMainToolbar"];
290    [toolbar setDelegate: self];
291    [toolbar setAllowsUserCustomization: YES];
292    [toolbar setAutosavesConfiguration: YES];
293    [toolbar setDisplayMode: NSToolbarDisplayModeIconOnly];
294    [fWindow setToolbar: toolbar];
295    [toolbar release];
296   
297    [fWindow setDelegate: self]; //do manually to avoid placement issue
298   
299    [fWindow makeFirstResponder: fTableView];
300    [fWindow setExcludedFromWindowsMenu: YES];
301   
302    //set table size
303    if ([fDefaults boolForKey: @"SmallView"])
304        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
305   
306    //window min height
307    NSSize contentMinSize = [fWindow contentMinSize];
308    contentMinSize.height = [[fWindow contentView] frame].size.height - [[fTableView enclosingScrollView] frame].size.height
309                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
310    [fWindow setContentMinSize: contentMinSize];
311   
312    if ([NSApp isOnLeopardOrBetter])
313    {
314        [fWindow setContentBorderThickness: [[fTableView enclosingScrollView] frame].origin.y forEdge: NSMinYEdge];
315        [[fTotalTorrentsField cell] setBackgroundStyle: NSBackgroundStyleRaised];
316       
317        [[[fActionButton menu] itemAtIndex: 0] setImage: [NSImage imageNamed: NSImageNameActionTemplate]]; //set in nib if Leopard-only
318       
319        [fBottomTigerLine removeFromSuperview];
320        [fStatusTigerField removeFromSuperview];
321        [fStatusTigerImageView removeFromSuperview];
322    }
323    else
324    {
325        [fActionButton setBezelStyle: NSSmallSquareBezelStyle];
326        [fSpeedLimitButton setBezelStyle: NSSmallSquareBezelStyle];
327       
328        //status bar
329        [fStatusButton setHidden: YES];
330        [fStatusTigerField setHidden: NO];
331        [fStatusTigerImageView setHidden: NO];
332       
333        //filter bar
334        [fNoFilterButton sizeToFit];
335       
336        NSRect activeRect = [fActiveFilterButton frame];
337        activeRect.origin.x = NSMaxX([fNoFilterButton frame]) + 1.0;
338        [fActiveFilterButton setFrame: activeRect];
339    }
340   
341    [self updateGroupsFilterButton];
342   
343    //set up filter bar
344    NSView * contentView = [fWindow contentView];
345    NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
346    [fFilterBar setHidden: YES];
347   
348    NSRect filterBarFrame = [fFilterBar frame];
349    filterBarFrame.size.width = windowSize.width;
350    [fFilterBar setFrame: filterBarFrame];
351   
352    [contentView addSubview: fFilterBar];
353    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
354
355    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
356   
357    //set up status bar
358    [fStatusBar setHidden: YES];
359   
360    [fTotalDLField setToolTip: NSLocalizedString(@"Total download speed", "Status Bar -> speed tooltip")];
361    [fTotalULField setToolTip: NSLocalizedString(@"Total upload speed", "Status Bar -> speed tooltip")];
362   
363    NSRect statusBarFrame = [fStatusBar frame];
364    statusBarFrame.size.width = windowSize.width;
365    [fStatusBar setFrame: statusBarFrame];
366   
367    [contentView addSubview: fStatusBar];
368    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
369    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
370   
371    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
372                                "Main window -> 1st bottom left button (action) tooltip")];
373    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
374                                "Main window -> 2nd bottom left button (turtle) tooltip")];
375   
376    [fTableView registerForDraggedTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE]];
377    [fWindow registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType, NSURLPboardType, nil]];
378
379    //register for sleep notifications
380    IONotificationPortRef notify;
381    io_object_t iterator;
382    if ((fRootPort = IORegisterForSystemPower(self, & notify, sleepCallback, &iterator)))
383        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
384    else
385        NSLog(@"Could not IORegisterForSystemPower");
386   
387    //load previous transfers
388    NSArray * history = [[NSArray alloc] initWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER]];
389   
390    //old version saved transfer info in prefs file
391    if (!history)
392    {
393        if ((history = [fDefaults arrayForKey: @"History"]))
394            [history retain];
395        [fDefaults removeObjectForKey: @"History"];
396    }
397   
398    if (history)
399    {
400        Torrent * torrent;
401        NSDictionary * historyItem;
402        NSEnumerator * enumerator = [history objectEnumerator];
403        while ((historyItem = [enumerator nextObject]))
404            if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
405            {
406                [fTorrents addObject: torrent];
407                [torrent release];
408            }
409       
410        [history release];
411    }
412   
413    //set filter
414    NSString * filterType = [fDefaults stringForKey: @"Filter"];
415   
416    NSButton * currentFilterButton;
417    if ([filterType isEqualToString: FILTER_ACTIVE])
418        currentFilterButton = fActiveFilterButton;
419    else if ([filterType isEqualToString: FILTER_PAUSE])
420        currentFilterButton = fPauseFilterButton;
421    else if ([filterType isEqualToString: FILTER_SEED])
422        currentFilterButton = fSeedFilterButton;
423    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
424        currentFilterButton = fDownloadFilterButton;
425    else
426    {
427        //safety
428        if (![filterType isEqualToString: FILTER_NONE])
429            [fDefaults setObject: FILTER_NONE forKey: @"Filter"];
430        currentFilterButton = fNoFilterButton;
431    }
432    [currentFilterButton setState: NSOnState];
433   
434    //set filter search type
435    NSString * filterSearchType = [fDefaults stringForKey: @"FilterSearchType"];
436   
437    NSMenu * filterSearchMenu = [[fSearchFilterField cell] searchMenuTemplate];
438    NSString * filterSearchTypeTitle;
439    if ([filterSearchType isEqualToString: FILTER_TYPE_TRACKER])
440        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_TRACKER] title];
441    else
442    {
443        //safety
444        if (![filterType isEqualToString: FILTER_TYPE_NAME])
445            [fDefaults setObject: FILTER_TYPE_NAME forKey: @"FilterSearchType"];
446        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_NAME] title];
447    }
448    [[fSearchFilterField cell] setPlaceholderString: filterSearchTypeTitle];
449   
450    fBadger = [[Badger alloc] initWithLib: fLib];
451   
452    //observe notifications
453    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
454   
455    [nc addObserver: self selector: @selector(updateUI)
456                    name: @"UpdateUI" object: nil];
457   
458    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
459                    name: @"TorrentFinishedDownloading" object: nil];
460   
461    [nc addObserver: self selector: @selector(torrentRestartedDownloading:)
462                    name: @"TorrentRestartedDownloading" object: nil];
463   
464    //avoids need of setting delegate
465    [nc addObserver: self selector: @selector(torrentTableViewSelectionDidChange:)
466                    name: NSOutlineViewSelectionDidChangeNotification object: fTableView];
467   
468    [nc addObserver: self selector: @selector(autoSpeedLimitChange:)
469                    name: @"AutoSpeedLimitChange" object: nil];
470   
471    [nc addObserver: self selector: @selector(changeAutoImport)
472                    name: @"AutoImportSettingChange" object: nil];
473   
474    [nc addObserver: self selector: @selector(setWindowSizeToFit)
475                    name: @"AutoSizeSettingChange" object: nil];
476   
477    [nc addObserver: self selector: @selector(updateForExpandCollape)
478                    name: @"OutlineExpandCollapse" object: nil];
479   
480    [nc addObserver: fWindow selector: @selector(makeKeyWindow)
481                    name: @"MakeWindowKey" object: nil];
482   
483    //check if torrent should now start
484    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
485                    name: @"TorrentStoppedForRatio" object: nil];
486   
487    [nc addObserver: self selector: @selector(updateTorrentsInQueue)
488                    name: @"UpdateQueue" object: nil];
489   
490    //open newly created torrent file
491    [nc addObserver: self selector: @selector(beginCreateFile:)
492                    name: @"BeginCreateTorrentFile" object: nil];
493   
494    //open newly created torrent file
495    [nc addObserver: self selector: @selector(openCreatedFile:)
496                    name: @"OpenCreatedTorrentFile" object: nil];
497   
498    //update when groups change
499    [nc addObserver: self selector: @selector(updateGroupsFilters:)
500                    name: @"UpdateGroups" object: nil];
501
502    //timer to update the interface every second
503    [self updateUI];
504    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
505                selector: @selector(updateUI) userInfo: nil repeats: YES];
506    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
507    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
508   
509    [self applyFilter: nil];
510   
511    [fWindow makeKeyAndOrderFront: nil];
512   
513    if ([fDefaults boolForKey: @"InfoVisible"])
514        [self showInfo: nil];
515   
516    //set up the speed limit
517    [self autoSpeedLimitChange: nil];
518}
519
520- (void) applicationDidFinishLaunching: (NSNotification *) notification
521{
522    [NSApp setServicesProvider: self];
523   
524    //register for dock icon drags
525    [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:)
526        forEventClass: kCoreEventClass andEventID: kAEOpenContents];
527   
528    //auto importing
529    [self checkAutoImportDirectory];
530}
531
532- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
533{
534    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
535        [fWindow makeKeyAndOrderFront: nil];
536    return NO;
537}
538
539- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
540{
541    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
542    {
543        NSInteger active = 0, downloading = 0;
544        Torrent * torrent;
545        NSEnumerator * enumerator = [fTorrents objectEnumerator];
546        while ((torrent = [enumerator nextObject]))
547            if ([torrent isActive] && ![torrent isStalled])
548            {
549                active++;
550                if (![torrent allDownloaded])
551                    downloading++;
552            }
553       
554        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
555        {
556            NSString * message = active == 1
557                ? NSLocalizedString(@"There is an active transfer that will be paused on quit."
558                    " The transfer will automatically resume on the next launch.", "Confirm Quit panel -> message")
559                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers that will be paused on quit."
560                    " The transfers will automatically resume on the next launch.", "Confirm Quit panel -> message"), active];
561
562            NSBeginAlertSheet(NSLocalizedString(@"Are you sure you want to quit?", "Confirm Quit panel -> title"),
563                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
564                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
565                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
566            return NSTerminateLater;
567        }
568    }
569   
570    return NSTerminateNow;
571}
572
573- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
574{
575    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
576}
577
578- (void) applicationWillTerminate: (NSNotification *) notification
579{
580    //stop blocklist download
581    if ([BlocklistDownloader isRunning])
582        [[BlocklistDownloader downloader] cancelDownload];
583   
584    //stop timers and notification checking
585    [[NSNotificationCenter defaultCenter] removeObserver: self];
586   
587    [fTimer invalidate];
588    [fSpeedLimitTimer invalidate];
589   
590    if (fAutoImportTimer)
591    {   
592        if ([fAutoImportTimer isValid])
593            [fAutoImportTimer invalidate];
594        [fAutoImportTimer release];
595    }
596   
597    [fBadger setQuitting];
598   
599    //remove all torrent downloads
600    if (fPendingTorrentDownloads)
601    {
602        NSEnumerator * downloadEnumerator = [fPendingTorrentDownloads objectEnumerator];
603        NSDictionary * downloadDict;
604        while ((downloadDict = [downloadEnumerator nextObject]))
605        {
606            NSURLDownload * download = [downloadDict objectForKey: @"Download"];
607            [download cancel];
608            [download release];
609        }
610        [fPendingTorrentDownloads removeAllObjects];
611    }
612   
613    //remember window states and close all windows
614    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
615    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
616    [self showStatusBar: NO animate: NO];
617    [self showFilterBar: NO animate: NO];
618   
619    //save history
620    [self updateTorrentHistory];
621    [fTableView saveCollapsedGroups];
622   
623    //remaining calls the same as dealloc
624    [fInfoController release];
625    [fMessageController release];
626    [fPrefsController release];
627   
628    [fTorrents release];
629    [fDisplayedTorrents release];
630   
631    [fOverlayWindow release];
632   
633    [fAutoImportedNames release];
634    [fPendingTorrentDownloads release];
635   
636    //complete cleanup
637    tr_sessionClose(fLib);
638   
639    [fBadger release]; //clears dock icon on Tiger
640}
641
642- (void) handleOpenContentsEvent: (NSAppleEventDescriptor *) event replyEvent: (NSAppleEventDescriptor *) replyEvent
643{
644    NSString * urlString = nil;
645
646    NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject];
647    if ([directObject descriptorType] == typeAEList)
648    {
649        for (NSUInteger i = 1; i <= [directObject numberOfItems]; i++)
650            if ((urlString = [[directObject descriptorAtIndex: i] stringValue]))
651                break;
652    }
653    else
654        urlString = [directObject stringValue];
655   
656    if (urlString)
657        [self openURL: [NSURL URLWithString: urlString]];
658}
659
660- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) suggestedName
661{
662    if ([[suggestedName pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
663    {
664        [download cancel];
665       
666        NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title"),
667            [NSString stringWithFormat: NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.",
668            "Download not a torrent -> message"), suggestedName,
669            [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]],
670            NSLocalizedString(@"OK", "Download not a torrent -> button"), nil, nil);
671       
672        [download release];
673    }
674    else
675        [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: [suggestedName lastPathComponent]]
676                    allowOverwrite: NO];
677}
678
679-(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path
680{
681    if (!fPendingTorrentDownloads)
682        fPendingTorrentDownloads = [[NSMutableDictionary alloc] init];
683   
684    [fPendingTorrentDownloads setObject: [NSDictionary dictionaryWithObjectsAndKeys:
685                    path, @"Path", download, @"Download", nil] forKey: [[download request] URL]];
686}
687
688- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error
689{
690    NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Torrent download error -> title"),
691        [NSString stringWithFormat: NSLocalizedString(@"The torrent could not be downloaded from %@: %@.",
692        "Torrent download failed -> message"),
693        [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
694        [error localizedDescription]], NSLocalizedString(@"OK", "Torrent download failed -> button"), nil, nil);
695   
696    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
697    if ([fPendingTorrentDownloads count] == 0)
698    {
699        [fPendingTorrentDownloads release];
700        fPendingTorrentDownloads = nil;
701    }
702   
703    [download release];
704}
705
706- (void) downloadDidFinish: (NSURLDownload *) download
707{
708    NSString * path = [[fPendingTorrentDownloads objectForKey: [[download request] URL]] objectForKey: @"Path"];
709   
710    [self openFiles: [NSArray arrayWithObject: path] addType: ADD_URL forcePath: nil];
711   
712    //delete the torrent file after opening
713    if ([NSApp isOnLeopardOrBetter])
714        [[NSFileManager defaultManager] removeItemAtPath: path error: NULL];
715    else
716        [[NSFileManager defaultManager] removeFileAtPath: path handler: nil];
717   
718    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
719    if ([fPendingTorrentDownloads count] == 0)
720    {
721        [fPendingTorrentDownloads release];
722        fPendingTorrentDownloads = nil;
723    }
724   
725    [download release];
726}
727
728- (void) application: (NSApplication *) app openFiles: (NSArray *) filenames
729{
730    [self openFiles: filenames addType: ADD_MANUAL forcePath: nil];
731}
732
733- (void) openFiles: (NSArray *) filenames addType: (addType) type forcePath: (NSString *) path
734{
735    #warning checks could probably be removed, since location is checked when starting
736    if (!path && [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]
737        && access([[[fDefaults stringForKey: @"IncompleteDownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
738    {
739        NSOpenPanel * panel = [NSOpenPanel openPanel];
740       
741        [panel setPrompt: NSLocalizedString(@"Select", "Default incomplete folder cannot be used alert -> prompt")];
742        [panel setAllowsMultipleSelection: NO];
743        [panel setCanChooseFiles: NO];
744        [panel setCanChooseDirectories: YES];
745        [panel setCanCreateDirectories: YES];
746
747        [panel setMessage: NSLocalizedString(@"The incomplete folder cannot be used. Choose a new location or cancel for none.",
748                                        "Default incomplete folder cannot be used alert -> message")];
749       
750        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: filenames, @"Filenames",
751                                                        [NSNumber numberWithInt: type], @"AddType", nil];
752       
753        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
754                didEndSelector: @selector(incompleteChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
755        return;
756    }
757   
758    if (!path && [fDefaults boolForKey: @"DownloadLocationConstant"]
759        && access([[[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
760    {
761        NSOpenPanel * panel = [NSOpenPanel openPanel];
762       
763        [panel setPrompt: NSLocalizedString(@"Select", "Default folder cannot be used alert -> prompt")];
764        [panel setAllowsMultipleSelection: NO];
765        [panel setCanChooseFiles: NO];
766        [panel setCanChooseDirectories: YES];
767        [panel setCanCreateDirectories: YES];
768
769        [panel setMessage: NSLocalizedString(@"The download folder cannot be used. Choose a new location.",
770                                        "Default folder cannot be used alert -> message")];
771       
772        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: filenames, @"Filenames",
773                                                        [NSNumber numberWithInt: type], @"AddType", nil];
774       
775        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
776                didEndSelector: @selector(downloadChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
777        return;
778    }
779   
780    torrentFileState deleteTorrentFile;
781    switch (type)
782    {
783        case ADD_CREATED:
784            deleteTorrentFile = TORRENT_FILE_SAVE;
785            break;
786        case ADD_URL:
787            deleteTorrentFile = TORRENT_FILE_DELETE;
788            break;
789        default:
790            deleteTorrentFile = TORRENT_FILE_DEFAULT;
791    }
792   
793    Torrent * torrent;
794    NSString * torrentPath;
795    tr_info info;
796    NSEnumerator * enumerator = [filenames objectEnumerator];
797    while ((torrentPath = [enumerator nextObject]))
798    {
799        //ensure torrent doesn't already exist
800        tr_ctor * ctor = tr_ctorNew(fLib);
801        tr_ctorSetMetainfoFromFile(ctor, [torrentPath UTF8String]);
802        int result = tr_torrentParse(fLib, ctor, &info);
803        if (result != TR_OK)
804        {
805            if (result == TR_EDUPLICATE)
806                [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
807            else if (result == TR_EINVALID)
808            {
809                if (type != ADD_AUTO)
810                    [self invalidOpenAlert: [torrentPath lastPathComponent]];
811            }
812            else //this shouldn't happen
813                NSLog(@"Unknown error code (%d) when attempting to open \"%@\"", result, torrentPath);
814           
815            tr_ctorFree(ctor);
816            tr_metainfoFree(&info);
817            continue;
818        }
819       
820        tr_ctorFree(ctor);
821       
822        //determine download location
823        NSString * location;
824        if (path)
825            location = [path stringByExpandingTildeInPath];
826        else if ([fDefaults boolForKey: @"DownloadLocationConstant"])
827            location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
828        else if (type != ADD_URL)
829            location = [torrentPath stringByDeletingLastPathComponent];
830        else
831            location = nil;
832       
833        //determine to show the options window
834        BOOL showWindow = type == ADD_SHOW_OPTIONS || ([fDefaults boolForKey: @"DownloadAsk"]
835                            && (info.isMultifile || ![fDefaults boolForKey: @"DownloadAskMulti"])
836                            && (type != ADD_AUTO || ![fDefaults boolForKey: @"DownloadAskManual"]));
837        tr_metainfoFree(&info);
838       
839        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath location: location
840                            deleteTorrentFile: showWindow ? TORRENT_FILE_SAVE : deleteTorrentFile lib: fLib]))
841            continue;
842       
843        //verify the data right away if it was newly created
844        if (type == ADD_CREATED)
845            [torrent resetCache];
846       
847        //add it to the "File -> Open Recent" menu
848        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
849       
850        //show the add window or add directly
851        if (showWindow || !location)
852        {
853            AddWindowController * addController = [[AddWindowController alloc] initWithTorrent: torrent destination: location
854                                                    controller: self deleteTorrent: deleteTorrentFile];
855            [addController showWindow: self];
856        }
857        else
858        {
859            [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
860           
861            [torrent update];
862            [fTorrents addObject: torrent];
863            [torrent release];
864        }
865    }
866
867    [self updateTorrentsInQueue];
868}
869
870- (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add
871{
872    Torrent * torrent = [addController torrent];
873    [addController release];
874   
875    if (add)
876    {
877        [torrent setOrderValue: [fTorrents count]]; //ensure that queue order is always sequential
878       
879        [torrent update];
880        [fTorrents addObject: torrent];
881        [torrent release];
882       
883        [self updateTorrentsInQueue];
884    }
885    else
886    {
887        [torrent closeRemoveTorrent];
888        [torrent release];
889    }
890}
891
892- (void) openCreatedFile: (NSNotification *) notification
893{
894    NSDictionary * dict = [notification userInfo];
895    [self openFiles: [NSArray arrayWithObject: [dict objectForKey: @"File"]] addType: ADD_CREATED
896                        forcePath: [dict objectForKey: @"Path"]];
897    [dict release];
898}
899
900- (void) incompleteChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
901{
902    if (code == NSOKButton)
903        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
904    else
905        [fDefaults setBool: NO forKey: @"UseIncompleteDownloadFolder"];
906   
907    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
908}
909
910- (void) downloadChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
911{
912    if (code == NSOKButton)
913    {
914        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"DownloadFolder"];
915        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
916    }
917    else
918        [dictionary release];
919}
920
921- (void) openFilesWithDict: (NSDictionary *) dictionary
922{
923    [self openFiles: [dictionary objectForKey: @"Filenames"] addType: [[dictionary objectForKey: @"AddType"] intValue] forcePath: nil];
924   
925    [dictionary release];
926}
927
928//called on by applescript
929- (void) open: (NSArray *) files
930{
931    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: files, @"Filenames",
932                                [NSNumber numberWithInt: ADD_MANUAL], @"AddType", nil];
933    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dict waitUntilDone: NO];
934}
935
936- (void) openShowSheet: (id) sender
937{
938    NSOpenPanel * panel = [NSOpenPanel openPanel];
939
940    [panel setAllowsMultipleSelection: YES];
941    [panel setCanChooseFiles: YES];
942    [panel setCanChooseDirectories: NO];
943
944    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
945        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
946        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
947}
948
949- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSNumber *) useOptions
950{
951    if (code == NSOKButton)
952    {
953        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: [panel filenames], @"Filenames",
954            [NSNumber numberWithInt: [useOptions boolValue] ? ADD_SHOW_OPTIONS : ADD_MANUAL], @"AddType", nil];
955        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
956    }
957}
958
959- (void) invalidOpenAlert: (NSString *) filename
960{
961    if (![fDefaults boolForKey: @"WarningInvalidOpen"])
962        return;
963   
964    NSAlert * alert = [[NSAlert alloc] init];
965    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"\"%@\" is not a valid torrent file.",
966                            "Open invalid alert -> title"), filename]];
967    [alert setInformativeText:
968            NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.",
969                            "Open invalid alert -> message")];
970    [alert setAlertStyle: NSWarningAlertStyle];
971    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open invalid alert -> button")];
972   
973    BOOL onLeopard = [NSApp isOnLeopardOrBetter];
974    if (onLeopard)
975        [alert setShowsSuppressionButton: YES];
976    else
977        [alert addButtonWithTitle: NSLocalizedString(@"Don't Alert Again", "Open duplicate alert -> button")];
978   
979    NSInteger result = [alert runModal];
980    if ((onLeopard ? [[alert suppressionButton] state] == NSOnState : result == NSAlertSecondButtonReturn))
981        [fDefaults setBool: NO forKey: @"WarningInvalidOpen"];
982    [alert release];
983}
984
985- (void) duplicateOpenAlert: (NSString *) name
986{
987    if (![fDefaults boolForKey: @"WarningDuplicate"])
988        return;
989   
990    NSAlert * alert = [[NSAlert alloc] init];
991    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.",
992                            "Open duplicate alert -> title"), name]];
993    [alert setInformativeText:
994            NSLocalizedString(@"The torrent file cannot be opened because it is a duplicate of an already added transfer.",
995                            "Open duplicate alert -> message")];
996    [alert setAlertStyle: NSWarningAlertStyle];
997    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate alert -> button")];
998   
999    BOOL onLeopard = [NSApp isOnLeopardOrBetter];
1000    if (onLeopard)
1001        [alert setShowsSuppressionButton: YES];
1002    else
1003        [alert addButtonWithTitle: NSLocalizedString(@"Don't Alert Again", "Open duplicate alert -> button")];
1004   
1005    NSInteger result = [alert runModal];
1006    if ((onLeopard ? [[alert suppressionButton] state] == NSOnState : result == NSAlertSecondButtonReturn))
1007        [fDefaults setBool: NO forKey: @"WarningDuplicate"];
1008    [alert release];
1009}
1010
1011- (void) openURL: (NSURL *) url
1012{
1013    [[NSURLDownload alloc] initWithRequest: [NSURLRequest requestWithURL: url] delegate: self];
1014}
1015
1016- (void) openURLShowSheet: (id) sender
1017{
1018    [NSApp beginSheet: fURLSheetWindow modalForWindow: fWindow modalDelegate: self
1019            didEndSelector: @selector(urlSheetDidEnd:returnCode:contextInfo:) contextInfo: nil];
1020}
1021
1022- (void) openURLEndSheet: (id) sender
1023{
1024    [fURLSheetWindow orderOut: sender];
1025    [NSApp endSheet: fURLSheetWindow returnCode: 1];
1026}
1027
1028- (void) openURLCancelEndSheet: (id) sender
1029{
1030    [fURLSheetWindow orderOut: sender];
1031    [NSApp endSheet: fURLSheetWindow returnCode: 0];
1032}
1033
1034- (void) controlTextDidChange: (NSNotification *) notification
1035{
1036    if ([notification object] != fURLSheetTextField)
1037        return;
1038   
1039    NSString * string = [fURLSheetTextField stringValue];
1040    BOOL enable = YES;
1041    if ([string isEqualToString: @""])
1042        enable = NO;
1043    else
1044    {
1045        NSRange prefixRange = [string rangeOfString: @"://"];
1046        if (prefixRange.location != NSNotFound && [string length] == NSMaxRange(prefixRange))
1047            enable = NO;
1048    }
1049   
1050    [fURLSheetOpenButton setEnabled: enable];
1051}
1052
1053- (void) urlSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
1054{
1055    [fURLSheetTextField selectText: self];
1056    if (returnCode != 1)
1057        return;
1058   
1059    NSString * urlString = [fURLSheetTextField stringValue];
1060    if ([urlString rangeOfString: @"://"].location == NSNotFound)
1061    {
1062        if ([urlString rangeOfString: @"."].location == NSNotFound)
1063        {
1064            NSInteger beforeCom;
1065            if ((beforeCom = [urlString rangeOfString: @"/"].location) != NSNotFound)
1066                urlString = [NSString stringWithFormat: @"http://www.%@.com/%@",
1067                                [urlString substringToIndex: beforeCom],
1068                                [urlString substringFromIndex: beforeCom + 1]];
1069            else
1070                urlString = [NSString stringWithFormat: @"http://www.%@.com/", urlString];
1071        }
1072        else
1073            urlString = [@"http://" stringByAppendingString: urlString];
1074    }
1075   
1076    NSURL * url = [NSURL URLWithString: urlString];
1077    [self performSelectorOnMainThread: @selector(openURL:) withObject: url waitUntilDone: NO];
1078}
1079
1080- (void) createFile: (id) sender
1081{
1082    [CreatorWindowController createTorrentFile: fLib];
1083}
1084
1085- (void) resumeSelectedTorrents: (id) sender
1086{
1087    [self resumeTorrents: [fTableView selectedTorrents]];
1088}
1089
1090- (void) resumeAllTorrents: (id) sender
1091{
1092    [self resumeTorrents: fTorrents];
1093}
1094
1095- (void) resumeTorrents: (NSArray *) torrents
1096{
1097    NSEnumerator * enumerator = [torrents objectEnumerator];
1098    Torrent * torrent;
1099    while ((torrent = [enumerator nextObject]))
1100        [torrent setWaitToStart: YES];
1101   
1102    [self updateTorrentsInQueue];
1103}
1104
1105- (void) resumeSelectedTorrentsNoWait:  (id) sender
1106{
1107    [self resumeTorrentsNoWait: [fTableView selectedTorrents]];
1108}
1109
1110- (void) resumeWaitingTorrents: (id) sender
1111{
1112    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1113   
1114    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1115    Torrent * torrent;
1116    while ((torrent = [enumerator nextObject]))
1117        if (![torrent isActive] && [torrent waitingToStart])
1118            [torrents addObject: torrent];
1119   
1120    [self resumeTorrentsNoWait: torrents];
1121}
1122
1123- (void) resumeTorrentsNoWait: (NSArray *) torrents
1124{
1125    //iterate through instead of all at once to ensure no conflicts
1126    NSEnumerator * enumerator = [torrents objectEnumerator];
1127    Torrent * torrent;
1128    while ((torrent = [enumerator nextObject]))
1129        [torrent startTransfer];
1130   
1131    [self updateUI];
1132    [self applyFilter: nil];
1133    [self updateTorrentHistory];
1134}
1135
1136- (void) stopSelectedTorrents: (id) sender
1137{
1138    [self stopTorrents: [fTableView selectedTorrents]];
1139}
1140
1141- (void) stopAllTorrents: (id) sender
1142{
1143    [self stopTorrents: fTorrents];
1144}
1145
1146- (void) stopTorrents: (NSArray *) torrents
1147{
1148    //don't want any of these starting then stopping
1149    NSEnumerator * enumerator = [torrents objectEnumerator];
1150    Torrent * torrent;
1151    while ((torrent = [enumerator nextObject]))
1152        [torrent setWaitToStart: NO];
1153
1154    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
1155   
1156    [self updateUI];
1157    [self applyFilter: nil];
1158    [self updateTorrentHistory];
1159}
1160
1161- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
1162{
1163    [torrents retain];
1164    NSInteger active = 0, downloading = 0;
1165
1166    if ([fDefaults boolForKey: @"CheckRemove"])
1167    {
1168        Torrent * torrent;
1169        NSEnumerator * enumerator = [torrents objectEnumerator];
1170        while ((torrent = [enumerator nextObject]))
1171            if ([torrent isActive])
1172            {
1173                active++;
1174                if (![torrent isSeeding])
1175                    downloading++;
1176            }
1177
1178        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
1179        {
1180            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
1181                                    torrents, @"Torrents",
1182                                    [NSNumber numberWithBool: deleteData], @"DeleteData",
1183                                    [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
1184           
1185            NSString * title, * message;
1186           
1187            NSInteger selected = [torrents count];
1188            if (selected == 1)
1189            {
1190                NSString * torrentName = [[torrents objectAtIndex: 0] name];
1191               
1192                if (!deleteData && !deleteTorrent)
1193                    title = [NSString stringWithFormat:
1194                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1195                                "Removal confirm panel -> title"), torrentName];
1196                else if (deleteData && !deleteTorrent)
1197                    title = [NSString stringWithFormat:
1198                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1199                                " and trash the data file?", "Removal confirm panel -> title"), torrentName];
1200                else if (!deleteData && deleteTorrent)
1201                    title = [NSString stringWithFormat:
1202                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1203                                " and trash the torrent file?", "Removal confirm panel -> title"), torrentName];
1204                else
1205                    title = [NSString stringWithFormat:
1206                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1207                                " and trash both the data and torrent files?", "Removal confirm panel -> title"), torrentName];
1208               
1209                message = NSLocalizedString(@"This transfer is active."
1210                            " Once removed, continuing the transfer will require the torrent file.",
1211                            "Removal confirm panel -> message");
1212            }
1213            else
1214            {
1215                if (!deleteData && !deleteTorrent)
1216                    title = [NSString stringWithFormat:
1217                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list?",
1218                                "Removal confirm panel -> title"), selected];
1219                else if (deleteData && !deleteTorrent)
1220                    title = [NSString stringWithFormat:
1221                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1222                                " and trash the data file?", "Removal confirm panel -> title"), selected];
1223                else if (!deleteData && deleteTorrent)
1224                    title = [NSString stringWithFormat:
1225                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1226                                " and trash the torrent file?", "Removal confirm panel -> title"), selected];
1227                else
1228                    title = [NSString stringWithFormat:
1229                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1230                                " and trash both the data and torrent files?", "Removal confirm panel -> title"), selected];
1231               
1232                if (selected == active)
1233                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
1234                                "Removal confirm panel -> message part 1"), active];
1235                else
1236                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
1237                                "Removal confirm panel -> message part 1"), selected, active];
1238                message = [message stringByAppendingFormat: @" %@",
1239                                NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files.",
1240                                "Removal confirm panel -> message part 2")];
1241            }
1242           
1243            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
1244                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
1245                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
1246            return;
1247        }
1248    }
1249   
1250    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
1251}
1252
1253- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (NSDictionary *) dict
1254{
1255    NSArray * torrents = [dict objectForKey: @"Torrents"];
1256    if (returnCode == NSAlertDefaultReturn)
1257        [self confirmRemoveTorrents: torrents deleteData: [[dict objectForKey: @"DeleteData"] boolValue]
1258                deleteTorrent: [[dict objectForKey: @"DeleteTorrent"] boolValue]];
1259    else
1260        [torrents release];
1261   
1262    [dict release];
1263}
1264
1265- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
1266{
1267    //don't want any of these starting then stopping
1268    NSEnumerator * enumerator = [torrents objectEnumerator];
1269    Torrent * torrent;
1270    while ((torrent = [enumerator nextObject]))
1271        [torrent setWaitToStart: NO];
1272   
1273    [fTorrents removeObjectsInArray: torrents];
1274   
1275    NSInteger lowestOrderValue = NSIntegerMax;
1276    enumerator = [torrents objectEnumerator];
1277    while ((torrent = [enumerator nextObject]))
1278    {
1279        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1280        [fTableView removeCollapsedGroup: [torrent groupValue]];
1281       
1282        if (deleteData)
1283            [torrent trashData];
1284        if (deleteTorrent)
1285            [torrent trashTorrent];
1286       
1287        lowestOrderValue = MIN(lowestOrderValue, [torrent orderValue]);
1288       
1289        [torrent closeRemoveTorrent];
1290    }
1291   
1292    [torrents release];
1293
1294    //reset the order values if necessary
1295    if (lowestOrderValue < [fTorrents count])
1296    {
1297        for (NSInteger i = lowestOrderValue; i < [fTorrents count]; i++)
1298            [[fTorrents objectAtIndex: i] setOrderValue: i];
1299    }
1300   
1301    [fTableView deselectAll: nil];
1302   
1303    [self updateTorrentsInQueue];
1304}
1305
1306- (void) removeNoDelete: (id) sender
1307{
1308    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: NO];
1309}
1310
1311- (void) removeDeleteData: (id) sender
1312{
1313    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: NO];
1314}
1315
1316- (void) removeDeleteTorrent: (id) sender
1317{
1318    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: YES];
1319}
1320
1321- (void) removeDeleteDataAndTorrent: (id) sender
1322{
1323    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: YES];
1324}
1325
1326- (void) moveDataFilesSelected: (id) sender
1327{
1328    [self moveDataFiles: [fTableView selectedTorrents]];
1329}
1330
1331- (void) moveDataFiles: (NSArray *) torrents
1332{
1333    NSOpenPanel * panel = [NSOpenPanel openPanel];
1334    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1335    [panel setAllowsMultipleSelection: NO];
1336    [panel setCanChooseFiles: NO];
1337    [panel setCanChooseDirectories: YES];
1338    [panel setCanCreateDirectories: YES];
1339   
1340    torrents = [torrents retain];
1341    NSInteger count = [torrents count];
1342    if (count == 1)
1343        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1344                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1345    else
1346        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1347                            "Move torrent -> select destination folder"), count]];
1348       
1349    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1350        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1351}
1352
1353- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) torrents
1354{
1355    if (code == NSOKButton)
1356    {
1357        NSEnumerator * enumerator = [torrents objectEnumerator];
1358        Torrent * torrent;
1359        while ((torrent = [enumerator nextObject]))
1360            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1361    }
1362   
1363    [torrents release];
1364}
1365
1366- (void) copyTorrentFiles: (id) sender
1367{
1368    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1369}
1370
1371- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1372{
1373    if ([torrents count] <= 0)
1374    {
1375        [torrents release];
1376        return;
1377    }
1378
1379    Torrent * torrent = [torrents objectAtIndex: 0];
1380
1381    //warn user if torrent file can't be found
1382    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1383    {
1384        NSAlert * alert = [[NSAlert alloc] init];
1385        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1386        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1387                                "Torrent file copy alert -> title"), [torrent name]]];
1388        [alert setInformativeText: [NSString stringWithFormat:
1389                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1390                                    [torrent torrentLocation]]];
1391        [alert setAlertStyle: NSWarningAlertStyle];
1392       
1393        [alert runModal];
1394        [alert release];
1395       
1396        [torrents removeObjectAtIndex: 0];
1397        [self copyTorrentFileForTorrents: torrents];
1398    }
1399    else
1400    {
1401        NSSavePanel * panel = [NSSavePanel savePanel];
1402        [panel setRequiredFileType: @"torrent"];
1403        [panel setCanSelectHiddenExtension: YES];
1404       
1405        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1406            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1407    }
1408}
1409
1410- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSMutableArray *) torrents
1411{
1412    //copy torrent to new location with name of data file
1413    if (code == NSOKButton)
1414        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1415   
1416    [torrents removeObjectAtIndex: 0];
1417    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1418}
1419
1420- (void) revealFile: (id) sender
1421{
1422    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
1423    Torrent * torrent;
1424    while ((torrent = [enumerator nextObject]))
1425        [torrent revealData];
1426}
1427
1428- (void) announceSelectedTorrents: (id) sender
1429{
1430    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
1431    Torrent * torrent;
1432    while ((torrent = [enumerator nextObject]))
1433    {
1434        if ([torrent canManualAnnounce])
1435            [torrent manualAnnounce];
1436    }
1437}
1438
1439- (void) verifySelectedTorrents: (id) sender
1440{
1441    [self verifyTorrents: [fTableView selectedTorrents]];
1442}
1443
1444- (void) verifyTorrents: (NSArray *) torrents
1445{
1446    NSEnumerator * enumerator = [torrents objectEnumerator];
1447    Torrent * torrent;
1448    while ((torrent = [enumerator nextObject]))
1449        [torrent resetCache];
1450   
1451    [self applyFilter: nil];
1452}
1453
1454- (void) showPreferenceWindow: (id) sender
1455{
1456    NSWindow * window = [fPrefsController window];
1457    if (![window isVisible])
1458        [window center];
1459
1460    [window makeKeyAndOrderFront: nil];
1461}
1462
1463- (void) showAboutWindow: (id) sender
1464{
1465    [[AboutWindowController aboutController] showWindow: nil];
1466}
1467
1468- (void) showInfo: (id) sender
1469{
1470    if ([[fInfoController window] isVisible])
1471        [fInfoController close];
1472    else
1473    {
1474        [fInfoController updateInfoStats];
1475        [[fInfoController window] orderFront: nil];
1476    }
1477}
1478
1479- (void) resetInfo
1480{
1481    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1482    [[QuickLookController quickLook] updateQuickLook];
1483}
1484
1485- (void) setInfoTab: (id) sender
1486{
1487    if (sender == fNextInfoTabItem)
1488        [fInfoController setNextTab];
1489    else
1490        [fInfoController setPreviousTab];
1491}
1492
1493- (void) showMessageWindow: (id) sender
1494{
1495    [fMessageController showWindow: nil];
1496}
1497
1498- (void) showStatsWindow: (id) sender
1499{
1500    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1501}
1502
1503- (void) updateUI
1504{
1505    [fTorrents makeObjectsPerformSelector: @selector(update)];
1506   
1507    if (![NSApp isHidden])
1508    {
1509        if ([fWindow isVisible])
1510        {
1511            [self sortTorrents];
1512           
1513            //update status bar
1514            if (![fStatusBar isHidden])
1515            {
1516                //set rates
1517                [fTotalDLField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_DOWN)]];
1518                [fTotalULField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_UP)]];
1519               
1520                //set status button text
1521                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1522                BOOL total;
1523                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1524                {
1525                    tr_session_stats stats;
1526                    if (total)
1527                        tr_sessionGetCumulativeStats(fLib, &stats);
1528                    else
1529                        tr_sessionGetStats(fLib, &stats);
1530                   
1531                    statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") stringByAppendingFormat: @": %@",
1532                                    [NSString stringForRatio: stats.ratio]];
1533                }
1534                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1535                {
1536                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1537                   
1538                    tr_session_stats stats;
1539                    if (total)
1540                        tr_sessionGetCumulativeStats(fLib, &stats);
1541                    else
1542                        tr_sessionGetStats(fLib, &stats);
1543                   
1544                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1545                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1546                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1547                }
1548               
1549                if ([NSApp isOnLeopardOrBetter])
1550                {
1551                    [fStatusButton setTitle: statusString];
1552                    [self resizeStatusButton];
1553                }
1554                else
1555                    [fStatusTigerField setStringValue: statusString];
1556            }
1557        }
1558
1559        //update non-constant parts of info window
1560        if ([[fInfoController window] isVisible])
1561            [fInfoController updateInfoStats];
1562    }
1563   
1564    //badge dock
1565    [fBadger updateBadge];
1566}
1567
1568- (void) resizeStatusButton
1569{
1570    [fStatusButton sizeToFit];
1571   
1572    //width ends up being too long
1573    NSRect statusFrame = [fStatusButton frame];
1574    statusFrame.size.width -= 25.0;
1575   
1576    CGFloat difference = NSMaxX(statusFrame) + 5.0 - [fTotalDLImageView frame].origin.x;
1577    if (difference > 0)
1578        statusFrame.size.width -= difference;
1579   
1580    [fStatusButton setFrame: statusFrame];
1581}
1582
1583- (void) setBottomCountText: (BOOL) filtering
1584{
1585    NSString * totalTorrentsString;
1586    NSInteger totalCount = [fTorrents count];
1587    if (totalCount != 1)
1588        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1589    else
1590        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1591   
1592    if (filtering)
1593    {
1594        NSInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1595        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1596            count -= [fDisplayedTorrents count];
1597       
1598        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d of %@", "Status bar transfer count"),
1599                                count, totalTorrentsString];
1600    }
1601   
1602    [fTotalTorrentsField setStringValue: totalTorrentsString];
1603}
1604
1605- (void) updateTorrentsInQueue
1606{
1607    BOOL download = [fDefaults boolForKey: @"Queue"],
1608        seed = [fDefaults boolForKey: @"QueueSeed"];
1609   
1610    NSInteger desiredDownloadActive = [self numToStartFromQueue: YES],
1611        desiredSeedActive = [self numToStartFromQueue: NO];
1612   
1613    Torrent * torrent;
1614    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1615    while ((torrent = [enumerator nextObject]))
1616    {
1617        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1618        {
1619            if (![torrent allDownloaded])
1620            {
1621                if (!download || desiredDownloadActive > 0)
1622                {
1623                    [torrent startTransfer];
1624                    if ([torrent isActive])
1625                        desiredDownloadActive--;
1626                    [torrent update];
1627                }
1628            }
1629            else
1630            {
1631                if (!seed || desiredSeedActive > 0)
1632                {
1633                    [torrent startTransfer];
1634                    if ([torrent isActive])
1635                        desiredSeedActive--;
1636                    [torrent update];
1637                }
1638            }
1639        }
1640    }
1641   
1642    [self updateUI];
1643    [self applyFilter: nil];
1644    [self updateTorrentHistory];
1645}
1646
1647- (NSInteger) numToStartFromQueue: (BOOL) downloadQueue
1648{
1649    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1650        return 0;
1651   
1652    NSInteger desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1653       
1654    Torrent * torrent;
1655    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1656    while ((torrent = [enumerator nextObject]))
1657    {
1658        if ([torrent isChecking])
1659        {
1660            desired--;
1661            if (desired <= 0)
1662                return 0;
1663        }
1664        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1665        {
1666            if ([torrent allDownloaded] != downloadQueue)
1667            {
1668                desired--;
1669                if (desired <= 0)
1670                    return 0;
1671            }
1672        }
1673        else;
1674    }
1675   
1676    return desired;
1677}
1678
1679- (void) torrentFinishedDownloading: (NSNotification *) notification
1680{
1681    Torrent * torrent = [notification object];
1682   
1683    if ([torrent isActive])
1684    {
1685        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1686        {
1687            NSSound * sound;
1688            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1689            {
1690                [sound setDelegate: self];
1691                fSoundPlaying = YES;
1692                [sound play];
1693            }
1694        }
1695       
1696        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1697                                        [torrent dataLocation] , @"Location", nil];
1698        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1699                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1700                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1701       
1702        if (![fWindow isMainWindow])
1703            [fBadger incrementCompleted];
1704       
1705        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1706        {
1707            [torrent stopTransfer];
1708            [torrent setWaitToStart: YES];
1709        }
1710    }
1711   
1712    [self updateTorrentsInQueue];
1713}
1714
1715- (void) torrentRestartedDownloading: (NSNotification *) notification
1716{
1717    Torrent * torrent = [notification object];
1718    if ([torrent isActive])
1719    {
1720        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1721        {
1722            [torrent stopTransfer];
1723            [torrent setWaitToStart: YES];
1724        }
1725    }
1726   
1727    [self updateTorrentsInQueue];
1728}
1729
1730- (void) torrentStoppedForRatio: (NSNotification *) notification
1731{
1732    Torrent * torrent = [notification object];
1733   
1734    [self updateTorrentsInQueue];
1735   
1736    if ([[fTableView selectedTorrents] containsObject: torrent])
1737    {
1738        [fInfoController updateInfoStats];
1739        [fInfoController updateOptions];
1740    }
1741   
1742    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1743    {
1744        NSSound * sound;
1745        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1746        {
1747            [sound setDelegate: self];
1748            fSoundPlaying = YES;
1749            [sound play];
1750        }
1751    }
1752   
1753    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
1754                                    [torrent dataLocation], @"Location", nil];
1755    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1756                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1757                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1758}
1759
1760- (void) updateTorrentHistory
1761{
1762    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1763
1764    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1765    Torrent * torrent;
1766    while ((torrent = [enumerator nextObject]))
1767        [history addObject: [torrent history]];
1768
1769    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER] atomically: YES];
1770}
1771
1772- (void) setSort: (id) sender
1773{
1774    NSString * sortType;
1775    switch ([sender tag])
1776    {
1777        case SORT_ORDER_TAG:
1778            sortType = SORT_ORDER;
1779            [fDefaults setBool: NO forKey: @"SortReverse"];
1780            break;
1781        case SORT_DATE_TAG:
1782            sortType = SORT_DATE;
1783            break;
1784        case SORT_NAME_TAG:
1785            sortType = SORT_NAME;
1786            break;
1787        case SORT_PROGRESS_TAG:
1788            sortType = SORT_PROGRESS;
1789            break;
1790        case SORT_STATE_TAG:
1791            sortType = SORT_STATE;
1792            break;
1793        case SORT_TRACKER_TAG:
1794            sortType = SORT_TRACKER;
1795            break;
1796        case SORT_ACTIVITY_TAG:
1797            sortType = SORT_ACTIVITY;
1798            break;
1799        default:
1800            return;
1801    }
1802   
1803    [fDefaults setObject: sortType forKey: @"Sort"];
1804    [self sortTorrents];
1805}
1806
1807- (void) setSortByGroup: (id) sender
1808{
1809    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1810    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1811   
1812    //expand all groups
1813    if (sortByGroup)
1814        [fTableView removeAllCollapsedGroups];
1815   
1816    [self applyFilter: nil];
1817}
1818
1819- (void) setSortReverse: (id) sender
1820{
1821    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1822    [self sortTorrents];
1823}
1824
1825- (void) sortTorrents
1826{
1827    NSArray * selectedValues = [fTableView selectedValues];
1828   
1829    [self sortTorrentsIgnoreSelected]; //actually sort
1830   
1831    [fTableView selectValues: selectedValues];
1832}
1833
1834- (void) sortTorrentsIgnoreSelected
1835{
1836    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1837    BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1838   
1839    NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: asc] autorelease];
1840   
1841    NSArray * descriptors;
1842    if ([sortType isEqualToString: SORT_ORDER])
1843        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1844    else if ([sortType isEqualToString: SORT_NAME])
1845    {
1846        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1847                                                selector: @selector(compareFinder:)] autorelease];
1848       
1849        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1850    }
1851    else if ([sortType isEqualToString: SORT_STATE])
1852    {
1853        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1854                                                selector: @selector(compareFinder:)] autorelease],
1855                        * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1856                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1857                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1858       
1859        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1860                                                            nameDescriptor, orderDescriptor, nil];
1861    }
1862    else if ([sortType isEqualToString: SORT_PROGRESS])
1863    {
1864        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1865                                                selector: @selector(compareFinder:)] autorelease],
1866                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1867                        * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1868                                                        ascending: asc] autorelease],
1869                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1870       
1871        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1872                                                            nameDescriptor, orderDescriptor, nil];
1873    }
1874    else if ([sortType isEqualToString: SORT_TRACKER])
1875    {
1876        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1877                                                selector: @selector(compareFinder:)] autorelease],
1878                        * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddressAnnounce" ascending: asc
1879                                                selector: @selector(localizedCaseInsensitiveCompare:)] autorelease];
1880       
1881        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, orderDescriptor, nil];
1882    }
1883    else if ([sortType isEqualToString: SORT_ACTIVITY])
1884    {
1885        NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1886        NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1887                                                    autorelease];
1888       
1889        descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, orderDescriptor, nil];
1890    }
1891    else
1892    {
1893        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1894   
1895        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1896    }
1897   
1898    //on Tiger add the group sort descriptor to the front
1899    if (![NSApp isOnLeopardOrBetter] && [fDefaults boolForKey: @"SortByGroup"])
1900    {
1901        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
1902       
1903        NSMutableArray * temp = [[NSMutableArray alloc] initWithCapacity: [descriptors count]+1];
1904        [temp addObject: groupDescriptor];
1905        [temp addObjectsFromArray: descriptors];
1906       
1907        [descriptors release];
1908        descriptors = temp;
1909    }
1910   
1911    //actually sort
1912    if ([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
1913    {
1914        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1915        TorrentGroup * group;
1916        while ((group = [enumerator nextObject]))
1917            [[group torrents] sortUsingDescriptors: descriptors];
1918    }
1919    else
1920        [fDisplayedTorrents sortUsingDescriptors: descriptors];
1921   
1922    [descriptors release];
1923   
1924    [fTableView reloadData];
1925}
1926
1927- (void) applyFilter: (id) sender
1928{
1929    //get all the torrents in the table
1930    NSMutableArray * previousTorrents;
1931    if ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1932    {
1933        previousTorrents = [NSMutableArray array];
1934       
1935        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1936        TorrentGroup * group;
1937        while ((group = [enumerator nextObject]))
1938            [previousTorrents addObjectsFromArray: [group torrents]];
1939    }
1940    else
1941        previousTorrents = fDisplayedTorrents;
1942   
1943    NSArray * selectedValues = [fTableView selectedValues];
1944   
1945    NSInteger active = 0, downloading = 0, seeding = 0, paused = 0;
1946    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1947    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1948    if ([filterType isEqualToString: FILTER_ACTIVE])
1949        filterActive = YES;
1950    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1951        filterDownload = YES;
1952    else if ([filterType isEqualToString: FILTER_SEED])
1953        filterSeed = YES;
1954    else if ([filterType isEqualToString: FILTER_PAUSE])
1955        filterPause = YES;
1956    else
1957        filterStatus = NO;
1958   
1959    NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
1960    BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
1961   
1962    NSString * searchString = [fSearchFilterField stringValue];
1963    BOOL filterText = [searchString length] > 0,
1964        filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
1965   
1966    NSMutableIndexSet * indexes = [NSMutableIndexSet indexSet];
1967   
1968    //get count of each type
1969    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1970    Torrent * torrent;
1971    NSInteger index = -1;
1972    while ((torrent = [enumerator nextObject]))
1973    {
1974        index++;
1975       
1976        //check status
1977        if ([torrent isActive] && ![torrent isCheckingWaiting])
1978        {
1979            if ([torrent isSeeding])
1980            {
1981                seeding++;
1982                BOOL isActive = ![torrent isStalled];
1983                if (isActive)
1984                    active++;
1985               
1986                if (filterStatus && !((filterActive && isActive) || filterSeed))
1987                    continue;
1988            }
1989            else
1990            {
1991                downloading++;
1992                BOOL isActive = ![torrent isStalled];
1993                if (isActive)
1994                    active++;
1995               
1996                if (filterStatus && !((filterActive && isActive) || filterDownload))
1997                    continue;
1998            }
1999        }
2000        else
2001        {
2002            paused++;
2003            if (filterStatus && !filterPause)
2004                continue;
2005        }
2006       
2007        //checkGroup
2008        if (filterGroup)
2009            if ([torrent groupValue] != groupFilterValue)
2010                continue;
2011       
2012        //check text field
2013        if (filterText)
2014        {
2015            if (filterTracker)
2016            {
2017                BOOL removeTextField = YES;
2018                NSEnumerator * trackerEnumerator = [[torrent allTrackers: NO] objectEnumerator];
2019                NSString * tracker;
2020                while ((tracker = [trackerEnumerator nextObject]))
2021                {
2022                    if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
2023                    {
2024                        removeTextField = NO;
2025                        break;
2026                    }
2027                }
2028               
2029                if (removeTextField)
2030                    continue;
2031            }
2032            else
2033            {
2034                if ([[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound)
2035                    continue;
2036            }
2037        }
2038       
2039        [indexes addIndex: index];
2040    }
2041   
2042    NSArray * allTorrents = [fTorrents objectsAtIndexes: indexes];
2043   
2044    //set button tooltips
2045    [fNoFilterButton setCount: [fTorrents count]];
2046    [fActiveFilterButton setCount: active];
2047    [fDownloadFilterButton setCount: downloading];
2048    [fSeedFilterButton setCount: seeding];
2049    [fPauseFilterButton setCount: paused];
2050   
2051    //clear display cache for not-shown torrents
2052    [previousTorrents removeObjectsInArray: allTorrents];
2053    enumerator = [previousTorrents objectEnumerator];
2054    while ((torrent = [enumerator nextObject]))
2055        [torrent setPreviousFinishedPieces: nil];
2056   
2057    //place torrents into groups
2058    BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter];
2059    if (groupRows)
2060    {
2061        [fDisplayedTorrents removeAllObjects];
2062       
2063        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2064        allTorrents = [allTorrents sortedArrayUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2065       
2066        NSMutableArray * groupTorrents;
2067        for (NSInteger i = 0, oldGroupValue = -2; i < [allTorrents count]; i++)
2068        {
2069            torrent = [allTorrents objectAtIndex: i];
2070            NSInteger groupValue = [torrent groupValue];
2071            if (groupValue != oldGroupValue)
2072            {
2073                TorrentGroup * group = [[TorrentGroup alloc] initWithGroup: groupValue];
2074                groupTorrents = [group torrents];
2075               
2076                [fDisplayedTorrents addObject: group];
2077                [group release];
2078               
2079                oldGroupValue = groupValue;
2080            }
2081           
2082            [groupTorrents addObject: torrent];
2083        }
2084    }
2085    else
2086        [fDisplayedTorrents setArray: allTorrents];
2087   
2088    //actually sort
2089    [self sortTorrentsIgnoreSelected];
2090   
2091    //reset expanded/collapsed rows
2092    if (groupRows)
2093    {
2094        enumerator = [fDisplayedTorrents objectEnumerator];
2095        TorrentGroup * group;
2096        while ((group = [enumerator nextObject]))
2097        {
2098            if ([fTableView isGroupCollapsed: [group groupIndex]])
2099                [fTableView collapseItem: group];
2100            else
2101                [fTableView expandItem: group];
2102        }
2103    }
2104   
2105    [fTableView selectValues: selectedValues];
2106    #warning still happens anyway?
2107    //removed because it made the inspector reset (noticeable when a transfer with web seeds is selected)
2108    //[self resetInfo]; //if group is already selected, but the torrents in it change
2109   
2110    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2111   
2112    [self setWindowSizeToFit];
2113}
2114
2115//resets filter and sorts torrents
2116- (void) setFilter: (id) sender
2117{
2118    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2119   
2120    NSButton * prevFilterButton;
2121    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2122        prevFilterButton = fPauseFilterButton;
2123    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2124        prevFilterButton = fActiveFilterButton;
2125    else if ([oldFilterType isEqualToString: FILTER_SEED])
2126        prevFilterButton = fSeedFilterButton;
2127    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2128        prevFilterButton = fDownloadFilterButton;
2129    else
2130        prevFilterButton = fNoFilterButton;
2131   
2132    if (sender != prevFilterButton)
2133    {
2134        [prevFilterButton setState: NSOffState];
2135        [sender setState: NSOnState];
2136
2137        NSString * filterType;
2138        if (sender == fActiveFilterButton)
2139            filterType = FILTER_ACTIVE;
2140        else if (sender == fDownloadFilterButton)
2141            filterType = FILTER_DOWNLOAD;
2142        else if (sender == fPauseFilterButton)
2143            filterType = FILTER_PAUSE;
2144        else if (sender == fSeedFilterButton)
2145            filterType = FILTER_SEED;
2146        else
2147            filterType = FILTER_NONE;
2148
2149        [fDefaults setObject: filterType forKey: @"Filter"];
2150    }
2151    else
2152        [sender setState: NSOnState];
2153
2154    [self applyFilter: nil];
2155}
2156
2157- (void) setFilterSearchType: (id) sender
2158{
2159    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2160   
2161    NSInteger prevTag, currentTag = [sender tag];
2162    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2163        prevTag = FILTER_TYPE_TAG_TRACKER;
2164    else
2165        prevTag = FILTER_TYPE_TAG_NAME;
2166   
2167    if (currentTag != prevTag)
2168    {
2169        NSString * filterType;
2170        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2171            filterType = FILTER_TYPE_TRACKER;
2172        else
2173            filterType = FILTER_TYPE_NAME;
2174       
2175        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2176       
2177        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2178    }
2179   
2180    [self applyFilter: nil];
2181}
2182
2183- (void) switchFilter: (id) sender
2184{
2185    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2186   
2187    NSButton * button;
2188    if ([filterType isEqualToString: FILTER_NONE])
2189        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2190    else if ([filterType isEqualToString: FILTER_ACTIVE])
2191        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2192    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2193        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2194    else if ([filterType isEqualToString: FILTER_SEED])
2195        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2196    else if ([filterType isEqualToString: FILTER_PAUSE])
2197        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2198    else
2199        button = fNoFilterButton;
2200   
2201    [self setFilter: button];
2202}
2203
2204- (void) setStatusLabel: (id) sender
2205{
2206    NSString * statusLabel;
2207    switch ([sender tag])
2208    {
2209        case STATUS_RATIO_TOTAL_TAG:
2210            statusLabel = STATUS_RATIO_TOTAL;
2211            break;
2212        case STATUS_RATIO_SESSION_TAG:
2213            statusLabel = STATUS_RATIO_SESSION;
2214            break;
2215        case STATUS_TRANSFER_TOTAL_TAG:
2216            statusLabel = STATUS_TRANSFER_TOTAL;
2217            break;
2218        case STATUS_TRANSFER_SESSION_TAG:
2219            statusLabel = STATUS_TRANSFER_SESSION;
2220            break;
2221        default:
2222            return;
2223    }
2224   
2225    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2226    [self updateUI];
2227}
2228
2229- (void) showGroups: (id) sender
2230{
2231    [[GroupsWindowController groupsWindow] showWindow: self];
2232}
2233
2234- (void) menuNeedsUpdate: (NSMenu *) menu
2235{
2236    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2237    {
2238        for (NSInteger i = [menu numberOfItems]-1 - 2; i >= 0; i--)
2239            [menu removeItemAtIndex: i];
2240       
2241        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2242        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2243                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: NO];
2244    }
2245    else if (menu == fGroupFilterMenu)
2246    {
2247        for (NSInteger i = [menu numberOfItems]-1; i >= 3; i--)
2248            [menu removeItemAtIndex: i];
2249       
2250        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:)
2251                                isSmall: YES];
2252        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2253                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: YES];
2254    }
2255    else if (menu == fUploadMenu || menu == fDownloadMenu)
2256    {
2257        if ([menu numberOfItems] > 3)
2258            return;
2259       
2260        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, -1 };
2261       
2262        NSMenuItem * item;
2263        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2264        {
2265            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2266                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2267                    keyEquivalent: @""];
2268            [item setTarget: self];
2269            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2270            [menu addItem: item];
2271            [item release];
2272        }
2273    }
2274    else if (menu == fRatioStopMenu)
2275    {
2276        if ([menu numberOfItems] > 3)
2277            return;
2278       
2279        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2280       
2281        NSMenuItem * item;
2282        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2283        {
2284            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2285                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2286            [item setTarget: self];
2287            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2288            [menu addItem: item];
2289            [item release];
2290        }
2291    }
2292    else;
2293}
2294
2295- (void) setGroup: (id) sender
2296{
2297    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
2298    Torrent * torrent;
2299    while ((torrent = [enumerator nextObject]))
2300    {
2301        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2302       
2303        [torrent setGroupValue: [sender tag]];
2304    }
2305   
2306    [self applyFilter: nil];
2307    [self updateUI];
2308    [self updateTorrentHistory];
2309}
2310
2311- (void) setGroupFilter: (id) sender
2312{
2313    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2314    [self updateGroupsFilterButton];
2315    [self applyFilter: nil];
2316}
2317
2318- (void) updateGroupsFilterButton
2319{
2320    NSInteger groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2321   
2322    NSImage * icon;
2323    NSString * toolTip;
2324    if (groupIndex == GROUP_FILTER_ALL_TAG)
2325    {
2326        icon = [NSImage imageNamed: @"PinTemplate.png"];
2327        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2328    }
2329    else
2330    {
2331        icon = [[GroupsController groups] imageForIndex: groupIndex];
2332        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2333                                                : NSLocalizedString(@"None", "Groups -> Button");
2334        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2335    }
2336   
2337    //tiger doesn't have built-in image scaling in buttons
2338    if (![NSApp isOnLeopardOrBetter])
2339    {
2340        icon = [[icon copy] autorelease];
2341        [icon setScalesWhenResized: YES];
2342        [icon setSize: NSMakeSize(12.0, 12.0)];
2343    }
2344   
2345    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2346    [fGroupsButton setToolTip: toolTip];
2347}
2348
2349- (void) updateGroupsFilters: (NSNotification *) notification
2350{
2351    [self updateGroupsFilterButton];
2352    [self applyFilter: nil];
2353}
2354
2355- (void) toggleSpeedLimit: (id) sender
2356{
2357    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2358    [fPrefsController applySpeedSettings: nil];
2359}
2360
2361- (void) autoSpeedLimitChange: (NSNotification *) notification
2362{
2363    //clear timer here in case it's not being reset
2364    [fSpeedLimitTimer invalidate];
2365    fSpeedLimitTimer = nil;
2366   
2367    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2368        return;
2369   
2370    NSCalendar * calendar = [NSCalendar currentCalendar];
2371    NSDateComponents * nowComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2372                    * onComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2373                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]],
2374                    * offComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2375                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]];
2376   
2377    //check if should be on if within range
2378    NSInteger onTime = [onComponents hour] * 60 + [onComponents minute],
2379        offTime = [offComponents hour] * 60 + [offComponents minute],
2380        nowTime = [nowComponents hour] * 60 + [nowComponents minute];
2381   
2382    BOOL shouldBeOn = NO;
2383    if (onTime < offTime)
2384        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2385    else if (onTime > offTime)
2386        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2387    else;
2388   
2389    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2390        [self toggleSpeedLimit: nil];
2391   
2392    //no need to set the timer if both times are equal
2393    if (onTime == offTime)
2394        return;
2395   
2396    [self setAutoSpeedLimitTimer: !shouldBeOn];
2397}
2398
2399//only called by fSpeedLimitTimer
2400- (void) autoSpeedLimit: (NSTimer *) timer
2401{
2402    BOOL shouldLimit = [[timer userInfo] boolValue];
2403   
2404    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldLimit)
2405    {
2406        [self toggleSpeedLimit: nil];
2407       
2408        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2409                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2410                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2411            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2412            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2413    }
2414   
2415    [self setAutoSpeedLimitTimer: !shouldLimit];
2416}
2417
2418- (void) setAutoSpeedLimitTimer: (BOOL) nextIsLimit
2419{
2420    NSDate * timerDate = [fDefaults objectForKey: nextIsLimit ? @"SpeedLimitAutoOnDate" : @"SpeedLimitAutoOffDate"];
2421   
2422    //create date with combination of the current date and the date to go off
2423    NSCalendar * calendar = [NSCalendar currentCalendar];
2424    NSDateComponents * nowComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
2425                                        | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2426                    * timerComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: timerDate];
2427   
2428    //check if should be the next day
2429    NSInteger nowTime = [nowComponents hour] * 60 + [nowComponents minute],
2430        timerTime = [timerComponents hour] * 60 + [timerComponents minute];
2431    if (timerTime < nowTime)
2432        [nowComponents setDay: [nowComponents day] + 1]; //properly goes to next month when appropriate
2433   
2434    [nowComponents setHour: [timerComponents hour]];
2435    [nowComponents setMinute: [timerComponents minute]];
2436    [nowComponents setSecond: 0];
2437   
2438    NSDate * dateToUse = [calendar dateFromComponents: nowComponents];
2439   
2440    fSpeedLimitTimer = [[NSTimer alloc] initWithFireDate: dateToUse interval: 0 target: self selector: @selector(autoSpeedLimit:)
2441                        userInfo: [NSNumber numberWithBool: nextIsLimit] repeats: NO];
2442   
2443    NSRunLoop * loop = [NSApp isOnLeopardOrBetter] ? [NSRunLoop mainRunLoop] : [NSRunLoop currentRunLoop];
2444    [loop addTimer: fSpeedLimitTimer forMode: NSDefaultRunLoopMode];
2445    [loop addTimer: fSpeedLimitTimer forMode: NSModalPanelRunLoopMode];
2446    [loop addTimer: fSpeedLimitTimer forMode: NSEventTrackingRunLoopMode];
2447    [fSpeedLimitTimer release];
2448}
2449
2450- (void) setLimitGlobalEnabled: (id) sender
2451{
2452    BOOL upload = [sender menu] == fUploadMenu;
2453    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2454   
2455    [fPrefsController applySpeedSettings: nil];
2456}
2457
2458- (void) setQuickLimitGlobal: (id) sender
2459{
2460    BOOL upload = [sender menu] == fUploadMenu;
2461    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2462    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2463   
2464    [fPrefsController updateLimitFields];
2465    [fPrefsController applySpeedSettings: nil];
2466}
2467
2468- (void) setRatioGlobalEnabled: (id) sender
2469{
2470    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2471}
2472
2473- (void) setQuickRatioGlobal: (id) sender
2474{
2475    [fDefaults setBool: YES forKey: @"RatioCheck"];
2476    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2477   
2478    [fPrefsController updateRatioStopField];
2479}
2480
2481- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2482{
2483    fSoundPlaying = NO;
2484}
2485
2486- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2487{
2488    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2489    {
2490        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2491            return;
2492       
2493        if (fAutoImportTimer)
2494        {
2495            if ([fAutoImportTimer isValid])
2496                [fAutoImportTimer invalidate];
2497            [fAutoImportTimer release];
2498            fAutoImportTimer = nil;
2499        }
2500       
2501        //check again in 10 seconds in case torrent file wasn't complete
2502        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2503            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2504       
2505        [self checkAutoImportDirectory];
2506    }
2507}
2508
2509- (void) changeAutoImport
2510{
2511    if (fAutoImportTimer)
2512    {
2513        if ([fAutoImportTimer isValid])
2514            [fAutoImportTimer invalidate];
2515        [fAutoImportTimer release];
2516        fAutoImportTimer = nil;
2517    }
2518   
2519    if (fAutoImportedNames)
2520    {
2521        [fAutoImportedNames release];
2522        fAutoImportedNames = nil;
2523    }
2524   
2525    [self checkAutoImportDirectory];
2526}
2527
2528- (void) checkAutoImportDirectory
2529{
2530    NSString * path;
2531    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2532        return;
2533   
2534    path = [path stringByExpandingTildeInPath];
2535   
2536    NSArray * importedNames;
2537    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2538        return;
2539   
2540    //only check files that have not been checked yet
2541    NSMutableArray * newNames = [importedNames mutableCopy];
2542   
2543    if (fAutoImportedNames)
2544        [newNames removeObjectsInArray: fAutoImportedNames];
2545    else
2546        fAutoImportedNames = [[NSMutableArray alloc] init];
2547    [fAutoImportedNames setArray: importedNames];
2548   
2549    NSString * file;
2550    for (NSInteger i = [newNames count] - 1; i >= 0; i--)
2551    {
2552        file = [newNames objectAtIndex: i];
2553        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2554            [newNames removeObjectAtIndex: i];
2555        else
2556            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2557    }
2558   
2559    NSEnumerator * enumerator = [newNames objectEnumerator];
2560    tr_ctor * ctor;
2561    while ((file = [enumerator nextObject]))
2562    {
2563        ctor = tr_ctorNew(fLib);
2564        tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2565       
2566        switch (tr_torrentParse(fLib, ctor, NULL))
2567        {
2568            case TR_OK:
2569                [self openFiles: [NSArray arrayWithObject: file] addType: ADD_AUTO forcePath: nil];
2570               
2571                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2572                    description: [file lastPathComponent] notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2573                    clickContext: nil];
2574                break;
2575           
2576            case TR_EINVALID:
2577                [fAutoImportedNames removeObject: [file lastPathComponent]];
2578        }
2579       
2580        tr_ctorFree(ctor);
2581    }
2582   
2583    [newNames release];
2584}
2585
2586- (void) beginCreateFile: (NSNotification *) notification
2587{
2588    if (![fDefaults boolForKey: @"AutoImport"])
2589        return;
2590   
2591    NSString * location = [notification object],
2592            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2593   
2594    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2595                                    isEqualToString: [path stringByExpandingTildeInPath]])
2596        [fAutoImportedNames addObject: [location lastPathComponent]];
2597}
2598
2599- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2600{
2601    if (item)
2602        return [[item torrents] count];
2603    else
2604        return [fDisplayedTorrents count];
2605}
2606
2607- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2608{
2609    if (item)
2610        return [[item torrents] objectAtIndex: index];
2611    else
2612        return [fDisplayedTorrents objectAtIndex: index];
2613}
2614
2615- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2616{
2617    return ![item isKindOfClass: [Torrent class]];
2618}
2619
2620- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2621{
2622    if ([item isKindOfClass: [Torrent class]])
2623        return [item hashString];
2624    else
2625    {
2626        NSString * ident = [tableColumn identifier];
2627        if ([ident isEqualToString: @"Group"])
2628        {
2629            NSInteger group = [item groupIndex];
2630            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2631                                : NSLocalizedString(@"No Group", "Group table row");
2632        }
2633        else if ([ident isEqualToString: @"Color"])
2634        {
2635            NSInteger group = [item groupIndex];
2636            return [[GroupsController groups] imageForIndex: group];
2637        }
2638        else if ([ident isEqualToString: @"DL Image"])
2639            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2640        else if ([ident isEqualToString: @"UL Image"])
2641            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2642                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2643        else
2644        {
2645            TorrentGroup * group = (TorrentGroup *)item;
2646           
2647            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2648                return [NSString stringForRatio: [group ratio]];
2649            else
2650            {
2651                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2652                return [NSString stringForSpeed: rate];
2653            }
2654        }
2655    }
2656}
2657
2658- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2659{
2660    //only allow reordering of rows if sorting by order
2661    if (([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
2662        || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2663    {
2664        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2665        NSEnumerator * enumerator = [items objectEnumerator];
2666        id torrent;
2667        while ((torrent = [enumerator nextObject]))
2668        {
2669            if (![torrent isKindOfClass: [Torrent class]])
2670                return NO;
2671           
2672            [indexSet addIndex: [fTableView rowForItem: torrent]];
2673        }
2674       
2675        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2676        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2677        return YES;
2678    }
2679    return NO;
2680}
2681
2682- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2683    proposedChildIndex: (NSInteger) index
2684{
2685    NSPasteboard * pasteboard = [info draggingPasteboard];
2686    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2687    {
2688        if ([fDefaults boolForKey: @"SortByGroup"])
2689        {
2690            if (!item)
2691                return NSDragOperationNone;
2692           
2693            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2694            {
2695                if ([item isKindOfClass: [Torrent class]])
2696                {
2697                    TorrentGroup * group = [fTableView parentForItem: item];
2698                    index = [[group torrents] indexOfObject: item] + 1;
2699                    item = group;
2700                }
2701            }
2702            else
2703            {
2704                if ([item isKindOfClass: [Torrent class]])
2705                    item = [fTableView parentForItem: item];
2706                index = NSOutlineViewDropOnItemIndex;
2707            }
2708        }
2709        else
2710        {
2711            if (item)
2712            {
2713                index = [fTableView rowForItem: item] + 1;
2714                item = nil;
2715            }
2716        }
2717       
2718        [fTableView setDropItem: item dropChildIndex: index];
2719        return NSDragOperationGeneric;
2720    }
2721   
2722    return NSDragOperationNone;
2723}
2724
2725- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2726    childIndex: (NSInteger) newRow
2727{
2728    NSPasteboard * pasteboard = [info draggingPasteboard];
2729    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2730    {
2731        //remember selected rows
2732        NSArray * selectedValues = [fTableView selectedValues];
2733   
2734        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2735       
2736        //get the torrents to move
2737        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2738        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2739            [movingTorrents addObject: [fTableView itemAtRow: i]];
2740       
2741        //reset groups
2742        if (item)
2743        {
2744            //change groups
2745            NSInteger groupValue = [item groupIndex];
2746            NSEnumerator * enumerator = [movingTorrents objectEnumerator];
2747            Torrent * torrent;
2748            while ((torrent = [enumerator nextObject]))
2749            {
2750                //have to reset objects here to avoid weird crash
2751                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2752                [[item torrents] addObject: torrent];
2753               
2754                [torrent setGroupValue: groupValue];
2755            }
2756            //part 2 of avoiding weird crash
2757            [fTableView reloadItem: nil reloadChildren: YES];
2758        }
2759       
2760        //reorder queue order
2761        if (newRow != NSOutlineViewDropOnItemIndex)
2762        {
2763            //find torrent to place under
2764            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2765            Torrent * topTorrent = nil;
2766            for (NSInteger i = newRow-1; i >= 0; i--)
2767            {
2768                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2769                if (![movingTorrents containsObject: tempTorrent])
2770                {
2771                    topTorrent = tempTorrent;
2772                    break;
2773                }
2774            }
2775           
2776            //remove objects to reinsert
2777            [fTorrents removeObjectsInArray: movingTorrents];
2778           
2779            //insert objects at new location
2780            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2781            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2782            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2783           
2784            //redo order values
2785            for (NSInteger i = 0; i < [fTorrents count]; i++)
2786                [[fTorrents objectAtIndex: i] setOrderValue: i];
2787        }
2788       
2789        [self applyFilter: nil];
2790        [fTableView selectValues: selectedValues];
2791    }
2792   
2793    return YES;
2794}
2795
2796- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2797{
2798    [self resetInfo];
2799}
2800
2801- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2802{
2803    NSPasteboard * pasteboard = [info draggingPasteboard];
2804    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2805    {
2806        //check if any torrent files can be added
2807        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2808        NSEnumerator * enumerator = [files objectEnumerator];
2809        NSString * file;
2810        BOOL torrent = NO;
2811        tr_ctor * ctor;
2812        while ((file = [enumerator nextObject]))
2813        {
2814            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2815            {
2816                ctor = tr_ctorNew(fLib);
2817                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2818                switch (tr_torrentParse(fLib, ctor, NULL))
2819                {
2820                    case TR_OK:
2821                        if (!fOverlayWindow)
2822                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2823                        [fOverlayWindow setTorrents: files];
2824                       
2825                        return NSDragOperationCopy;
2826                   
2827                    case TR_EDUPLICATE:
2828                        torrent = YES;
2829                }
2830                tr_ctorFree(ctor);
2831            }
2832        }
2833       
2834        //create a torrent file if a single file
2835        if (!torrent && [files count] == 1)
2836        {
2837            if (!fOverlayWindow)
2838                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2839            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2840           
2841            return NSDragOperationCopy;
2842        }
2843    }
2844    else if ([[pasteboard types] containsObject: NSURLPboardType])
2845    {
2846        if (!fOverlayWindow)
2847            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2848        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2849       
2850        return NSDragOperationCopy;
2851    }
2852    else;
2853   
2854    return NSDragOperationNone;
2855}
2856
2857- (void) draggingExited: (id <NSDraggingInfo>) info
2858{
2859    if (fOverlayWindow)
2860        [fOverlayWindow fadeOut];
2861}
2862
2863- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2864{
2865    if (fOverlayWindow)
2866        [fOverlayWindow fadeOut];
2867   
2868    NSPasteboard * pasteboard = [info draggingPasteboard];
2869    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2870    {
2871        BOOL torrent = NO, accept = YES;
2872       
2873        //create an array of files that can be opened
2874        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2875        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2876        NSEnumerator * enumerator = [files objectEnumerator];
2877        NSString * file;
2878        tr_ctor * ctor;
2879        while ((file = [enumerator nextObject]))
2880        {
2881            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2882            {
2883                ctor = tr_ctorNew(fLib);
2884                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2885                switch (tr_torrentParse(fLib, ctor, NULL))
2886                {
2887                    case TR_OK:
2888                        [filesToOpen addObject: file];
2889                        torrent = YES;
2890                        break;
2891                       
2892                    case TR_EDUPLICATE:
2893                        torrent = YES;
2894                }
2895                tr_ctorFree(ctor);
2896            }
2897        }
2898       
2899        if ([filesToOpen count] > 0)
2900            [self application: NSApp openFiles: filesToOpen];
2901        else
2902        {
2903            if (!torrent && [files count] == 1)
2904                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2905            else
2906                accept = NO;
2907        }
2908        [filesToOpen release];
2909       
2910        return accept;
2911    }
2912    else if ([[pasteboard types] containsObject: NSURLPboardType])
2913    {
2914        NSURL * url;
2915        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2916        {
2917            [self openURL: url];
2918            return YES;
2919        }
2920    }
2921    else;
2922   
2923    return NO;
2924}
2925
2926- (void) toggleSmallView: (id) sender
2927{
2928    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2929    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2930   
2931    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2932   
2933    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2934   
2935    //window min height
2936    NSSize contentMinSize = [fWindow contentMinSize],
2937            contentSize = [[fWindow contentView] frame].size;
2938    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2939                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2940    [fWindow setContentMinSize: contentMinSize];
2941   
2942    //resize for larger min height if not set to auto size
2943    if (![fDefaults boolForKey: @"AutoSize"])
2944    {
2945        if (!makeSmall && contentSize.height < contentMinSize.height)
2946        {
2947            NSRect frame = [fWindow frame];
2948            CGFloat heightChange = contentMinSize.height - contentSize.height;
2949            frame.size.height += heightChange;
2950            frame.origin.y -= heightChange;
2951           
2952            [fWindow setFrame: frame display: YES];
2953        }
2954    }
2955    else
2956        [self setWindowSizeToFit];
2957}
2958
2959- (void) togglePiecesBar: (id) sender
2960{
2961    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2962    [fTableView togglePiecesBar];
2963}
2964
2965- (void) toggleAvailabilityBar: (id) sender
2966{
2967    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2968    [fTableView display];
2969}
2970
2971- (void) toggleStatusString: (id) sender
2972{
2973    if ([fDefaults boolForKey: @"SmallView"])
2974        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2975    else
2976        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2977   
2978    [fTableView reloadData];
2979}
2980
2981- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2982{
2983    NSScrollView * scrollView = [fTableView enclosingScrollView];
2984   
2985    //convert pixels to points
2986    NSRect windowFrame = [fWindow frame];
2987    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2988    windowSize.height += height;
2989   
2990    if (check)
2991    {
2992        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2993       
2994        if (windowSize.height < minSize.height)
2995            windowSize.height = minSize.height;
2996        else
2997        {
2998            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2999            if ([fStatusBar isHidden])
3000                maxSize.height -= [fStatusBar frame].size.height;
3001            if ([fFilterBar isHidden])
3002                maxSize.height -= [fFilterBar frame].size.height;
3003            if (windowSize.height > maxSize.height)
3004                windowSize.height = maxSize.height;
3005        }
3006    }
3007
3008    //convert points to pixels
3009    windowSize = [scrollView convertSize: windowSize toView: nil];
3010
3011    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
3012    windowFrame.size.height = windowSize.height;
3013    return windowFrame;
3014}
3015
3016- (void) toggleStatusBar: (id) sender
3017{
3018    [self showStatusBar: [fStatusBar isHidden] animate: YES];
3019    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
3020}
3021
3022//doesn't save shown state
3023- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
3024{
3025    if (show != [fStatusBar isHidden])
3026        return;
3027
3028    if (show)
3029        [fStatusBar setHidden: NO];
3030
3031    NSRect frame;
3032    CGFloat heightChange = [fStatusBar frame].size.height;
3033    if (!show)
3034        heightChange *= -1;
3035   
3036    //allow bar to show even if not enough room
3037    if (show && ![fDefaults boolForKey: @"AutoSize"])
3038    {
3039        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3040        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3041        if (change < 0.0)
3042        {
3043            frame = [fWindow frame];
3044            frame.size.height += change;
3045            frame.origin.y -= change;
3046            [fWindow setFrame: frame display: NO animate: NO];
3047        }
3048    }
3049
3050    [self updateUI];
3051   
3052    NSScrollView * scrollView = [fTableView enclosingScrollView];
3053   
3054    //set views to not autoresize
3055    NSUInteger statsMask = [fStatusBar autoresizingMask];
3056    NSUInteger filterMask = [fFilterBar autoresizingMask];
3057    NSUInteger scrollMask = [scrollView autoresizingMask];
3058    [fStatusBar setAutoresizingMask: NSViewNotSizable];
3059    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3060    [scrollView setAutoresizingMask: NSViewNotSizable];
3061   
3062    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3063    [fWindow setFrame: frame display: YES animate: animate];
3064   
3065    //re-enable autoresize
3066    [fStatusBar setAutoresizingMask: statsMask];
3067    [fFilterBar setAutoresizingMask: filterMask];
3068    [scrollView setAutoresizingMask: scrollMask];
3069   
3070    //change min size
3071    NSSize minSize = [fWindow contentMinSize];
3072    minSize.height += heightChange;
3073    [fWindow setContentMinSize: minSize];
3074   
3075    if (!show)
3076        [fStatusBar setHidden: YES];
3077}
3078
3079- (void) toggleFilterBar: (id) sender
3080{
3081    //disable filtering when hiding
3082    if (![fFilterBar isHidden])
3083    {
3084        [fSearchFilterField setStringValue: @""];
3085        [self setFilter: fNoFilterButton];
3086        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3087    }
3088
3089    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3090    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3091}
3092
3093//doesn't save shown state
3094- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3095{
3096    if (show != [fFilterBar isHidden])
3097        return;
3098
3099    if (show)
3100        [fFilterBar setHidden: NO];
3101
3102    NSRect frame;
3103    CGFloat heightChange = [fFilterBar frame].size.height;
3104    if (!show)
3105        heightChange *= -1;
3106   
3107    //allow bar to show even if not enough room
3108    if (show && ![fDefaults boolForKey: @"AutoSize"])
3109    {
3110        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3111        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3112        if (change < 0.0)
3113        {
3114            frame = [fWindow frame];
3115            frame.size.height += change;
3116            frame.origin.y -= change;
3117            [fWindow setFrame: frame display: NO animate: NO];
3118        }
3119    }
3120   
3121    NSScrollView * scrollView = [fTableView enclosingScrollView];
3122
3123    //set views to not autoresize
3124    NSUInteger filterMask = [fFilterBar autoresizingMask];
3125    NSUInteger scrollMask = [scrollView autoresizingMask];
3126    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3127    [scrollView setAutoresizingMask: NSViewNotSizable];
3128   
3129    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3130    [fWindow setFrame: frame display: YES animate: animate];
3131   
3132    //re-enable autoresize
3133    [fFilterBar setAutoresizingMask: filterMask];
3134    [scrollView setAutoresizingMask: scrollMask];
3135   
3136    //change min size
3137    NSSize minSize = [fWindow contentMinSize];
3138    minSize.height += heightChange;
3139    [fWindow setContentMinSize: minSize];
3140   
3141    if (!show)
3142    {
3143        [fFilterBar setHidden: YES];
3144        [fWindow makeFirstResponder: fTableView];
3145    }
3146}
3147
3148- (void) focusFilterField
3149{
3150    [fWindow makeFirstResponder: fSearchFilterField];
3151    if ([fFilterBar isHidden])
3152        [self toggleFilterBar: self];
3153}
3154
3155- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3156{
3157    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3158   
3159    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3160    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3161    [button setStringValue: @""];
3162   
3163    [item setView: button];
3164    [button release];
3165   
3166    NSSize buttonSize = NSMakeSize(36.0, 25.0);
3167    [item setMinSize: buttonSize];
3168    [item setMaxSize: buttonSize];
3169   
3170    return [item autorelease];
3171}
3172
3173- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3174{
3175    if ([ident isEqualToString: TOOLBAR_CREATE])
3176    {
3177        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3178       
3179        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3180        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3181        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3182        [item setImage: [NSImage imageNamed: @"Create.png"]];
3183        [item setTarget: self];
3184        [item setAction: @selector(createFile:)];
3185        [item setAutovalidates: NO];
3186       
3187        return item;
3188    }
3189    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3190    {
3191        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3192       
3193        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3194        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3195        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3196        [item setImage: [NSImage imageNamed: @"Open.png"]];
3197        [item setTarget: self];
3198        [item setAction: @selector(openShowSheet:)];
3199        [item setAutovalidates: NO];
3200       
3201        return item;
3202    }
3203    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3204    {
3205        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3206       
3207        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3208        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3209        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3210        [item setImage: [NSImage imageNamed: @"OpenWeb.png"]];
3211        [item setTarget: self];
3212        [item setAction: @selector(openURLShowSheet:)];
3213        [item setAutovalidates: NO];
3214       
3215        return item;
3216    }
3217    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3218    {
3219        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3220       
3221        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3222        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3223        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3224        [item setImage: [NSImage imageNamed: @"Remove.png"]];
3225        [item setTarget: self];
3226        [item setAction: @selector(removeNoDelete:)];
3227       
3228        return item;
3229    }
3230    else if ([ident isEqualToString: TOOLBAR_INFO])
3231    {
3232        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3233       
3234        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3235        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3236        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3237        [item setImage: [NSImage imageNamed: @"Info.png"]];
3238        [item setTarget: self];
3239        [item setAction: @selector(showInfo:)];
3240       
3241        return item;
3242    }
3243    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3244    {
3245        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3246       
3247        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3248        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3249        [groupItem setView: segmentedControl];
3250        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3251       
3252        [segmentedControl setSegmentCount: 2];
3253        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3254       
3255        NSSize groupSize = NSMakeSize(72.0, 25.0);
3256        [groupItem setMinSize: groupSize];
3257        [groupItem setMaxSize: groupSize];
3258       
3259        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3260        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3261        [groupItem setTarget: self];
3262        [groupItem setAction: @selector(allToolbarClicked:)];
3263       
3264        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3265       
3266        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3267        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
3268        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3269                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3270       
3271        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3272        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
3273        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3274                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3275       
3276        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3277                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3278       
3279        [segmentedControl release];
3280        return [groupItem autorelease];
3281    }
3282    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3283    {
3284        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3285       
3286        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3287        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3288        [groupItem setView: segmentedControl];
3289        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3290       
3291        [segmentedControl setSegmentCount: 2];
3292        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3293       
3294        NSSize groupSize = NSMakeSize(72.0, 25.0);
3295        [groupItem setMinSize: groupSize];
3296        [groupItem setMaxSize: groupSize];
3297       
3298        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3299        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3300        [groupItem setTarget: self];
3301        [groupItem setAction: @selector(selectedToolbarClicked:)];
3302       
3303        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3304       
3305        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3306        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
3307        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3308                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3309       
3310        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3311        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
3312        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3313                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3314       
3315        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3316                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3317       
3318        [segmentedControl release];
3319        return [groupItem autorelease];
3320    }
3321    else if ([ident isEqualToString: TOOLBAR_FILTER])
3322    {
3323        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3324       
3325        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3326        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3327        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3328        [item setImage: [NSImage imageNamed: @"Filter.png"]];
3329        [item setTarget: self];
3330        [item setAction: @selector(toggleFilterBar:)];
3331       
3332        return item;
3333    }
3334    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3335    {
3336        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3337       
3338        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3339        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3340        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3341        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3342        [item setTarget: self];
3343        [item setAction: @selector(toggleQuickLook:)];
3344       
3345        return item;
3346    }
3347    else
3348        return nil;
3349}
3350
3351- (void) allToolbarClicked: (id) sender
3352{
3353    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3354                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3355    switch (tagValue)
3356    {
3357        case TOOLBAR_PAUSE_TAG:
3358            [self stopAllTorrents: sender];
3359            break;
3360        case TOOLBAR_RESUME_TAG:
3361            [self resumeAllTorrents: sender];
3362            break;
3363    }
3364}
3365
3366- (void) selectedToolbarClicked: (id) sender
3367{
3368    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3369                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3370    switch (tagValue)
3371    {
3372        case TOOLBAR_PAUSE_TAG:
3373            [self stopSelectedTorrents: sender];
3374            break;
3375        case TOOLBAR_RESUME_TAG:
3376            [self resumeSelectedTorrents: sender];
3377            break;
3378    }
3379}
3380
3381- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3382{
3383    NSMutableArray * idents = [NSMutableArray arrayWithObjects:
3384                                TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB,
3385                                TOOLBAR_REMOVE, TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3386                                TOOLBAR_FILTER, TOOLBAR_INFO,
3387                                NSToolbarSeparatorItemIdentifier,
3388                                NSToolbarSpaceItemIdentifier,
3389                                NSToolbarFlexibleSpaceItemIdentifier,
3390                                NSToolbarCustomizeToolbarItemIdentifier, nil];
3391   
3392    //allow quicklook on leopard
3393    if ([NSApp isOnLeopardOrBetter])
3394        [idents insertObject: TOOLBAR_QUICKLOOK atIndex: 6];
3395   
3396    return idents;
3397}
3398
3399- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3400{
3401    NSMutableArray * idents =  [NSMutableArray arrayWithObjects:
3402                                TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE,
3403                                NSToolbarSeparatorItemIdentifier,
3404                                TOOLBAR_PAUSE_RESUME_ALL,
3405                                NSToolbarFlexibleSpaceItemIdentifier,
3406                                TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3407   
3408    //allow quicklook on leopard
3409    if ([NSApp isOnLeopardOrBetter])
3410        [idents insertObject: TOOLBAR_QUICKLOOK atIndex: [idents count]-2];
3411   
3412    return idents;
3413}
3414
3415- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3416{
3417    NSString * ident = [toolbarItem itemIdentifier];
3418   
3419    //enable remove item
3420    if ([ident isEqualToString: TOOLBAR_REMOVE])
3421        return [fTableView numberOfSelectedRows] > 0;
3422
3423    //enable pause all item
3424    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3425    {
3426        Torrent * torrent;
3427        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3428        while ((torrent = [enumerator nextObject]))
3429            if ([torrent isActive] || [torrent waitingToStart])
3430                return YES;
3431        return NO;
3432    }
3433
3434    //enable resume all item
3435    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3436    {
3437        Torrent * torrent;
3438        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3439        while ((torrent = [enumerator nextObject]))
3440            if (![torrent isActive] && ![torrent waitingToStart])
3441                return YES;
3442        return NO;
3443    }
3444
3445    //enable pause item
3446    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3447    {
3448        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3449        Torrent * torrent;
3450        while ((torrent = [enumerator nextObject]))
3451            if ([torrent isActive] || [torrent waitingToStart])
3452                return YES;
3453        return NO;
3454    }
3455   
3456    //enable resume item
3457    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3458    {
3459        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3460        Torrent * torrent;
3461        while ((torrent = [enumerator nextObject]))
3462            if (![torrent isActive] && ![torrent waitingToStart])
3463                return YES;
3464        return NO;
3465    }
3466   
3467    //set info image
3468    if ([ident isEqualToString: TOOLBAR_INFO])
3469    {
3470        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue.png"]
3471                                                                    : [NSImage imageNamed: @"Info.png"]];
3472        return YES;
3473    }
3474   
3475    //set filter image
3476    if ([ident isEqualToString: TOOLBAR_FILTER])
3477    {
3478        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue.png"] : [NSImage imageNamed: @"Filter.png"]];
3479        return YES;
3480    }
3481   
3482    //enable quicklook item
3483    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3484        return [[QuickLookController quickLook] canQuickLook];
3485
3486    return YES;
3487}
3488
3489- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3490{
3491    SEL action = [menuItem action];
3492   
3493    if (action == @selector(toggleSpeedLimit:))
3494    {
3495        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3496        return YES;
3497    }
3498   
3499    //only enable some items if it is in a context menu or the window is useable
3500    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3501
3502    //enable open items
3503    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3504        return [fWindow attachedSheet] == nil;
3505   
3506    //enable sort options
3507    if (action == @selector(setSort:))
3508    {
3509        NSString * sortType;
3510        switch ([menuItem tag])
3511        {
3512            case SORT_ORDER_TAG:
3513                sortType = SORT_ORDER;
3514                break;
3515            case SORT_DATE_TAG:
3516                sortType = SORT_DATE;
3517                break;
3518            case SORT_NAME_TAG:
3519                sortType = SORT_NAME;
3520                break;
3521            case SORT_PROGRESS_TAG:
3522                sortType = SORT_PROGRESS;
3523                break;
3524            case SORT_STATE_TAG:
3525                sortType = SORT_STATE;
3526                break;
3527            case SORT_TRACKER_TAG:
3528                sortType = SORT_TRACKER;
3529                break;
3530            case SORT_ACTIVITY_TAG:
3531                sortType = SORT_ACTIVITY;
3532        }
3533       
3534        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3535        return [fWindow isVisible];
3536    }
3537   
3538    //enable sort options
3539    if (action == @selector(setStatusLabel:))
3540    {
3541        NSString * statusLabel;
3542        switch ([menuItem tag])
3543        {
3544            case STATUS_RATIO_TOTAL_TAG:
3545                statusLabel = STATUS_RATIO_TOTAL;
3546                break;
3547            case STATUS_RATIO_SESSION_TAG:
3548                statusLabel = STATUS_RATIO_SESSION;
3549                break;
3550            case STATUS_TRANSFER_TOTAL_TAG:
3551                statusLabel = STATUS_TRANSFER_TOTAL;
3552                break;
3553            case STATUS_TRANSFER_SESSION_TAG:
3554                statusLabel = STATUS_TRANSFER_SESSION;
3555        }
3556       
3557        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3558        return YES;
3559    }
3560   
3561    if (action == @selector(setGroup:))
3562    {
3563        BOOL checked = NO;
3564       
3565        NSInteger index = [menuItem tag];
3566        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3567        Torrent * torrent;
3568        while ((torrent = [enumerator nextObject]))
3569            if (index == [torrent groupValue])
3570            {
3571                checked = YES;
3572                break;
3573            }
3574       
3575        [menuItem setState: checked ? NSOnState : NSOffState];
3576        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3577    }
3578   
3579    if (action == @selector(setGroupFilter:))
3580    {
3581        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3582        return YES;
3583    }
3584   
3585    if (action == @selector(toggleSmallView:))
3586    {
3587        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3588        return [fWindow isVisible];
3589    }
3590   
3591    if (action == @selector(togglePiecesBar:))
3592    {
3593        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3594        return [fWindow isVisible];
3595    }
3596   
3597    if (action == @selector(toggleStatusString:))
3598    {
3599        if ([fDefaults boolForKey: @"SmallView"])
3600        {
3601            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3602            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3603        }
3604        else
3605        {
3606            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3607            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3608        }
3609       
3610        return [fWindow isVisible];
3611    }
3612   
3613    if (action == @selector(toggleAvailabilityBar:))
3614    {
3615        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3616        return [fWindow isVisible];
3617    }
3618   
3619    if (action == @selector(setLimitGlobalEnabled:))
3620    {
3621        BOOL upload = [menuItem menu] == fUploadMenu;
3622        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3623        if (limit)
3624            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3625                                    "Action menu -> upload/download limit"),
3626                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3627       
3628        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3629        return YES;
3630    }
3631   
3632    if (action == @selector(setRatioGlobalEnabled:))
3633    {
3634        BOOL check = menuItem == fCheckRatioItem;
3635        if (check)
3636            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3637                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3638       
3639        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3640        return YES;
3641    }
3642
3643    //enable show info
3644    if (action == @selector(showInfo:))
3645    {
3646        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3647                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3648        [menuItem setTitle: title];
3649
3650        return YES;
3651    }
3652   
3653    //enable prev/next inspector tab
3654    if (action == @selector(setInfoTab:))
3655        return [[fInfoController window] isVisible];
3656   
3657    //enable toggle status bar
3658    if (action == @selector(toggleStatusBar:))
3659    {
3660        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3661                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3662        [menuItem setTitle: title];
3663
3664        return [fWindow isVisible];
3665    }
3666   
3667    //enable toggle filter bar
3668    if (action == @selector(toggleFilterBar:))
3669    {
3670        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3671                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3672        [menuItem setTitle: title];
3673
3674        return [fWindow isVisible];
3675    }
3676   
3677    //enable prev/next filter button
3678    if (action == @selector(switchFilter:))
3679        return [fWindow isVisible] && ![fFilterBar isHidden];
3680   
3681    //enable quicklook item
3682    if (action == @selector(toggleQuickLook:))
3683        return [[QuickLookController quickLook] canQuickLook];
3684   
3685    //enable reveal in finder
3686    if (action == @selector(revealFile:))
3687        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3688
3689    //enable remove items
3690    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3691        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3692    {
3693        BOOL warning = NO,
3694            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3695            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3696       
3697        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3698        Torrent * torrent;
3699        while ((torrent = [enumerator nextObject]))
3700        {
3701            if (!warning && [torrent isActive])
3702            {
3703                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3704                if (warning && canDelete)
3705                    break;
3706            }
3707            if (!canDelete && [torrent publicTorrent])
3708            {
3709                canDelete = YES;
3710                if (warning)
3711                    break;
3712            }
3713        }
3714   
3715        //append or remove ellipsis when needed
3716        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3717        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3718        {
3719            if (![title hasSuffix: ellipsis])
3720                [menuItem setTitle: [title stringByAppendingEllipsis]];
3721        }
3722        else
3723        {
3724            if ([title hasSuffix: ellipsis])
3725                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3726        }
3727       
3728        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3729    }
3730
3731    //enable pause all item
3732    if (action == @selector(stopAllTorrents:))
3733    {
3734        Torrent * torrent;
3735        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3736        while ((torrent = [enumerator nextObject]))
3737            if ([torrent isActive] || [torrent waitingToStart])
3738                return YES;
3739        return NO;
3740    }
3741   
3742    //enable resume all item
3743    if (action == @selector(resumeAllTorrents:))
3744    {
3745        Torrent * torrent;
3746        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3747        while ((torrent = [enumerator nextObject]))
3748            if (![torrent isActive] && ![torrent waitingToStart])
3749                return YES;
3750        return NO;
3751    }
3752   
3753    //enable resume all waiting item
3754    if (action == @selector(resumeWaitingTorrents:))
3755    {
3756        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3757            return NO;
3758   
3759        Torrent * torrent;
3760        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3761        while ((torrent = [enumerator nextObject]))
3762            if (![torrent isActive] && [torrent waitingToStart])
3763                return YES;
3764        return NO;
3765    }
3766   
3767    //enable resume selected waiting item
3768    if (action == @selector(resumeSelectedTorrentsNoWait:))
3769    {
3770        if (!canUseTable)
3771            return NO;
3772       
3773        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3774        Torrent * torrent;
3775        while ((torrent = [enumerator nextObject]))
3776            if (![torrent isActive])
3777                return YES;
3778        return NO;
3779    }
3780
3781    //enable pause item
3782    if (action == @selector(stopSelectedTorrents:))
3783    {
3784        if (!canUseTable)
3785            return NO;
3786   
3787        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3788        Torrent * torrent;
3789        while ((torrent = [enumerator nextObject]))
3790            if ([torrent isActive] || [torrent waitingToStart])
3791                return YES;
3792        return NO;
3793    }
3794   
3795    //enable resume item
3796    if (action == @selector(resumeSelectedTorrents:))
3797    {
3798        if (!canUseTable)
3799            return NO;
3800   
3801        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3802        Torrent * torrent;
3803        while ((torrent = [enumerator nextObject]))
3804            if (![torrent isActive] && ![torrent waitingToStart])
3805                return YES;
3806        return NO;
3807    }
3808   
3809    //enable manual announce item
3810    if (action == @selector(announceSelectedTorrents:))
3811    {
3812        if (!canUseTable)
3813            return NO;
3814       
3815        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3816        Torrent * torrent;
3817        while ((torrent = [enumerator nextObject]))
3818            if ([torrent canManualAnnounce])
3819                return YES;
3820        return NO;
3821    }
3822   
3823    //enable reset cache item
3824    if (action == @selector(verifySelectedTorrents:))
3825        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3826   
3827    //enable move torrent file item
3828    if (action == @selector(moveDataFilesSelected:))
3829        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3830   
3831    //enable copy torrent file item
3832    if (action == @selector(copyTorrentFiles:))
3833        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3834   
3835    //enable reverse sort item
3836    if (action == @selector(setSortReverse:))
3837    {
3838        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3839        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3840    }
3841   
3842    //enable group sort item
3843    if (action == @selector(setSortByGroup:))
3844    {
3845        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3846        return YES;
3847    }
3848   
3849    //check proper filter search item
3850    if (action == @selector(setFilterSearchType:))
3851    {
3852        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3853       
3854        BOOL state;
3855        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3856            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3857        else
3858            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3859       
3860        [menuItem setState: state ? NSOnState : NSOffState];
3861        return YES;
3862    }
3863   
3864    return YES;
3865}
3866
3867- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3868{
3869    NSEnumerator * enumerator;
3870    Torrent * torrent;
3871
3872    switch (messageType)
3873    {
3874        case kIOMessageSystemWillSleep:
3875            //if there are any running transfers, wait 15 seconds for them to stop
3876            enumerator = [fTorrents objectEnumerator];
3877            while ((torrent = [enumerator nextObject]))
3878                if ([torrent isActive])
3879                {
3880                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3881                    [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3882                    sleep(15);
3883                    break;
3884                }
3885
3886            IOAllowPowerChange(fRootPort, (long) messageArgument);
3887            break;
3888
3889        case kIOMessageCanSystemSleep:
3890            if ([fDefaults boolForKey: @"SleepPrevent"])
3891            {
3892                //prevent idle sleep unless no torrents are active
3893                enumerator = [fTorrents objectEnumerator];
3894                while ((torrent = [enumerator nextObject]))
3895                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3896                    {
3897                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3898                        return;
3899                    }
3900            }
3901           
3902            IOAllowPowerChange(fRootPort, (long) messageArgument);
3903            break;
3904
3905        case kIOMessageSystemHasPoweredOn:
3906            //resume sleeping transfers after we wake up
3907            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3908            [self autoSpeedLimitChange: nil];
3909            break;
3910    }
3911}
3912
3913- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3914{
3915    NSInteger seeding = 0, downloading = 0;
3916    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3917    Torrent * torrent;
3918    while ((torrent = [enumerator nextObject]))
3919    {
3920        if ([torrent isSeeding])
3921            seeding++;
3922        else if ([torrent isActive])
3923            downloading++;
3924        else;
3925    }
3926   
3927    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3928            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3929   
3930    BOOL hasSeparator = seedingItem || downloadingItem;
3931   
3932    if (seeding > 0)
3933    {
3934        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3935        if (!seedingItem)
3936        {
3937            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3938            [seedingItem setTag: DOCK_SEEDING_TAG];
3939            [fDockMenu insertItem: seedingItem atIndex: 0];
3940        }
3941        else
3942            [seedingItem setTitle: title];
3943    }
3944    else
3945    {
3946        if (seedingItem)
3947            [fDockMenu removeItem: seedingItem];
3948    }
3949   
3950    if (downloading > 0)
3951    {
3952        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3953        if (!downloadingItem)
3954        {
3955            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3956            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3957            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3958        }
3959        else
3960            [downloadingItem setTitle: title];
3961    }
3962    else
3963    {
3964        if (downloadingItem)
3965            [fDockMenu removeItem: downloadingItem];
3966    }
3967   
3968    if (seeding > 0 || downloading > 0)
3969    {
3970        if (!hasSeparator)
3971            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3972    }
3973    else
3974    {
3975        if (hasSeparator)
3976            [fDockMenu removeItemAtIndex: 0];
3977    }
3978   
3979    return fDockMenu;
3980}
3981
3982- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3983{
3984    //if auto size is enabled, the current frame shouldn't need to change
3985    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3986   
3987    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3988    return frame;
3989}
3990
3991- (void) setWindowSizeToFit
3992{
3993    if ([fDefaults boolForKey: @"AutoSize"])
3994    {
3995        NSScrollView * scrollView = [fTableView enclosingScrollView];
3996       
3997        [scrollView setHasVerticalScroller: NO];
3998        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3999        [scrollView setHasVerticalScroller: YES];
4000       
4001        //hack to ensure scrollbars don't disappear after resizing
4002        [scrollView setAutohidesScrollers: NO];
4003        [scrollView setAutohidesScrollers: YES];
4004    }
4005}
4006
4007- (NSRect) sizedWindowFrame
4008{
4009    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
4010                    ? [fDisplayedTorrents count] : 0;
4011   
4012    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
4013                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
4014                        - [[fTableView enclosingScrollView] frame].size.height;
4015   
4016    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4017}
4018
4019- (void) updateForExpandCollape
4020{
4021    [self setWindowSizeToFit];
4022    [self setBottomCountText: YES];
4023}
4024
4025- (void) showMainWindow: (id) sender
4026{
4027    [fWindow makeKeyAndOrderFront: nil];
4028}
4029
4030- (void) windowDidBecomeMain: (NSNotification *) notification
4031{
4032    [fBadger clearCompleted];
4033    [self updateUI];
4034}
4035
4036- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
4037{
4038    //only resize horizontally if autosize is enabled
4039    if ([fDefaults boolForKey: @"AutoSize"])
4040        proposedFrameSize.height = [fWindow frame].size.height;
4041    return proposedFrameSize;
4042}
4043
4044- (void) windowDidResize: (NSNotification *) notification
4045{
4046    if (![fStatusBar isHidden])
4047        [self resizeStatusButton];
4048   
4049    if ([fFilterBar isHidden])
4050        return;
4051   
4052    //replace all buttons
4053    [fNoFilterButton sizeToFit];
4054    [fActiveFilterButton sizeToFit];
4055    [fDownloadFilterButton sizeToFit];
4056    [fSeedFilterButton sizeToFit];
4057    [fPauseFilterButton sizeToFit];
4058   
4059    NSRect allRect = [fNoFilterButton frame];
4060    NSRect activeRect = [fActiveFilterButton frame];
4061    NSRect downloadRect = [fDownloadFilterButton frame];
4062    NSRect seedRect = [fSeedFilterButton frame];
4063    NSRect pauseRect = [fPauseFilterButton frame];
4064   
4065    //size search filter to not overlap buttons
4066    NSRect searchFrame = [fSearchFilterField frame];
4067    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
4068    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
4069   
4070    //make sure it is not too long
4071    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
4072    {
4073        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
4074        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
4075    }
4076    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
4077    {
4078        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
4079        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
4080       
4081        //calculate width the buttons can take up
4082        const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x;
4083       
4084        const CGFloat currentTotal = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect)
4085                                        + NSWidth(pauseRect);
4086       
4087        //decrease button widths proportionally
4088        allRect.size.width  = NSWidth(allRect) * (allowedWidth / currentTotal);
4089        activeRect.size.width = NSWidth(activeRect) * (allowedWidth / currentTotal);
4090        downloadRect.size.width = NSWidth(downloadRect) * (allowedWidth / currentTotal);
4091        seedRect.size.width = NSWidth(seedRect) * (allowedWidth / currentTotal);
4092        pauseRect.size.width = NSWidth(pauseRect) * (allowedWidth / currentTotal);
4093    }
4094    else;
4095   
4096    activeRect.origin.x = NSMaxX(allRect) + 1.0;
4097    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
4098    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4099    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4100   
4101    [fNoFilterButton setFrame: allRect];
4102    [fActiveFilterButton setFrame: activeRect];
4103    [fDownloadFilterButton setFrame: downloadRect];
4104    [fSeedFilterButton setFrame: seedRect];
4105    [fPauseFilterButton setFrame: pauseRect];
4106   
4107    [fSearchFilterField setFrame: searchFrame];
4108}
4109
4110- (void) applicationWillUnhide: (NSNotification *) notification
4111{
4112    [self updateUI];
4113}
4114
4115- (NSArray *) quickLookURLs
4116{
4117    NSArray * selectedTorrents = [fTableView selectedTorrents];
4118    NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
4119    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4120    Torrent * torrent;
4121   
4122    while ((torrent = [enumerator nextObject]))
4123        if ([self canQuickLookTorrent: torrent])
4124            [urlArray addObject: [NSURL fileURLWithPath: [torrent dataLocation]]];
4125   
4126    return urlArray;
4127}
4128
4129- (BOOL) canQuickLook
4130{
4131    NSArray * selectedTorrents = [fTableView selectedTorrents];
4132    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4133    Torrent * torrent;
4134   
4135    while ((torrent = [enumerator nextObject]))
4136        if ([self canQuickLookTorrent: torrent])
4137            return YES;
4138   
4139    return NO;
4140}
4141
4142- (BOOL) canQuickLookTorrent: (Torrent *) torrent
4143{
4144    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent dataLocation]])
4145        return NO;
4146   
4147    return [torrent isFolder] || [torrent isComplete];
4148}
4149
4150- (NSRect) quickLookFrameWithURL: (NSURL *) url
4151{
4152    if ([fWindow isVisible])
4153    {
4154        NSString * fullPath = [url path];
4155        NSRange visibleRows = [fTableView rowsInRect: [fTableView bounds]];
4156       
4157        for (NSInteger row = 0; row < NSMaxRange(visibleRows); row++)
4158        {
4159            id item = [fTableView itemAtRow: row];
4160            if ([item isKindOfClass: [Torrent class]] && [[(Torrent *)item dataLocation] isEqualToString: fullPath])
4161            {
4162                NSRect frame = [fTableView iconRectForRow: row];
4163                frame.origin = [fTableView convertPoint: frame.origin toView: nil];
4164                frame.origin = [fWindow convertBaseToScreen: frame.origin];
4165                frame.origin.y -= frame.size.height;
4166                return frame;
4167            }
4168        }
4169    }
4170   
4171    return NSZeroRect;
4172}
4173
4174- (void) toggleQuickLook: (id) sender
4175{
4176    [[QuickLookController quickLook] toggleQuickLook];
4177}
4178
4179- (void) linkHomepage: (id) sender
4180{
4181    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4182}
4183
4184- (void) linkForums: (id) sender
4185{
4186    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4187}
4188
4189- (void) linkTrac: (id) sender
4190{
4191    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4192}
4193
4194- (void) linkDonate: (id) sender
4195{
4196    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4197}
4198
4199- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4200{
4201    fUpdateInProgress = YES;
4202}
4203
4204- (NSDictionary *) registrationDictionaryForGrowl
4205{
4206    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4207                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4208    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4209                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4210}
4211
4212- (void) growlNotificationWasClicked: (id) clickContext
4213{
4214    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4215        return;
4216   
4217    NSString * type = [clickContext objectForKey: @"Type"], * location;
4218    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4219            && (location = [clickContext objectForKey: @"Location"]))
4220        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4221}
4222
4223- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4224{
4225    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4226   
4227    //get the torrent
4228    Torrent * torrent = nil;
4229    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4230    {
4231        NSEnumerator * enumerator = [fTorrents objectEnumerator];
4232        while ((torrent = [enumerator nextObject]))
4233            if (torrentStruct == [torrent torrentStruct])
4234            {
4235                [torrent retain];
4236                break;
4237            }
4238       
4239        if (!torrent)
4240        {
4241            [pool release];
4242           
4243            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4244            return;
4245        }
4246    }
4247   
4248    switch (type)
4249    {
4250        case TR_RPC_TORRENT_ADDED:
4251            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4252                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4253            break;
4254       
4255        case TR_RPC_TORRENT_STARTED:
4256        case TR_RPC_TORRENT_STOPPED:
4257            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4258            break;
4259       
4260        case TR_RPC_TORRENT_REMOVING:
4261            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4262            break;
4263       
4264        case TR_RPC_TORRENT_CHANGED:
4265            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4266            break;
4267       
4268        case TR_RPC_SESSION_CHANGED:
4269            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4270            break;
4271       
4272        default:
4273            NSLog(@"Unknown RPC command received!");
4274            [torrent release];
4275    }
4276   
4277    [pool release];
4278}
4279
4280- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4281{
4282    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4283    [torrentStructPtr release];
4284   
4285    NSString * location = nil;
4286    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4287        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4288   
4289    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4290   
4291    [torrent update];
4292    [fTorrents addObject: torrent];
4293    [torrent release];
4294   
4295    [self updateTorrentsInQueue];
4296}
4297
4298- (void) rpcRemoveTorrent: (Torrent *) torrent
4299{
4300    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO deleteTorrent: NO];
4301    [torrent release];
4302}
4303
4304- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4305{
4306    [torrent update];
4307    [torrent release];
4308   
4309    [self updateUI];
4310    [self applyFilter: nil];
4311    [self updateTorrentHistory];
4312}
4313
4314- (void) rpcChangedTorrent: (Torrent *) torrent
4315{
4316    [torrent update];
4317   
4318    if ([[fTableView selectedTorrents] containsObject: torrent])
4319    {
4320        [fInfoController updateInfoStats]; //this will reload the file table
4321        [fInfoController updateOptions];
4322    }
4323   
4324    [torrent release];
4325}
4326
4327@end
Note: See TracBrowser for help on using the repository browser.