source: trunk/macosx/Controller.m @ 7250

Last change on this file since 7250 was 7250, checked in by livings124, 13 years ago

#1536 Speed Limit Rollover information

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