source: trunk/macosx/Controller.m @ 6144

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

fix string typo; one less warning

  • Property svn:keywords set to Date Rev Author Id
File size: 156.5 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 6144 2008-06-11 19:06:31Z 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        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1213        [fTableView removeCollapsedGroup: [torrent groupValue]];
1214       
1215        if (deleteData)
1216            [torrent trashData];
1217        if (deleteTorrent)
1218            [torrent trashTorrent];
1219       
1220        lowestOrderValue = MIN(lowestOrderValue, [torrent orderValue]);
1221       
1222        if (rpc)
1223            [torrent closeRemoveTorrentInterface];
1224        else
1225            [torrent closeRemoveTorrent];
1226    }
1227   
1228    [torrents release];
1229
1230    //reset the order values if necessary
1231    if (lowestOrderValue < [fTorrents count])
1232    {
1233        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: YES] autorelease];
1234        NSArray * tempTorrents = [fTorrents sortedArrayUsingDescriptors: [NSArray arrayWithObject: orderDescriptor]];
1235
1236        int i;
1237        for (i = lowestOrderValue; i < [tempTorrents count]; i++)
1238            [[tempTorrents objectAtIndex: i] setOrderValue: i];
1239    }
1240   
1241    [fTableView deselectAll: nil];
1242   
1243    [self updateTorrentsInQueue];
1244}
1245
1246- (void) removeNoDelete: (id) sender
1247{
1248    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: NO];
1249}
1250
1251- (void) removeDeleteData: (id) sender
1252{
1253    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: NO];
1254}
1255
1256- (void) removeDeleteTorrent: (id) sender
1257{
1258    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: YES];
1259}
1260
1261- (void) removeDeleteDataAndTorrent: (id) sender
1262{
1263    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: YES];
1264}
1265
1266- (void) moveDataFilesSelected: (id) sender
1267{
1268    [self moveDataFiles: [fTableView selectedTorrents]];
1269}
1270
1271- (void) moveDataFiles: (NSArray *) torrents
1272{
1273    NSOpenPanel * panel = [NSOpenPanel openPanel];
1274    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1275    [panel setAllowsMultipleSelection: NO];
1276    [panel setCanChooseFiles: NO];
1277    [panel setCanChooseDirectories: YES];
1278    [panel setCanCreateDirectories: YES];
1279   
1280    torrents = [torrents retain];
1281    int count = [torrents count];
1282    if (count == 1)
1283        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1284                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1285    else
1286        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1287                            "Move torrent -> select destination folder"), count]];
1288       
1289    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1290        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1291}
1292
1293- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSArray *) torrents
1294{
1295    if (code == NSOKButton)
1296    {
1297        NSEnumerator * enumerator = [torrents objectEnumerator];
1298        Torrent * torrent;
1299        while ((torrent = [enumerator nextObject]))
1300            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1301    }
1302   
1303    [torrents release];
1304}
1305
1306- (void) copyTorrentFiles: (id) sender
1307{
1308    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1309}
1310
1311- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1312{
1313    if ([torrents count] <= 0)
1314    {
1315        [torrents release];
1316        return;
1317    }
1318
1319    Torrent * torrent = [torrents objectAtIndex: 0];
1320
1321    //warn user if torrent file can't be found
1322    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1323    {
1324        NSAlert * alert = [[NSAlert alloc] init];
1325        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1326        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1327                                "Torrent file copy alert -> title"), [torrent name]]];
1328        [alert setInformativeText: [NSString stringWithFormat:
1329                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1330                                    [torrent torrentLocation]]];
1331        [alert setAlertStyle: NSWarningAlertStyle];
1332       
1333        [alert runModal];
1334        [alert release];
1335       
1336        [torrents removeObjectAtIndex: 0];
1337        [self copyTorrentFileForTorrents: torrents];
1338    }
1339    else
1340    {
1341        NSSavePanel * panel = [NSSavePanel savePanel];
1342        [panel setRequiredFileType: @"torrent"];
1343        [panel setCanSelectHiddenExtension: YES];
1344       
1345        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1346            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1347    }
1348}
1349
1350- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (NSMutableArray *) torrents
1351{
1352    //copy torrent to new location with name of data file
1353    if (code == NSOKButton)
1354        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1355   
1356    [torrents removeObjectAtIndex: 0];
1357    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1358}
1359
1360- (void) revealFile: (id) sender
1361{
1362    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
1363    Torrent * torrent;
1364    while ((torrent = [enumerator nextObject]))
1365        [torrent revealData];
1366}
1367
1368- (void) announceSelectedTorrents: (id) sender
1369{
1370    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
1371    Torrent * torrent;
1372    while ((torrent = [enumerator nextObject]))
1373    {
1374        if ([torrent canManualAnnounce])
1375            [torrent manualAnnounce];
1376    }
1377}
1378
1379- (void) verifySelectedTorrents: (id) sender
1380{
1381    [self verifyTorrents: [fTableView selectedTorrents]];
1382}
1383
1384- (void) verifyTorrents: (NSArray *) torrents
1385{
1386    NSEnumerator * enumerator = [torrents objectEnumerator];
1387    Torrent * torrent;
1388    while ((torrent = [enumerator nextObject]))
1389        [torrent resetCache];
1390   
1391    [self applyFilter: nil];
1392}
1393
1394- (void) showPreferenceWindow: (id) sender
1395{
1396    NSWindow * window = [fPrefsController window];
1397    if (![window isVisible])
1398        [window center];
1399
1400    [window makeKeyAndOrderFront: nil];
1401}
1402
1403- (void) showAboutWindow: (id) sender
1404{
1405    [[AboutWindowController aboutController] showWindow: nil];
1406}
1407
1408- (void) showInfo: (id) sender
1409{
1410    if ([[fInfoController window] isVisible])
1411        [fInfoController close];
1412    else
1413    {
1414        [fInfoController updateInfoStats];
1415        [[fInfoController window] orderFront: nil];
1416    }
1417}
1418
1419- (void) setInfoTab: (id) sender
1420{
1421    if (sender == fNextInfoTabItem)
1422        [fInfoController setNextTab];
1423    else
1424        [fInfoController setPreviousTab];
1425}
1426
1427- (void) showMessageWindow: (id) sender
1428{
1429    [fMessageController showWindow: nil];
1430}
1431
1432- (void) showStatsWindow: (id) sender
1433{
1434    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1435}
1436
1437- (void) updateUI
1438{
1439    [fTorrents makeObjectsPerformSelector: @selector(update)];
1440   
1441    if (![NSApp isHidden])
1442    {
1443        if ([fWindow isVisible])
1444        {
1445            [self sortTorrents];
1446           
1447            //update status bar
1448            if (![fStatusBar isHidden])
1449            {
1450                //set rates
1451                float downloadRate, uploadRate;
1452                tr_sessionGetSpeed(fLib, & downloadRate, & uploadRate);
1453               
1454                [fTotalDLField setStringValue: [NSString stringForSpeed: downloadRate]];
1455                [fTotalULField setStringValue: [NSString stringForSpeed: uploadRate]];
1456               
1457                //set status button text
1458                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1459                BOOL total;
1460                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1461                {
1462                    tr_session_stats stats;
1463                    if (total)
1464                        tr_sessionGetCumulativeStats(fLib, &stats);
1465                    else
1466                        tr_sessionGetStats(fLib, &stats);
1467                   
1468                    statusString = [NSString stringWithFormat: @"%@: %@", NSLocalizedString(@"Ratio", "status bar -> status label"),
1469                                    [NSString stringForRatio: stats.ratio]];
1470                }
1471                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1472                {
1473                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1474                   
1475                    tr_session_stats stats;
1476                    if (total)
1477                        tr_sessionGetCumulativeStats(fLib, &stats);
1478                    else
1479                        tr_sessionGetStats(fLib, &stats);
1480                   
1481                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1482                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1483                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1484                }
1485               
1486                if ([NSApp isOnLeopardOrBetter])
1487                {
1488                    [fStatusButton setTitle: statusString];
1489                    [self resizeStatusButton];
1490                }
1491                else
1492                    [fStatusTigerField setStringValue: statusString];
1493            }
1494        }
1495
1496        //update non-constant parts of info window
1497        if ([[fInfoController window] isVisible])
1498            [fInfoController updateInfoStats];
1499    }
1500   
1501    //badge dock
1502    [fBadger updateBadge];
1503}
1504
1505- (void) resizeStatusButton
1506{
1507    [fStatusButton sizeToFit];
1508   
1509    //width ends up being too long
1510    NSRect statusFrame = [fStatusButton frame];
1511    statusFrame.size.width -= 25.0;
1512   
1513    float difference = NSMaxX(statusFrame) + 5.0 - [fTotalDLImageView frame].origin.x;
1514    if (difference > 0)
1515        statusFrame.size.width -= difference;
1516   
1517    [fStatusButton setFrame: statusFrame];
1518}
1519
1520- (void) setBottomCountText: (BOOL) filtering
1521{
1522    NSString * totalTorrentsString;
1523    int totalCount = [fTorrents count];
1524    if (totalCount != 1)
1525        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1526    else
1527        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1528   
1529    if (filtering)
1530    {
1531        int count = 0, rows = [fTableView numberOfRows];
1532        if (rows > 0 && ![[fTableView itemAtRow: 0] isKindOfClass: [Torrent class]])
1533        {
1534            int i;
1535            for (i = 1; i < rows; i++)
1536                if ([[fTableView itemAtRow: i] isKindOfClass: [Torrent class]])
1537                    count++;
1538        }
1539        else
1540            count = rows;
1541       
1542        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d of %@", "Status bar transfer count"),
1543                                count, totalTorrentsString];
1544    }
1545   
1546    [fTotalTorrentsField setStringValue: totalTorrentsString];
1547}
1548
1549- (void) updateTorrentsInQueue
1550{
1551    BOOL download = [fDefaults boolForKey: @"Queue"],
1552        seed = [fDefaults boolForKey: @"QueueSeed"];
1553   
1554    int desiredDownloadActive = [self numToStartFromQueue: YES],
1555        desiredSeedActive = [self numToStartFromQueue: NO];
1556   
1557    //sort torrents by order value
1558    if ([fTorrents count] > 1 && (desiredDownloadActive > 0 || desiredSeedActive > 0))
1559    {
1560        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: YES] autorelease];
1561        [fTorrents sortUsingDescriptors: [NSArray arrayWithObject: orderDescriptor]];
1562    }
1563   
1564    Torrent * torrent;
1565    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1566    while ((torrent = [enumerator nextObject]))
1567    {
1568        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1569        {
1570            if (![torrent allDownloaded])
1571            {
1572                if (!download || desiredDownloadActive > 0)
1573                {
1574                    [torrent startTransfer];
1575                    if ([torrent isActive])
1576                        desiredDownloadActive--;
1577                    [torrent update];
1578                }
1579            }
1580            else
1581            {
1582                if (!seed || desiredSeedActive > 0)
1583                {
1584                    [torrent startTransfer];
1585                    if ([torrent isActive])
1586                        desiredSeedActive--;
1587                    [torrent update];
1588                }
1589            }
1590        }
1591    }
1592   
1593    [self updateUI];
1594    [self applyFilter: nil];
1595    [self updateTorrentHistory];
1596}
1597
1598- (int) numToStartFromQueue: (BOOL) downloadQueue
1599{
1600    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1601        return 0;
1602   
1603    int desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1604       
1605    Torrent * torrent;
1606    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1607    while ((torrent = [enumerator nextObject]))
1608    {
1609        if ([torrent isChecking])
1610        {
1611            desired--;
1612            if (desired <= 0)
1613                return 0;
1614        }
1615        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1616        {
1617            if ([torrent allDownloaded] != downloadQueue)
1618            {
1619                desired--;
1620                if (desired <= 0)
1621                    return 0;
1622            }
1623        }
1624        else;
1625    }
1626   
1627    return desired;
1628}
1629
1630- (void) torrentFinishedDownloading: (NSNotification *) notification
1631{
1632    Torrent * torrent = [notification object];
1633   
1634    if ([torrent isActive])
1635    {
1636        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1637        {
1638            NSSound * sound;
1639            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1640            {
1641                [sound setDelegate: self];
1642                fSoundPlaying = YES;
1643                [sound play];
1644            }
1645        }
1646       
1647        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1648                                        [torrent dataLocation] , @"Location", nil];
1649        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1650                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1651                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1652       
1653        if (![fWindow isMainWindow])
1654            [fBadger incrementCompleted];
1655       
1656        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1657        {
1658            [torrent stopTransfer];
1659            [torrent setWaitToStart: YES];
1660        }
1661    }
1662   
1663    [self updateTorrentsInQueue];
1664}
1665
1666- (void) torrentRestartedDownloading: (NSNotification *) notification
1667{
1668    Torrent * torrent = [notification object];
1669    if ([torrent isActive])
1670    {
1671        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1672        {
1673            [torrent stopTransfer];
1674            [torrent setWaitToStart: YES];
1675        }
1676    }
1677   
1678    [self updateTorrentsInQueue];
1679}
1680
1681- (void) torrentStoppedForRatio: (NSNotification *) notification
1682{
1683    Torrent * torrent = [notification object];
1684   
1685    [self updateTorrentsInQueue];
1686   
1687    if ([[fTableView selectedTorrents] containsObject: torrent])
1688    {
1689        [fInfoController updateInfoStats];
1690        [fInfoController updateOptions];
1691    }
1692   
1693    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1694    {
1695        NSSound * sound;
1696        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1697        {
1698            [sound setDelegate: self];
1699            fSoundPlaying = YES;
1700            [sound play];
1701        }
1702    }
1703   
1704    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
1705                                    [torrent dataLocation], @"Location", nil];
1706    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1707                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1708                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1709}
1710
1711- (void) updateTorrentHistory
1712{
1713    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1714
1715    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1716    Torrent * torrent;
1717    while ((torrent = [enumerator nextObject]))
1718        [history addObject: [torrent history]];
1719
1720    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER] atomically: YES];
1721}
1722
1723- (void) setSort: (id) sender
1724{
1725    NSString * sortType;
1726    switch ([sender tag])
1727    {
1728        case SORT_ORDER_TAG:
1729            sortType = SORT_ORDER;
1730            [fDefaults setBool: NO forKey: @"SortReverse"];
1731            break;
1732        case SORT_DATE_TAG:
1733            sortType = SORT_DATE;
1734            break;
1735        case SORT_NAME_TAG:
1736            sortType = SORT_NAME;
1737            break;
1738        case SORT_PROGRESS_TAG:
1739            sortType = SORT_PROGRESS;
1740            break;
1741        case SORT_STATE_TAG:
1742            sortType = SORT_STATE;
1743            break;
1744        case SORT_TRACKER_TAG:
1745            sortType = SORT_TRACKER;
1746            break;
1747        case SORT_ACTIVITY_TAG:
1748            sortType = SORT_ACTIVITY;
1749            break;
1750        default:
1751            return;
1752    }
1753   
1754    [fDefaults setObject: sortType forKey: @"Sort"];
1755    [self sortTorrents];
1756}
1757
1758- (void) setSortByGroup: (id) sender
1759{
1760    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1761    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1762   
1763    //expand all groups
1764    if (sortByGroup)
1765        [fTableView removeAllCollapsedGroups];
1766   
1767    [self applyFilter: nil];
1768}
1769
1770- (void) setSortReverse: (id) sender
1771{
1772    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1773    [self sortTorrents];
1774}
1775
1776- (void) sortTorrents
1777{
1778    NSArray * selectedValues = [fTableView selectedValues];
1779   
1780    [self sortTorrentsIgnoreSelected]; //actually sort
1781   
1782    [fTableView selectValues: selectedValues];
1783}
1784
1785- (void) sortTorrentsIgnoreSelected
1786{
1787    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1788    BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1789   
1790    NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: asc] autorelease];
1791   
1792    NSArray * descriptors;
1793    if ([sortType isEqualToString: SORT_ORDER])
1794        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1795    else if ([sortType isEqualToString: SORT_NAME])
1796    {
1797        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1798                                                selector: @selector(caseInsensitiveCompare:)] autorelease];
1799       
1800        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1801    }
1802    else if ([sortType isEqualToString: SORT_STATE])
1803    {
1804        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1805                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1806                        * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1807                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1808                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1809       
1810        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1811                                                            nameDescriptor, orderDescriptor, nil];
1812    }
1813    else if ([sortType isEqualToString: SORT_PROGRESS])
1814    {
1815        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1816                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1817                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1818                        * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1819                                                        ascending: asc] autorelease],
1820                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1821       
1822        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1823                                                            nameDescriptor, orderDescriptor, nil];
1824    }
1825    else if ([sortType isEqualToString: SORT_TRACKER])
1826    {
1827        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1828                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1829                        * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddressAnnounce" ascending: asc
1830                                                selector: @selector(caseInsensitiveCompare:)] autorelease];
1831       
1832        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, orderDescriptor, nil];
1833    }
1834    else if ([sortType isEqualToString: SORT_ACTIVITY])
1835    {
1836        NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1837        NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1838                                                    autorelease];
1839       
1840        descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, orderDescriptor, nil];
1841    }
1842    else
1843    {
1844        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1845   
1846        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1847    }
1848   
1849    //on Tiger add the group sort descriptor to the front
1850    if (![NSApp isOnLeopardOrBetter] && [fDefaults boolForKey: @"SortByGroup"])
1851    {
1852        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
1853       
1854        NSMutableArray * temp = [[NSMutableArray alloc] initWithCapacity: [descriptors count]+1];
1855        [temp addObject: groupDescriptor];
1856        [temp addObjectsFromArray: descriptors];
1857       
1858        [descriptors release];
1859        descriptors = temp;
1860    }
1861   
1862    //actually sort
1863    if ([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
1864    {
1865        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1866        NSDictionary * dict;
1867        while ((dict = [enumerator nextObject]))
1868            [[dict objectForKey: @"Torrents"] sortUsingDescriptors: descriptors];
1869    }
1870    else
1871        [fDisplayedTorrents sortUsingDescriptors: descriptors];
1872   
1873    [descriptors release];
1874   
1875    [fTableView reloadData];
1876}
1877
1878- (void) applyFilter: (id) sender
1879{
1880    //get all the torrents in the table
1881    NSMutableArray * previousTorrents;
1882    if ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1883    {
1884        previousTorrents = [NSMutableArray array];
1885       
1886        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1887        NSDictionary * dict;
1888        while ((dict = [enumerator nextObject]))
1889            [previousTorrents addObjectsFromArray: [dict objectForKey: @"Torrents"]];
1890    }
1891    else
1892        previousTorrents = fDisplayedTorrents;
1893   
1894    NSArray * selectedValues = [fTableView selectedValues];
1895   
1896    int active = 0, downloading = 0, seeding = 0, paused = 0;
1897    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1898    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1899    if ([filterType isEqualToString: FILTER_ACTIVE])
1900        filterActive = YES;
1901    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1902        filterDownload = YES;
1903    else if ([filterType isEqualToString: FILTER_SEED])
1904        filterSeed = YES;
1905    else if ([filterType isEqualToString: FILTER_PAUSE])
1906        filterPause = YES;
1907    else
1908        filterStatus = NO;
1909   
1910    int groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
1911    BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
1912   
1913    NSString * searchString = [fSearchFilterField stringValue];
1914    BOOL filterText = [searchString length] > 0,
1915        filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
1916   
1917    NSMutableIndexSet * indexes = [NSMutableIndexSet indexSet];
1918   
1919    //get count of each type
1920    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1921    Torrent * torrent;
1922    int i = -1;
1923    while ((torrent = [enumerator nextObject]))
1924    {
1925        i++;
1926       
1927        //check status
1928        if ([torrent isActive] && ![torrent isCheckingWaiting])
1929        {
1930            if ([torrent isSeeding])
1931            {
1932                seeding++;
1933                BOOL isActive = ![torrent isStalled];
1934                if (isActive)
1935                    active++;
1936               
1937                if (filterStatus && (!(filterActive && isActive) && !filterSeed))
1938                    continue;
1939            }
1940            else
1941            {
1942                downloading++;
1943                BOOL isActive = ![torrent isStalled];
1944                if (isActive)
1945                    active++;
1946               
1947                if (filterStatus && (!(filterActive && isActive) && !filterDownload))
1948                    continue;
1949            }
1950        }
1951        else
1952        {
1953            paused++;
1954            if (filterStatus && !filterPause)
1955                continue;
1956        }
1957       
1958        //checkGroup
1959        if (filterGroup)
1960            if ([torrent groupValue] != groupFilterValue)
1961                continue;
1962       
1963        //check text field
1964        if (filterText)
1965        {
1966            if (filterTracker)
1967            {
1968                BOOL removeTextField = YES;
1969                NSEnumerator * trackerEnumerator = [[torrent allTrackers: NO] objectEnumerator];
1970                NSString * tracker;
1971                while ((tracker = [trackerEnumerator nextObject]))
1972                {
1973                    if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1974                    {
1975                        removeTextField = NO;
1976                        break;
1977                    }
1978                }
1979               
1980                if (removeTextField)
1981                    continue;
1982            }
1983            else
1984            {
1985                if ([[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound)
1986                    continue;
1987            }
1988        }
1989       
1990        [indexes addIndex: i];
1991    }
1992   
1993    NSArray * allTorrents = [fTorrents objectsAtIndexes: indexes];
1994   
1995    //set button tooltips
1996    [fNoFilterButton setCount: [fTorrents count]];
1997    [fActiveFilterButton setCount: active];
1998    [fDownloadFilterButton setCount: downloading];
1999    [fSeedFilterButton setCount: seeding];
2000    [fPauseFilterButton setCount: paused];
2001   
2002    //clear display cache for not-shown torrents
2003    [previousTorrents removeObjectsInArray: allTorrents];
2004    enumerator = [previousTorrents objectEnumerator];
2005    while ((torrent = [enumerator nextObject]))
2006        [torrent setPreviousFinishedPieces: nil];
2007   
2008    //place torrents into groups
2009    BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter];
2010    if (groupRows)
2011    {
2012        [fDisplayedTorrents removeAllObjects];
2013       
2014        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2015        allTorrents = [allTorrents sortedArrayUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2016       
2017        NSMutableArray * groupTorrents;
2018        int oldGroupValue = -2;
2019        for (i = 0; i < [allTorrents count]; i++)
2020        {
2021            torrent = [allTorrents objectAtIndex: i];
2022            int groupValue = [torrent groupValue];
2023            if (groupValue != oldGroupValue)
2024            {
2025                groupTorrents = [NSMutableArray array];
2026                NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt: groupValue], @"Group",
2027                                        groupTorrents, @"Torrents", nil];
2028                [fDisplayedTorrents addObject: dict];
2029               
2030                oldGroupValue = groupValue;
2031            }
2032           
2033            [groupTorrents addObject: torrent];
2034        }
2035    }
2036    else
2037        [fDisplayedTorrents setArray: allTorrents];
2038   
2039    //actually sort
2040    [self sortTorrentsIgnoreSelected];
2041    [fTableView selectValues: selectedValues];
2042   
2043    //reset expanded/collapsed rows
2044    if (groupRows)
2045    {
2046        enumerator = [fDisplayedTorrents objectEnumerator];
2047        NSDictionary * dict;
2048        while ((dict = [enumerator nextObject]))
2049        {
2050            if ([fTableView isGroupCollapsed: [[dict objectForKey: @"Group"] intValue]])
2051                [fTableView collapseItem: dict];
2052            else
2053                [fTableView expandItem: dict];
2054        }
2055    }
2056   
2057    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2058   
2059    [self setWindowSizeToFit];
2060}
2061
2062//resets filter and sorts torrents
2063- (void) setFilter: (id) sender
2064{
2065    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2066   
2067    NSButton * prevFilterButton;
2068    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2069        prevFilterButton = fPauseFilterButton;
2070    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2071        prevFilterButton = fActiveFilterButton;
2072    else if ([oldFilterType isEqualToString: FILTER_SEED])
2073        prevFilterButton = fSeedFilterButton;
2074    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2075        prevFilterButton = fDownloadFilterButton;
2076    else
2077        prevFilterButton = fNoFilterButton;
2078   
2079    if (sender != prevFilterButton)
2080    {
2081        [prevFilterButton setState: NSOffState];
2082        [sender setState: NSOnState];
2083
2084        NSString * filterType;
2085        if (sender == fActiveFilterButton)
2086            filterType = FILTER_ACTIVE;
2087        else if (sender == fDownloadFilterButton)
2088            filterType = FILTER_DOWNLOAD;
2089        else if (sender == fPauseFilterButton)
2090            filterType = FILTER_PAUSE;
2091        else if (sender == fSeedFilterButton)
2092            filterType = FILTER_SEED;
2093        else
2094            filterType = FILTER_NONE;
2095
2096        [fDefaults setObject: filterType forKey: @"Filter"];
2097    }
2098    else
2099        [sender setState: NSOnState];
2100
2101    [self applyFilter: nil];
2102}
2103
2104- (void) setFilterSearchType: (id) sender
2105{
2106    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2107   
2108    int prevTag, currentTag = [sender tag];
2109    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2110        prevTag = FILTER_TYPE_TAG_TRACKER;
2111    else
2112        prevTag = FILTER_TYPE_TAG_NAME;
2113   
2114    if (currentTag != prevTag)
2115    {
2116        NSString * filterType;
2117        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2118            filterType = FILTER_TYPE_TRACKER;
2119        else
2120            filterType = FILTER_TYPE_NAME;
2121       
2122        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2123       
2124        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2125    }
2126   
2127    [self applyFilter: nil];
2128}
2129
2130- (void) switchFilter: (id) sender
2131{
2132    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2133   
2134    NSButton * button;
2135    if ([filterType isEqualToString: FILTER_NONE])
2136        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2137    else if ([filterType isEqualToString: FILTER_ACTIVE])
2138        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2139    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2140        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2141    else if ([filterType isEqualToString: FILTER_SEED])
2142        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2143    else if ([filterType isEqualToString: FILTER_PAUSE])
2144        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2145    else
2146        button = fNoFilterButton;
2147   
2148    [self setFilter: button];
2149}
2150
2151- (void) setStatusLabel: (id) sender
2152{
2153    NSString * statusLabel;
2154    switch ([sender tag])
2155    {
2156        case STATUS_RATIO_TOTAL_TAG:
2157            statusLabel = STATUS_RATIO_TOTAL;
2158            break;
2159        case STATUS_RATIO_SESSION_TAG:
2160            statusLabel = STATUS_RATIO_SESSION;
2161            break;
2162        case STATUS_TRANSFER_TOTAL_TAG:
2163            statusLabel = STATUS_TRANSFER_TOTAL;
2164            break;
2165        case STATUS_TRANSFER_SESSION_TAG:
2166            statusLabel = STATUS_TRANSFER_SESSION;
2167            break;
2168        default:
2169            return;
2170    }
2171   
2172    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2173    [self updateUI];
2174}
2175
2176- (void) showGroups: (id) sender
2177{
2178    [[GroupsWindowController groupsWindow] showWindow: self];
2179}
2180
2181- (void) menuNeedsUpdate: (NSMenu *) menu
2182{
2183    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2184    {
2185        int i;
2186        for (i = [menu numberOfItems]-1 - 2; i >= 0; i--)
2187            [menu removeItemAtIndex: i];
2188       
2189        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2190        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2191                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: NO];
2192    }
2193    else if (menu == fGroupFilterMenu)
2194    {
2195        int i;
2196        for (i = [menu numberOfItems]-1; i >= 3; i--)
2197            [menu removeItemAtIndex: i];
2198       
2199        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:)
2200                                isSmall: YES];
2201        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2202                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: YES];
2203    }
2204    else if (menu == fUploadMenu || menu == fDownloadMenu)
2205    {
2206        if ([menu numberOfItems] > 3)
2207            return;
2208       
2209        const int speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, -1 };
2210       
2211        NSMenuItem * item;
2212        int i;
2213        for (i = 0; speedLimitActionValue[i] != -1; i++)
2214        {
2215            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2216                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2217                    keyEquivalent: @""];
2218            [item setTarget: self];
2219            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2220            [menu addItem: item];
2221            [item release];
2222        }
2223    }
2224    else if (menu == fRatioStopMenu)
2225    {
2226        if ([menu numberOfItems] > 3)
2227            return;
2228       
2229        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2230       
2231        NSMenuItem * item;
2232        int i;
2233        for (i = 0; ratioLimitActionValue[i] != -1; i++)
2234        {
2235            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2236                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2237            [item setTarget: self];
2238            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2239            [menu addItem: item];
2240            [item release];
2241        }
2242    }
2243    else;
2244}
2245
2246- (void) setGroup: (id) sender
2247{
2248    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
2249    Torrent * torrent;
2250    while ((torrent = [enumerator nextObject]))
2251    {
2252        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2253       
2254        [torrent setGroupValue: [sender tag]];
2255    }
2256   
2257    [self applyFilter: nil];
2258    [self updateUI];
2259    [self updateTorrentHistory];
2260}
2261
2262- (void) setGroupFilter: (id) sender
2263{
2264    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2265    [self updateGroupsFilterButton];
2266    [self applyFilter: nil];
2267}
2268
2269- (void) updateGroupsFilterButton
2270{
2271    int groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2272   
2273    NSImage * icon;
2274    NSString * toolTip;
2275    if (groupIndex == GROUP_FILTER_ALL_TAG)
2276    {
2277        icon = [NSImage imageNamed: @"PinTemplate.png"];
2278        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2279    }
2280    else
2281    {
2282        icon = [[GroupsController groups] imageForIndex: groupIndex];
2283        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2284                                                : NSLocalizedString(@"None", "Groups -> Button");
2285        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2286    }
2287   
2288    //tiger doesn't have built-in image scaling in buttons
2289    if (![NSApp isOnLeopardOrBetter])
2290    {
2291        icon = [[icon copy] autorelease];
2292        [icon setScalesWhenResized: YES];
2293        [icon setSize: NSMakeSize(12.0, 12.0)];
2294    }
2295   
2296    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2297    [fGroupsButton setToolTip: toolTip];
2298}
2299
2300- (void) updateGroupsFilters: (NSNotification *) notification
2301{
2302    [self updateGroupsFilterButton];
2303    [self applyFilter: nil];
2304}
2305
2306- (void) toggleSpeedLimit: (id) sender
2307{
2308    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2309    [fPrefsController applySpeedSettings: nil];
2310}
2311
2312- (void) autoSpeedLimitChange: (NSNotification *) notification
2313{
2314    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2315        return;
2316 
2317    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2318                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
2319        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2320                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
2321        * nowDate = [NSCalendarDate calendarDate];
2322   
2323    //check if should be on if within range
2324    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
2325        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
2326        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
2327   
2328    BOOL shouldBeOn = NO;
2329    if (onTime < offTime)
2330        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2331    else if (onTime > offTime)
2332        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2333    else;
2334   
2335    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2336        [self toggleSpeedLimit: nil];
2337}
2338
2339- (void) autoSpeedLimit
2340{
2341    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2342        return;
2343   
2344    //only toggle if within first few seconds of minutes
2345    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
2346    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
2347        return;
2348   
2349    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2350                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
2351   
2352    BOOL toggle;
2353    if ([fDefaults boolForKey: @"SpeedLimit"])
2354        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
2355    else
2356    {
2357        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2358                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
2359        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
2360                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
2361    }
2362   
2363    if (toggle)
2364    {
2365        [self toggleSpeedLimit: nil];
2366       
2367        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2368                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2369                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2370            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2371            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2372    }
2373}
2374
2375- (void) setLimitGlobalEnabled: (id) sender
2376{
2377    BOOL upload = [sender menu] == fUploadMenu;
2378    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2379   
2380    [fPrefsController applySpeedSettings: nil];
2381}
2382
2383- (void) setQuickLimitGlobal: (id) sender
2384{
2385    BOOL upload = [sender menu] == fUploadMenu;
2386    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2387    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2388   
2389    [fPrefsController updateLimitFields];
2390    [fPrefsController applySpeedSettings: nil];
2391}
2392
2393- (void) setRatioGlobalEnabled: (id) sender
2394{
2395    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2396}
2397
2398- (void) setQuickRatioGlobal: (id) sender
2399{
2400    [fDefaults setBool: YES forKey: @"RatioCheck"];
2401    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2402   
2403    [fPrefsController updateRatioStopField];
2404}
2405
2406- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2407{
2408    fSoundPlaying = NO;
2409}
2410
2411- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2412{
2413    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2414    {
2415        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2416            return;
2417       
2418        if (fAutoImportTimer)
2419        {
2420            if ([fAutoImportTimer isValid])
2421                [fAutoImportTimer invalidate];
2422            [fAutoImportTimer release];
2423            fAutoImportTimer = nil;
2424        }
2425       
2426        //check again in 10 seconds in case torrent file wasn't complete
2427        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2428            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2429       
2430        [self checkAutoImportDirectory];
2431    }
2432}
2433
2434- (void) changeAutoImport
2435{
2436    if (fAutoImportTimer)
2437    {
2438        if ([fAutoImportTimer isValid])
2439            [fAutoImportTimer invalidate];
2440        [fAutoImportTimer release];
2441        fAutoImportTimer = nil;
2442    }
2443   
2444    if (fAutoImportedNames)
2445    {
2446        [fAutoImportedNames release];
2447        fAutoImportedNames = nil;
2448    }
2449   
2450    [self checkAutoImportDirectory];
2451}
2452
2453- (void) checkAutoImportDirectory
2454{
2455    NSString * path;
2456    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2457        return;
2458   
2459    path = [path stringByExpandingTildeInPath];
2460   
2461    NSArray * importedNames;
2462    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2463        return;
2464   
2465    //only check files that have not been checked yet
2466    NSMutableArray * newNames = [importedNames mutableCopy];
2467   
2468    if (fAutoImportedNames)
2469        [newNames removeObjectsInArray: fAutoImportedNames];
2470    else
2471        fAutoImportedNames = [[NSMutableArray alloc] init];
2472    [fAutoImportedNames setArray: importedNames];
2473   
2474    NSString * file;
2475    int i;
2476    for (i = [newNames count] - 1; i >= 0; i--)
2477    {
2478        file = [newNames objectAtIndex: i];
2479        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2480            [newNames removeObjectAtIndex: i];
2481        else
2482            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2483    }
2484   
2485    NSEnumerator * enumerator = [newNames objectEnumerator];
2486    tr_ctor * ctor;
2487    while ((file = [enumerator nextObject]))
2488    {
2489        ctor = tr_ctorNew(fLib);
2490        tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2491       
2492        switch (tr_torrentParse(fLib, ctor, NULL))
2493        {
2494            case TR_OK:
2495                [self openFiles: [NSArray arrayWithObject: file] addType: ADD_AUTO forcePath: nil];
2496               
2497                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2498                    description: [file lastPathComponent] notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2499                    clickContext: nil];
2500                break;
2501           
2502            case TR_EINVALID:
2503                [fAutoImportedNames removeObject: [file lastPathComponent]];
2504        }
2505       
2506        tr_ctorFree(ctor);
2507    }
2508   
2509    [newNames release];
2510}
2511
2512- (void) beginCreateFile: (NSNotification *) notification
2513{
2514    if (![fDefaults boolForKey: @"AutoImport"])
2515        return;
2516   
2517    NSString * location = [notification object],
2518            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2519   
2520    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2521                                    isEqualToString: [path stringByExpandingTildeInPath]])
2522        [fAutoImportedNames addObject: [location lastPathComponent]];
2523}
2524
2525- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2526{
2527    if (item)
2528        return [[item objectForKey: @"Torrents"] count];
2529    else
2530        return [fDisplayedTorrents count];
2531}
2532
2533- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2534{
2535    if (item)
2536        return [[item objectForKey: @"Torrents"] objectAtIndex: index];
2537    else
2538        return [fDisplayedTorrents objectAtIndex: index];
2539}
2540
2541- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2542{
2543    return ![item isKindOfClass: [Torrent class]];
2544}
2545
2546- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2547{
2548    if ([item isKindOfClass: [Torrent class]])
2549        return [item hashString];
2550    else
2551    {
2552        NSString * ident = [tableColumn identifier];
2553        if ([ident isEqualToString: @"Group"])
2554        {
2555            int group = [[item objectForKey: @"Group"] intValue];
2556            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2557                                : NSLocalizedString(@"No Group", "Group table row");
2558        }
2559        else if ([ident isEqualToString: @"Color"])
2560        {
2561            int group = [[item objectForKey: @"Group"] intValue];
2562            return [[GroupsController groups] imageForIndex: group];
2563        }
2564        else if ([ident isEqualToString: @"DL Image"])
2565            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2566        else if ([ident isEqualToString: @"UL Image"])
2567            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2568                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2569        else
2570        {
2571            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2572            {
2573                uint64_t uploaded = 0, downloaded = 0;
2574                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2575                Torrent * torrent;
2576                while ((torrent = [enumerator nextObject]))
2577                {
2578                    uploaded += [torrent uploadedTotal];
2579                    downloaded += [torrent downloadedTotal];
2580                }
2581               
2582                return [NSString stringForRatio: tr_getRatio(uploaded, downloaded)];
2583            }
2584            else
2585            {
2586                BOOL upload = [ident isEqualToString: @"UL"];
2587               
2588                float rate = 0.0;
2589                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2590                Torrent * torrent;
2591                while ((torrent = [enumerator nextObject]))
2592                    rate += upload ? [torrent uploadRate] : [torrent downloadRate];
2593               
2594                return [NSString stringForSpeed: rate];
2595            }
2596        }
2597    }
2598}
2599
2600- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2601{
2602    //only allow reordering of rows if sorting by order
2603    if (([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
2604        || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2605    {
2606        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2607        NSEnumerator * enumerator = [items objectEnumerator];
2608        id torrent;
2609        while ((torrent = [enumerator nextObject]))
2610        {
2611            if (![torrent isKindOfClass: [Torrent class]])
2612                return NO;
2613           
2614            [indexSet addIndex: [fTableView rowForItem: torrent]];
2615        }
2616       
2617        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2618        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2619        return YES;
2620    }
2621    return NO;
2622}
2623
2624- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2625    proposedChildIndex: (NSInteger) index
2626{
2627    NSPasteboard * pasteboard = [info draggingPasteboard];
2628    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2629    {
2630        if ([fDefaults boolForKey: @"SortByGroup"])
2631        {
2632            if (!item)
2633                return NSDragOperationNone;
2634           
2635            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2636            {
2637                if ([item isKindOfClass: [Torrent class]])
2638                {
2639                    NSDictionary * group = [fTableView parentForItem: item];
2640                    index = [[group objectForKey: @"Torrents"] indexOfObject: item] + 1;
2641                    item = group;
2642                }
2643            }
2644            else
2645            {
2646                if ([item isKindOfClass: [Torrent class]])
2647                    item = [fTableView parentForItem: item];
2648                index = NSOutlineViewDropOnItemIndex;
2649            }
2650        }
2651        else
2652        {
2653            if (item)
2654            {
2655                index = [fTableView rowForItem: item] + 1;
2656                item = nil;
2657            }
2658        }
2659       
2660        [fTableView setDropItem: item dropChildIndex: index];
2661        return NSDragOperationGeneric;
2662    }
2663   
2664    return NSDragOperationNone;
2665}
2666
2667- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2668    childIndex: (NSInteger) newRow
2669{
2670    NSPasteboard * pasteboard = [info draggingPasteboard];
2671    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2672    {
2673        //remember selected rows
2674        NSArray * selectedValues = [fTableView selectedValues];
2675   
2676        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2677       
2678        //get the torrents to move
2679        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2680        int i;
2681        for (i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2682            [movingTorrents addObject: [fTableView itemAtRow: i]];
2683       
2684        //reset groups
2685        if (item)
2686        {
2687            //change groups
2688            int groupValue = [[item objectForKey: @"Group"] intValue];
2689            NSEnumerator * enumerator = [movingTorrents objectEnumerator];
2690            Torrent * torrent;
2691            while ((torrent = [enumerator nextObject]))
2692            {
2693                //have to reset objects here to avoid weird crash
2694                [[[fTableView parentForItem: torrent] objectForKey: @"Torrent"] removeObject: torrent];
2695                [[item objectForKey: @"Torrent"] addObject: torrent];
2696               
2697                [torrent setGroupValue: groupValue];
2698            }
2699            //part 2 of avoiding weird crash
2700            [fTableView reloadItem: nil reloadChildren: YES];
2701        }
2702       
2703        //reorder queue order
2704        if (newRow != NSOutlineViewDropOnItemIndex)
2705        {
2706            //find torrent to place under
2707            NSArray * groupTorrents = item ? [item objectForKey: @"Torrents"] : fDisplayedTorrents;
2708            Torrent * topTorrent = nil;
2709            for (i = newRow-1; i >= 0; i--)
2710            {
2711                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2712                if (![movingTorrents containsObject: tempTorrent])
2713                {
2714                    topTorrent = tempTorrent;
2715                    break;
2716                }
2717            }
2718           
2719            //remove objects to reinsert
2720            [fTorrents removeObjectsInArray: movingTorrents];
2721           
2722            //get all torrents to reorder
2723            NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: YES] autorelease];
2724            [fTorrents sortUsingDescriptors: [NSArray arrayWithObject: orderDescriptor]];
2725           
2726            //insert objects at new location
2727            int insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2728            for (i = 0; i < [movingTorrents count]; i++)
2729                [fTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2730           
2731            //redo order values
2732            for (i = 0; i < [fTorrents count]; i++)
2733                [[fTorrents objectAtIndex: i] setOrderValue: i];
2734        }
2735       
2736        [self applyFilter: nil];
2737       
2738        //set selected rows
2739        [fTableView selectValues: selectedValues];
2740    }
2741   
2742    return YES;
2743}
2744
2745- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2746{
2747    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
2748    [[QuickLookController quickLook] updateQuickLook];
2749}
2750
2751- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2752{
2753    NSPasteboard * pasteboard = [info draggingPasteboard];
2754    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2755    {
2756        //check if any torrent files can be added
2757        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2758        NSEnumerator * enumerator = [files objectEnumerator];
2759        NSString * file;
2760        BOOL torrent = NO;
2761        tr_ctor * ctor;
2762        while ((file = [enumerator nextObject]))
2763        {
2764            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2765            {
2766                ctor = tr_ctorNew(fLib);
2767                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2768                switch (tr_torrentParse(fLib, ctor, NULL))
2769                {
2770                    case TR_OK:
2771                        if (!fOverlayWindow)
2772                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2773                        [fOverlayWindow setTorrents: files];
2774                       
2775                        return NSDragOperationCopy;
2776                   
2777                    case TR_EDUPLICATE:
2778                        torrent = YES;
2779                }
2780                tr_ctorFree(ctor);
2781            }
2782        }
2783       
2784        //create a torrent file if a single file
2785        if (!torrent && [files count] == 1)
2786        {
2787            if (!fOverlayWindow)
2788                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2789            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2790           
2791            return NSDragOperationCopy;
2792        }
2793    }
2794    else if ([[pasteboard types] containsObject: NSURLPboardType])
2795    {
2796        if (!fOverlayWindow)
2797            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2798        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2799       
2800        return NSDragOperationCopy;
2801    }
2802    else;
2803   
2804    return NSDragOperationNone;
2805}
2806
2807- (void) draggingExited: (id <NSDraggingInfo>) info
2808{
2809    if (fOverlayWindow)
2810        [fOverlayWindow fadeOut];
2811}
2812
2813- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2814{
2815    if (fOverlayWindow)
2816        [fOverlayWindow fadeOut];
2817   
2818    NSPasteboard * pasteboard = [info draggingPasteboard];
2819    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2820    {
2821        BOOL torrent = NO, accept = YES;
2822       
2823        //create an array of files that can be opened
2824        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2825        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2826        NSEnumerator * enumerator = [files objectEnumerator];
2827        NSString * file;
2828        tr_ctor * ctor;
2829        while ((file = [enumerator nextObject]))
2830        {
2831            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2832            {
2833                ctor = tr_ctorNew(fLib);
2834                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2835                switch (tr_torrentParse(fLib, ctor, NULL))
2836                {
2837                    case TR_OK:
2838                        [filesToOpen addObject: file];
2839                        torrent = YES;
2840                        break;
2841                       
2842                    case TR_EDUPLICATE:
2843                        torrent = YES;
2844                }
2845                tr_ctorFree(ctor);
2846            }
2847        }
2848       
2849        if ([filesToOpen count] > 0)
2850            [self application: NSApp openFiles: filesToOpen];
2851        else
2852        {
2853            if (!torrent && [files count] == 1)
2854                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2855            else
2856                accept = NO;
2857        }
2858        [filesToOpen release];
2859       
2860        return accept;
2861    }
2862    else if ([[pasteboard types] containsObject: NSURLPboardType])
2863    {
2864        NSURL * url;
2865        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2866        {
2867            [self openURL: url];
2868            return YES;
2869        }
2870    }
2871    else;
2872   
2873    return NO;
2874}
2875
2876- (void) toggleSmallView: (id) sender
2877{
2878    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2879    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2880   
2881    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2882   
2883    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2884   
2885    //window min height
2886    NSSize contentMinSize = [fWindow contentMinSize],
2887            contentSize = [[fWindow contentView] frame].size;
2888    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2889                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2890    [fWindow setContentMinSize: contentMinSize];
2891   
2892    //resize for larger min height if not set to auto size
2893    if (![fDefaults boolForKey: @"AutoSize"])
2894    {
2895        if (!makeSmall && contentSize.height < contentMinSize.height)
2896        {
2897            NSRect frame = [fWindow frame];
2898            float heightChange = contentMinSize.height - contentSize.height;
2899            frame.size.height += heightChange;
2900            frame.origin.y -= heightChange;
2901           
2902            [fWindow setFrame: frame display: YES];
2903        }
2904    }
2905    else
2906        [self setWindowSizeToFit];
2907}
2908
2909- (void) togglePiecesBar: (id) sender
2910{
2911    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2912    [fTableView togglePiecesBar];
2913}
2914
2915- (void) toggleAvailabilityBar: (id) sender
2916{
2917    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2918    [fTableView display];
2919}
2920
2921- (void) toggleStatusString: (id) sender
2922{
2923    if ([fDefaults boolForKey: @"SmallView"])
2924        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2925    else
2926        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2927   
2928    [fTableView reloadData];
2929}
2930
2931- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2932{
2933    NSScrollView * scrollView = [fTableView enclosingScrollView];
2934   
2935    //convert pixels to points
2936    NSRect windowFrame = [fWindow frame];
2937    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2938    windowSize.height += height;
2939   
2940    if (check)
2941    {
2942        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2943       
2944        if (windowSize.height < minSize.height)
2945            windowSize.height = minSize.height;
2946        else
2947        {
2948            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2949            if ([fStatusBar isHidden])
2950                maxSize.height -= [fStatusBar frame].size.height;
2951            if ([fFilterBar isHidden])
2952                maxSize.height -= [fFilterBar frame].size.height;
2953            if (windowSize.height > maxSize.height)
2954                windowSize.height = maxSize.height;
2955        }
2956    }
2957
2958    //convert points to pixels
2959    windowSize = [scrollView convertSize: windowSize toView: nil];
2960
2961    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2962    windowFrame.size.height = windowSize.height;
2963    return windowFrame;
2964}
2965
2966- (void) toggleStatusBar: (id) sender
2967{
2968    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2969    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2970}
2971
2972//doesn't save shown state
2973- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2974{
2975    if (show != [fStatusBar isHidden])
2976        return;
2977
2978    if (show)
2979        [fStatusBar setHidden: NO];
2980
2981    NSRect frame;
2982    float heightChange = [fStatusBar frame].size.height;
2983    if (!show)
2984        heightChange *= -1;
2985   
2986    //allow bar to show even if not enough room
2987    if (show && ![fDefaults boolForKey: @"AutoSize"])
2988    {
2989        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2990        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2991        if (change < 0.0)
2992        {
2993            frame = [fWindow frame];
2994            frame.size.height += change;
2995            frame.origin.y -= change;
2996            [fWindow setFrame: frame display: NO animate: NO];
2997        }
2998    }
2999
3000    [self updateUI];
3001   
3002    NSScrollView * scrollView = [fTableView enclosingScrollView];
3003   
3004    //set views to not autoresize
3005    unsigned int statsMask = [fStatusBar autoresizingMask];
3006    unsigned int filterMask = [fFilterBar autoresizingMask];
3007    unsigned int scrollMask = [scrollView autoresizingMask];
3008    [fStatusBar setAutoresizingMask: NSViewNotSizable];
3009    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3010    [scrollView setAutoresizingMask: NSViewNotSizable];
3011   
3012    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3013    [fWindow setFrame: frame display: YES animate: animate];
3014   
3015    //re-enable autoresize
3016    [fStatusBar setAutoresizingMask: statsMask];
3017    [fFilterBar setAutoresizingMask: filterMask];
3018    [scrollView setAutoresizingMask: scrollMask];
3019   
3020    //change min size
3021    NSSize minSize = [fWindow contentMinSize];
3022    minSize.height += heightChange;
3023    [fWindow setContentMinSize: minSize];
3024   
3025    if (!show)
3026        [fStatusBar setHidden: YES];
3027}
3028
3029- (void) toggleFilterBar: (id) sender
3030{
3031    //disable filtering when hiding
3032    if (![fFilterBar isHidden])
3033    {
3034        [fSearchFilterField setStringValue: @""];
3035        [self setFilter: fNoFilterButton];
3036        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3037    }
3038
3039    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3040    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3041}
3042
3043//doesn't save shown state
3044- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3045{
3046    if (show != [fFilterBar isHidden])
3047        return;
3048
3049    if (show)
3050        [fFilterBar setHidden: NO];
3051
3052    NSRect frame;
3053    float heightChange = [fFilterBar frame].size.height;
3054    if (!show)
3055        heightChange *= -1;
3056   
3057    //allow bar to show even if not enough room
3058    if (show && ![fDefaults boolForKey: @"AutoSize"])
3059    {
3060        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3061        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3062        if (change < 0.0)
3063        {
3064            frame = [fWindow frame];
3065            frame.size.height += change;
3066            frame.origin.y -= change;
3067            [fWindow setFrame: frame display: NO animate: NO];
3068        }
3069    }
3070   
3071    NSScrollView * scrollView = [fTableView enclosingScrollView];
3072
3073    //set views to not autoresize
3074    unsigned int filterMask = [fFilterBar autoresizingMask];
3075    unsigned int scrollMask = [scrollView autoresizingMask];
3076    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3077    [scrollView setAutoresizingMask: NSViewNotSizable];
3078   
3079    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3080    [fWindow setFrame: frame display: YES animate: animate];
3081   
3082    //re-enable autoresize
3083    [fFilterBar setAutoresizingMask: filterMask];
3084    [scrollView setAutoresizingMask: scrollMask];
3085   
3086    //change min size
3087    NSSize minSize = [fWindow contentMinSize];
3088    minSize.height += heightChange;
3089    [fWindow setContentMinSize: minSize];
3090   
3091    if (!show)
3092    {
3093        [fFilterBar setHidden: YES];
3094        [fWindow makeFirstResponder: fTableView];
3095    }
3096}
3097
3098- (void) focusFilterField
3099{
3100    [fWindow makeFirstResponder: fSearchFilterField];
3101    if ([fFilterBar isHidden])
3102        [self toggleFilterBar: self];
3103}
3104
3105- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3106{
3107    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3108   
3109    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3110    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3111    [button setStringValue: @""];
3112   
3113    [item setView: button];
3114    [button release];
3115   
3116    NSSize buttonSize = NSMakeSize(36.0, 25.0);
3117    [item setMinSize: buttonSize];
3118    [item setMaxSize: buttonSize];
3119   
3120    return [item autorelease];
3121}
3122
3123- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3124{
3125    if ([ident isEqualToString: TOOLBAR_CREATE])
3126    {
3127        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3128       
3129        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3130        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3131        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3132        [item setImage: [NSImage imageNamed: @"Create.png"]];
3133        [item setTarget: self];
3134        [item setAction: @selector(createFile:)];
3135        [item setAutovalidates: NO];
3136       
3137        return item;
3138    }
3139    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3140    {
3141        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3142       
3143        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3144        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3145        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3146        [item setImage: [NSImage imageNamed: @"Open.png"]];
3147        [item setTarget: self];
3148        [item setAction: @selector(openShowSheet:)];
3149        [item setAutovalidates: NO];
3150       
3151        return item;
3152    }
3153    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3154    {
3155        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3156       
3157        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3158        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3159        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3160        [item setImage: [NSImage imageNamed: @"OpenWeb.png"]];
3161        [item setTarget: self];
3162        [item setAction: @selector(openURLShowSheet:)];
3163        [item setAutovalidates: NO];
3164       
3165        return item;
3166    }
3167    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3168    {
3169        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3170       
3171        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3172        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3173        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3174        [item setImage: [NSImage imageNamed: @"Remove.png"]];
3175        [item setTarget: self];
3176        [item setAction: @selector(removeNoDelete:)];
3177       
3178        return item;
3179    }
3180    else if ([ident isEqualToString: TOOLBAR_INFO])
3181    {
3182        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3183       
3184        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3185        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3186        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3187        [item setImage: [NSImage imageNamed: @"Info.png"]];
3188        [item setTarget: self];
3189        [item setAction: @selector(showInfo:)];
3190       
3191        return item;
3192    }
3193    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3194    {
3195        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3196       
3197        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3198        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3199        [groupItem setView: segmentedControl];
3200        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3201       
3202        [segmentedControl setSegmentCount: 2];
3203        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3204       
3205        NSSize groupSize = NSMakeSize(72.0, 25.0);
3206        [groupItem setMinSize: groupSize];
3207        [groupItem setMaxSize: groupSize];
3208       
3209        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3210        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3211        [groupItem setTarget: self];
3212        [groupItem setAction: @selector(allToolbarClicked:)];
3213       
3214        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3215       
3216        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3217        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
3218        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3219                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3220       
3221        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3222        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
3223        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3224                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3225       
3226        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3227                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3228       
3229        [segmentedControl release];
3230        return [groupItem autorelease];
3231    }
3232    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3233    {
3234        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3235       
3236        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3237        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3238        [groupItem setView: segmentedControl];
3239        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3240       
3241        [segmentedControl setSegmentCount: 2];
3242        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3243       
3244        NSSize groupSize = NSMakeSize(72.0, 25.0);
3245        [groupItem setMinSize: groupSize];
3246        [groupItem setMaxSize: groupSize];
3247       
3248        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3249        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3250        [groupItem setTarget: self];
3251        [groupItem setAction: @selector(selectedToolbarClicked:)];
3252       
3253        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3254       
3255        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3256        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
3257        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3258                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3259       
3260        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3261        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
3262        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3263                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3264       
3265        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3266                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3267       
3268        [segmentedControl release];
3269        return [groupItem autorelease];
3270    }
3271    else if ([ident isEqualToString: TOOLBAR_FILTER])
3272    {
3273        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3274       
3275        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3276        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3277        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3278        [item setImage: [NSImage imageNamed: @"Filter.png"]];
3279        [item setTarget: self];
3280        [item setAction: @selector(toggleFilterBar:)];
3281       
3282        return item;
3283    }
3284    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3285    {
3286        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3287       
3288        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3289        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3290        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3291        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3292        [item setTarget: self];
3293        [item setAction: @selector(toggleQuickLook:)];
3294       
3295        return item;
3296    }
3297    else
3298        return nil;
3299}
3300
3301- (void) allToolbarClicked: (id) sender
3302{
3303    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3304                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3305    switch (tagValue)
3306    {
3307        case TOOLBAR_PAUSE_TAG:
3308            [self stopAllTorrents: sender];
3309            break;
3310        case TOOLBAR_RESUME_TAG:
3311            [self resumeAllTorrents: sender];
3312            break;
3313    }
3314}
3315
3316- (void) selectedToolbarClicked: (id) sender
3317{
3318    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3319                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3320    switch (tagValue)
3321    {
3322        case TOOLBAR_PAUSE_TAG:
3323            [self stopSelectedTorrents: sender];
3324            break;
3325        case TOOLBAR_RESUME_TAG:
3326            [self resumeSelectedTorrents: sender];
3327            break;
3328    }
3329}
3330
3331- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3332{
3333    NSMutableArray * idents = [NSMutableArray arrayWithObjects:
3334                                TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB,
3335                                TOOLBAR_REMOVE, TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3336                                TOOLBAR_FILTER, TOOLBAR_INFO,
3337                                NSToolbarSeparatorItemIdentifier,
3338                                NSToolbarSpaceItemIdentifier,
3339                                NSToolbarFlexibleSpaceItemIdentifier,
3340                                NSToolbarCustomizeToolbarItemIdentifier, nil];
3341   
3342    //allow quicklook on leopard
3343    if ([NSApp isOnLeopardOrBetter])
3344        [idents insertObject: TOOLBAR_QUICKLOOK atIndex: 6];
3345   
3346    return idents;
3347}
3348
3349- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3350{
3351    return [NSArray arrayWithObjects:
3352            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE,
3353            NSToolbarSeparatorItemIdentifier,
3354            TOOLBAR_PAUSE_RESUME_ALL,
3355            NSToolbarFlexibleSpaceItemIdentifier,
3356            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3357}
3358
3359- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3360{
3361    NSString * ident = [toolbarItem itemIdentifier];
3362   
3363    //enable remove item
3364    if ([ident isEqualToString: TOOLBAR_REMOVE])
3365        return [fTableView numberOfSelectedRows] > 0;
3366
3367    //enable pause all item
3368    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3369    {
3370        Torrent * torrent;
3371        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3372        while ((torrent = [enumerator nextObject]))
3373            if ([torrent isActive] || [torrent waitingToStart])
3374                return YES;
3375        return NO;
3376    }
3377
3378    //enable resume all item
3379    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3380    {
3381        Torrent * torrent;
3382        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3383        while ((torrent = [enumerator nextObject]))
3384            if (![torrent isActive] && ![torrent waitingToStart])
3385                return YES;
3386        return NO;
3387    }
3388
3389    //enable pause item
3390    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3391    {
3392        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3393        Torrent * torrent;
3394        while ((torrent = [enumerator nextObject]))
3395            if ([torrent isActive] || [torrent waitingToStart])
3396                return YES;
3397        return NO;
3398    }
3399   
3400    //enable resume item
3401    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3402    {
3403        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3404        Torrent * torrent;
3405        while ((torrent = [enumerator nextObject]))
3406            if (![torrent isActive] && ![torrent waitingToStart])
3407                return YES;
3408        return NO;
3409    }
3410   
3411    //set info image
3412    if ([ident isEqualToString: TOOLBAR_INFO])
3413    {
3414        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue.png"]
3415                                                                    : [NSImage imageNamed: @"Info.png"]];
3416        return YES;
3417    }
3418   
3419    //set filter image
3420    if ([ident isEqualToString: TOOLBAR_FILTER])
3421    {
3422        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue.png"] : [NSImage imageNamed: @"Filter.png"]];
3423        return YES;
3424    }
3425   
3426    //enable quicklook item
3427    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3428        return [[QuickLookController quickLook] canQuickLook];
3429
3430    return YES;
3431}
3432
3433- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3434{
3435    SEL action = [menuItem action];
3436   
3437    if (action == @selector(toggleSpeedLimit:))
3438    {
3439        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3440        return YES;
3441    }
3442   
3443    //only enable some items if it is in a context menu or the window is useable
3444    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3445
3446    //enable open items
3447    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3448        return [fWindow attachedSheet] == nil;
3449   
3450    //enable sort options
3451    if (action == @selector(setSort:))
3452    {
3453        NSString * sortType;
3454        switch ([menuItem tag])
3455        {
3456            case SORT_ORDER_TAG:
3457                sortType = SORT_ORDER;
3458                break;
3459            case SORT_DATE_TAG:
3460                sortType = SORT_DATE;
3461                break;
3462            case SORT_NAME_TAG:
3463                sortType = SORT_NAME;
3464                break;
3465            case SORT_PROGRESS_TAG:
3466                sortType = SORT_PROGRESS;
3467                break;
3468            case SORT_STATE_TAG:
3469                sortType = SORT_STATE;
3470                break;
3471            case SORT_TRACKER_TAG:
3472                sortType = SORT_TRACKER;
3473                break;
3474            case SORT_ACTIVITY_TAG:
3475                sortType = SORT_ACTIVITY;
3476        }
3477       
3478        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3479        return [fWindow isVisible];
3480    }
3481   
3482    //enable sort options
3483    if (action == @selector(setStatusLabel:))
3484    {
3485        NSString * statusLabel;
3486        switch ([menuItem tag])
3487        {
3488            case STATUS_RATIO_TOTAL_TAG:
3489                statusLabel = STATUS_RATIO_TOTAL;
3490                break;
3491            case STATUS_RATIO_SESSION_TAG:
3492                statusLabel = STATUS_RATIO_SESSION;
3493                break;
3494            case STATUS_TRANSFER_TOTAL_TAG:
3495                statusLabel = STATUS_TRANSFER_TOTAL;
3496                break;
3497            case STATUS_TRANSFER_SESSION_TAG:
3498                statusLabel = STATUS_TRANSFER_SESSION;
3499        }
3500       
3501        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3502        return YES;
3503    }
3504   
3505    if (action == @selector(setGroup:))
3506    {
3507        BOOL checked = NO;
3508       
3509        int index = [menuItem tag];
3510        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3511        Torrent * torrent;
3512        while ((torrent = [enumerator nextObject]))
3513            if (index == [torrent groupValue])
3514            {
3515                checked = YES;
3516                break;
3517            }
3518       
3519        [menuItem setState: checked ? NSOnState : NSOffState];
3520        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3521    }
3522   
3523    if (action == @selector(setGroupFilter:))
3524    {
3525        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3526        return YES;
3527    }
3528   
3529    if (action == @selector(toggleSmallView:))
3530    {
3531        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3532        return [fWindow isVisible];
3533    }
3534   
3535    if (action == @selector(togglePiecesBar:))
3536    {
3537        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3538        return [fWindow isVisible];
3539    }
3540   
3541    if (action == @selector(toggleStatusString:))
3542    {
3543        if ([fDefaults boolForKey: @"SmallView"])
3544        {
3545            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3546            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3547        }
3548        else
3549        {
3550            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3551            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3552        }
3553       
3554        return [fWindow isVisible];
3555    }
3556   
3557    if (action == @selector(toggleAvailabilityBar:))
3558    {
3559        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3560        return [fWindow isVisible];
3561    }
3562   
3563    if (action == @selector(setLimitGlobalEnabled:))
3564    {
3565        BOOL upload = [menuItem menu] == fUploadMenu;
3566        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3567        if (limit)
3568            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3569                                    "Action menu -> upload/download limit"),
3570                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3571       
3572        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3573        return YES;
3574    }
3575   
3576    if (action == @selector(setRatioGlobalEnabled:))
3577    {
3578        BOOL check = menuItem == fCheckRatioItem;
3579        if (check)
3580            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3581                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3582       
3583        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3584        return YES;
3585    }
3586
3587    //enable show info
3588    if (action == @selector(showInfo:))
3589    {
3590        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3591                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3592        [menuItem setTitle: title];
3593
3594        return YES;
3595    }
3596   
3597    //enable prev/next inspector tab
3598    if (action == @selector(setInfoTab:))
3599        return [[fInfoController window] isVisible];
3600   
3601    //enable toggle status bar
3602    if (action == @selector(toggleStatusBar:))
3603    {
3604        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3605                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3606        [menuItem setTitle: title];
3607
3608        return [fWindow isVisible];
3609    }
3610   
3611    //enable toggle filter bar
3612    if (action == @selector(toggleFilterBar:))
3613    {
3614        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3615                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3616        [menuItem setTitle: title];
3617
3618        return [fWindow isVisible];
3619    }
3620   
3621    //enable prev/next filter button
3622    if (action == @selector(switchFilter:))
3623        return [fWindow isVisible] && ![fFilterBar isHidden];
3624   
3625    //enable quicklook item
3626    if (action == @selector(toggleQuickLook:))
3627        return [[QuickLookController quickLook] canQuickLook];
3628   
3629    //enable reveal in finder
3630    if (action == @selector(revealFile:))
3631        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3632
3633    //enable remove items
3634    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3635        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3636    {
3637        BOOL warning = NO,
3638            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3639            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3640       
3641        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3642        Torrent * torrent;
3643        while ((torrent = [enumerator nextObject]))
3644        {
3645            if (!warning && [torrent isActive])
3646            {
3647                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3648                if (warning && canDelete)
3649                    break;
3650            }
3651            if (!canDelete && [torrent publicTorrent])
3652            {
3653                canDelete = YES;
3654                if (warning)
3655                    break;
3656            }
3657        }
3658   
3659        //append or remove ellipsis when needed
3660        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3661        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3662        {
3663            if (![title hasSuffix: ellipsis])
3664                [menuItem setTitle: [title stringByAppendingEllipsis]];
3665        }
3666        else
3667        {
3668            if ([title hasSuffix: ellipsis])
3669                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3670        }
3671       
3672        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3673    }
3674
3675    //enable pause all item
3676    if (action == @selector(stopAllTorrents:))
3677    {
3678        Torrent * torrent;
3679        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3680        while ((torrent = [enumerator nextObject]))
3681            if ([torrent isActive] || [torrent waitingToStart])
3682                return YES;
3683        return NO;
3684    }
3685   
3686    //enable resume all item
3687    if (action == @selector(resumeAllTorrents:))
3688    {
3689        Torrent * torrent;
3690        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3691        while ((torrent = [enumerator nextObject]))
3692            if (![torrent isActive] && ![torrent waitingToStart])
3693                return YES;
3694        return NO;
3695    }
3696   
3697    //enable resume all waiting item
3698    if (action == @selector(resumeWaitingTorrents:))
3699    {
3700        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3701            return NO;
3702   
3703        Torrent * torrent;
3704        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3705        while ((torrent = [enumerator nextObject]))
3706            if (![torrent isActive] && [torrent waitingToStart])
3707                return YES;
3708        return NO;
3709    }
3710   
3711    //enable resume selected waiting item
3712    if (action == @selector(resumeSelectedTorrentsNoWait:))
3713    {
3714        if (!canUseTable)
3715            return NO;
3716       
3717        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3718        Torrent * torrent;
3719        while ((torrent = [enumerator nextObject]))
3720            if (![torrent isActive])
3721                return YES;
3722        return NO;
3723    }
3724
3725    //enable pause item
3726    if (action == @selector(stopSelectedTorrents:))
3727    {
3728        if (!canUseTable)
3729            return NO;
3730   
3731        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3732        Torrent * torrent;
3733        while ((torrent = [enumerator nextObject]))
3734            if ([torrent isActive] || [torrent waitingToStart])
3735                return YES;
3736        return NO;
3737    }
3738   
3739    //enable resume item
3740    if (action == @selector(resumeSelectedTorrents:))
3741    {
3742        if (!canUseTable)
3743            return NO;
3744   
3745        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3746        Torrent * torrent;
3747        while ((torrent = [enumerator nextObject]))
3748            if (![torrent isActive] && ![torrent waitingToStart])
3749                return YES;
3750        return NO;
3751    }
3752   
3753    //enable manual announce item
3754    if (action == @selector(announceSelectedTorrents:))
3755    {
3756        if (!canUseTable)
3757            return NO;
3758       
3759        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3760        Torrent * torrent;
3761        while ((torrent = [enumerator nextObject]))
3762            if ([torrent canManualAnnounce])
3763                return YES;
3764        return NO;
3765    }
3766   
3767    //enable reset cache item
3768    if (action == @selector(verifySelectedTorrents:))
3769        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3770   
3771    //enable move torrent file item
3772    if (action == @selector(moveDataFilesSelected:))
3773        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3774   
3775    //enable copy torrent file item
3776    if (action == @selector(copyTorrentFiles:))
3777        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3778   
3779    //enable reverse sort item
3780    if (action == @selector(setSortReverse:))
3781    {
3782        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3783        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3784    }
3785   
3786    //enable group sort item
3787    if (action == @selector(setSortByGroup:))
3788    {
3789        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3790        return YES;
3791    }
3792   
3793    //check proper filter search item
3794    if (action == @selector(setFilterSearchType:))
3795    {
3796        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3797       
3798        BOOL state;
3799        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3800            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3801        else
3802            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3803       
3804        [menuItem setState: state ? NSOnState : NSOffState];
3805        return YES;
3806    }
3807   
3808    return YES;
3809}
3810
3811- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3812{
3813    NSEnumerator * enumerator;
3814    Torrent * torrent;
3815
3816    switch (messageType)
3817    {
3818        case kIOMessageSystemWillSleep:
3819            //if there are any running transfers, wait 15 seconds for them to stop
3820            enumerator = [fTorrents objectEnumerator];
3821            while ((torrent = [enumerator nextObject]))
3822                if ([torrent isActive])
3823                {
3824                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3825                    [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3826                    sleep(15);
3827                    break;
3828                }
3829
3830            IOAllowPowerChange(fRootPort, (long) messageArgument);
3831            break;
3832
3833        case kIOMessageCanSystemSleep:
3834            if ([fDefaults boolForKey: @"SleepPrevent"])
3835            {
3836                //prevent idle sleep unless no torrents are active
3837                enumerator = [fTorrents objectEnumerator];
3838                while ((torrent = [enumerator nextObject]))
3839                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3840                    {
3841                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3842                        return;
3843                    }
3844            }
3845           
3846            IOAllowPowerChange(fRootPort, (long) messageArgument);
3847            break;
3848
3849        case kIOMessageSystemHasPoweredOn:
3850            //resume sleeping transfers after we wake up
3851            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3852            [self autoSpeedLimitChange: nil];
3853            break;
3854    }
3855}
3856
3857- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3858{
3859    int seeding = 0, downloading = 0;
3860    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3861    Torrent * torrent;
3862    while ((torrent = [enumerator nextObject]))
3863    {
3864        if ([torrent isSeeding])
3865            seeding++;
3866        else if ([torrent isActive])
3867            downloading++;
3868        else;
3869    }
3870   
3871    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3872            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3873   
3874    BOOL hasSeparator = seedingItem || downloadingItem;
3875   
3876    if (seeding > 0)
3877    {
3878        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3879        if (!seedingItem)
3880        {
3881            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3882            [seedingItem setTag: DOCK_SEEDING_TAG];
3883            [fDockMenu insertItem: seedingItem atIndex: 0];
3884        }
3885        else
3886            [seedingItem setTitle: title];
3887    }
3888    else
3889    {
3890        if (seedingItem)
3891            [fDockMenu removeItem: seedingItem];
3892    }
3893   
3894    if (downloading > 0)
3895    {
3896        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3897        if (!downloadingItem)
3898        {
3899            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3900            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3901            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3902        }
3903        else
3904            [downloadingItem setTitle: title];
3905    }
3906    else
3907    {
3908        if (downloadingItem)
3909            [fDockMenu removeItem: downloadingItem];
3910    }
3911   
3912    if (seeding > 0 || downloading > 0)
3913    {
3914        if (!hasSeparator)
3915            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3916    }
3917    else
3918    {
3919        if (hasSeparator)
3920            [fDockMenu removeItemAtIndex: 0];
3921    }
3922   
3923    return fDockMenu;
3924}
3925
3926- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3927{
3928    //if auto size is enabled, the current frame shouldn't need to change
3929    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3930   
3931    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3932    return frame;
3933}
3934
3935- (void) setWindowSizeToFit
3936{
3937    if ([fDefaults boolForKey: @"AutoSize"])
3938    {
3939        NSScrollView * scrollView = [fTableView enclosingScrollView];
3940       
3941        [scrollView setHasVerticalScroller: NO];
3942        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3943        [scrollView setHasVerticalScroller: YES];
3944    }
3945}
3946
3947- (NSRect) sizedWindowFrame
3948{
3949    int groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3950                    ? [fDisplayedTorrents count] : 0;
3951   
3952    float heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3953                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3954                        - [[fTableView enclosingScrollView] frame].size.height;
3955   
3956    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3957}
3958
3959- (void) updateForExpandCollape
3960{
3961    [self setWindowSizeToFit];
3962    [self setBottomCountText: YES];
3963}
3964
3965- (void) showMainWindow: (id) sender
3966{
3967    [fWindow makeKeyAndOrderFront: nil];
3968}
3969
3970- (void) windowDidBecomeMain: (NSNotification *) notification
3971{
3972    [fBadger clearCompleted];
3973    [self updateUI];
3974}
3975
3976- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3977{
3978    //only resize horizontally if autosize is enabled
3979    if ([fDefaults boolForKey: @"AutoSize"])
3980        proposedFrameSize.height = [fWindow frame].size.height;
3981    return proposedFrameSize;
3982}
3983
3984- (void) windowDidResize: (NSNotification *) notification
3985{
3986    if (![fStatusBar isHidden])
3987        [self resizeStatusButton];
3988   
3989    if ([fFilterBar isHidden])
3990        return;
3991   
3992    //replace all buttons
3993    [fActiveFilterButton sizeToFit];
3994    [fDownloadFilterButton sizeToFit];
3995    [fSeedFilterButton sizeToFit];
3996    [fPauseFilterButton sizeToFit];
3997   
3998    NSRect activeRect = [fActiveFilterButton frame];
3999   
4000    NSRect downloadRect = [fDownloadFilterButton frame];
4001    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
4002   
4003    NSRect seedRect = [fSeedFilterButton frame];
4004    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4005   
4006    NSRect pauseRect = [fPauseFilterButton frame];
4007    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4008   
4009    //size search filter to not overlap buttons
4010    NSRect searchFrame = [fSearchFilterField frame];
4011    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
4012    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
4013   
4014    //make sure it is not too long
4015    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
4016    {
4017        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
4018        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
4019    }
4020    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
4021    {
4022        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
4023        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
4024       
4025        //resize the buttons so they don't overlay
4026        int difference = (NSMaxX(pauseRect) + 5.0) - searchFrame.origin.x - 1; //subtract 1, since 0 will be counted
4027       
4028        //decrease downloading by 8, seeding by 1, paused by 1, active by 1, repeat
4029        int download = (difference / 11 * 8) + MIN(difference % 11 + 1, 8); //8 for every 11
4030        int seed = (difference / 11) + (difference % 11 >= 8 ? 1 : 0);
4031        int paused = (difference / 11) + (difference % 11 >= 9 ? 1 : 0);
4032        int active = (difference / 11) + (difference % 11 >= 10 ? 1 : 0);
4033       
4034        activeRect.size.width -= active;
4035       
4036        downloadRect.origin.x -= active;
4037        downloadRect.size.width -= download;
4038       
4039        seedRect.origin.x -= active + download;
4040        seedRect.size.width -= seed;
4041       
4042        pauseRect.origin.x -= active + download + seed;
4043        pauseRect.size.width -= paused;
4044    }
4045    else;
4046   
4047    [fActiveFilterButton setFrame: activeRect];
4048    [fDownloadFilterButton setFrame: downloadRect];
4049    [fSeedFilterButton setFrame: seedRect];
4050    [fPauseFilterButton setFrame: pauseRect];
4051   
4052    [fSearchFilterField setFrame: searchFrame];
4053}
4054
4055- (void) applicationWillUnhide: (NSNotification *) notification
4056{
4057    [self updateUI];
4058}
4059
4060- (NSArray *) quickLookURLs
4061{
4062    NSArray * selectedTorrents = [fTableView selectedTorrents];
4063    NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
4064    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4065    Torrent * torrent;
4066   
4067    while ((torrent = [enumerator nextObject]))
4068    {
4069        if ([torrent isFolder] || [torrent isComplete])
4070            [urlArray addObject: [NSURL fileURLWithPath: [torrent dataLocation]]];
4071    }
4072   
4073    return urlArray;
4074}
4075
4076- (BOOL) canQuickLook
4077{
4078    NSArray * selectedTorrents = [fTableView selectedTorrents];
4079    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4080    Torrent * torrent;
4081   
4082    while ((torrent = [enumerator nextObject]))
4083    {
4084        if ([torrent isFolder] || [torrent isComplete])
4085            return YES;
4086    }
4087   
4088    return NO;
4089}
4090
4091- (NSRect) quickLookFrameWithURL: (NSURL *) url
4092{
4093    if ([fWindow isVisible])
4094    {
4095        NSString * fullPath = [url path];
4096        NSRange visibleRows = [fTableView rowsInRect: [fTableView bounds]];
4097       
4098        int row;
4099        for (row = 0; row < NSMaxRange(visibleRows); row++)
4100        {
4101            id item = [fTableView itemAtRow: row];
4102            if ([item isKindOfClass: [Torrent class]] && [[(Torrent *)item dataLocation] isEqualToString: fullPath])
4103            {
4104                NSRect frame = [fTableView iconRectForRow: row];
4105                frame.origin = [fTableView convertPoint: frame.origin toView: nil];
4106                frame.origin = [fWindow convertBaseToScreen: frame.origin];
4107                frame.origin.y -= frame.size.height;
4108                return frame;
4109            }
4110        }
4111    }
4112   
4113    return NSZeroRect;
4114}
4115
4116- (void) toggleQuickLook: (id) sender
4117{
4118    [[QuickLookController quickLook] toggleQuickLook];
4119}
4120
4121- (void) linkHomepage: (id) sender
4122{
4123    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4124}
4125
4126- (void) linkForums: (id) sender
4127{
4128    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4129}
4130
4131- (void) linkDonate: (id) sender
4132{
4133    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4134}
4135
4136- (void) prepareForUpdate: (NSNotification *) notification
4137{
4138    fUpdateInProgress = YES;
4139}
4140
4141- (NSDictionary *) registrationDictionaryForGrowl
4142{
4143    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4144                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4145    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4146                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4147}
4148
4149- (void) growlNotificationWasClicked: (id) clickContext
4150{
4151    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4152        return;
4153   
4154    NSString * type = [clickContext objectForKey: @"Type"], * location;
4155    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4156            && (location = [clickContext objectForKey: @"Location"]))
4157        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4158}
4159
4160- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4161{
4162    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4163   
4164    //get the torrent
4165    Torrent * torrent = nil;
4166    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4167    {
4168        NSEnumerator * enumerator = [fTorrents objectEnumerator];
4169        while ((torrent = [enumerator nextObject]))
4170            if (torrentStruct == [torrent torrentStruct])
4171                break;
4172       
4173        if (!torrent)
4174        {
4175            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4176            return;
4177        }
4178       
4179        [torrent retain];
4180    }
4181   
4182    switch (type)
4183    {
4184        case TR_RPC_TORRENT_ADDED:
4185            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4186                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4187            break;
4188       
4189        case TR_RPC_TORRENT_STARTED:
4190        case TR_RPC_TORRENT_STOPPED:
4191            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4192            break;
4193       
4194        case TR_RPC_TORRENT_REMOVING:
4195            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4196            break;
4197       
4198        case TR_RPC_TORRENT_CHANGED:
4199            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4200            break;
4201       
4202        case TR_RPC_SESSION_CHANGED:
4203            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4204            break;
4205       
4206        default:
4207            NSLog(@"Unknown RPC command received!");
4208            [torrent release];
4209    }
4210   
4211    [pool release];
4212}
4213
4214- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4215{
4216    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4217    [torrentStructPtr release];
4218   
4219    NSString * location = nil;
4220    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4221        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4222   
4223    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4224   
4225    [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
4226   
4227    [torrent update];
4228    [fTorrents addObject: torrent];
4229    [torrent release];
4230   
4231    [self updateTorrentsInQueue];
4232}
4233
4234- (void) rpcRemoveTorrent: (Torrent *) torrent
4235{
4236    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO deleteTorrent: NO fromRPC: YES];
4237    [torrent release];
4238}
4239
4240- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4241{
4242    [torrent update];
4243    [torrent release];
4244   
4245    [self updateUI];
4246    [self applyFilter: nil];
4247    [self updateTorrentHistory];
4248}
4249
4250- (void) rpcChangedTorrent: (Torrent *) torrent
4251{
4252    [torrent update];
4253   
4254    if ([[fTableView selectedTorrents] containsObject: torrent])
4255    {
4256        [fInfoController updateInfoStats]; //this will reload the file table
4257        [fInfoController updateOptions];
4258    }
4259   
4260    [torrent release];
4261}
4262
4263@end
Note: See TracBrowser for help on using the repository browser.