source: trunk/macosx/Controller.m @ 7185

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

remove references and dead code to the group window being its own window; other rearrangements of code

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