source: trunk/macosx/Controller.m @ 6122

Last change on this file since 6122 was 6122, checked in by livings124, 14 years ago

(mac) implement proxy support

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