source: trunk/macosx/Controller.m @ 6033

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

accurately test the rpc acl's ip address

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