source: trunk/macosx/Controller.m @ 6045

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

some small simplifications to the group code

  • Property svn:keywords set to Date Rev Author Id
File size: 155.9 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 6045 2008-06-05 02:46:39Z 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    if (groupIndex == GROUP_FILTER_ALL_TAG)
2269    {
2270        icon = [NSImage imageNamed: @"PinTemplate.png"];
2271        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2272    }
2273    else
2274    {
2275        icon = [[GroupsController groups] imageForIndex: groupIndex];
2276        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2277                                                : NSLocalizedString(@"None", "Groups -> Button");
2278        toolTip = [NSString stringWithFormat: @"%@: %@", NSLocalizedString(@"Group", "Groups -> Button"), groupName];
2279    }
2280   
2281    //tiger doesn't have built-in image scaling in buttons
2282    if (![NSApp isOnLeopardOrBetter])
2283    {
2284        icon = [[icon copy] autorelease];
2285        [icon setScalesWhenResized: YES];
2286        [icon setSize: NSMakeSize(12.0, 12.0)];
2287    }
2288   
2289    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2290    [fGroupsButton setToolTip: toolTip];
2291}
2292
2293- (void) updateGroupsFilters: (NSNotification *) notification
2294{
2295    [self updateGroupsFilterButton];
2296    [self applyFilter: nil];
2297}
2298
2299- (void) toggleSpeedLimit: (id) sender
2300{
2301    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2302    [fPrefsController applySpeedSettings: nil];
2303}
2304
2305- (void) autoSpeedLimitChange: (NSNotification *) notification
2306{
2307    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2308        return;
2309 
2310    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2311                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
2312        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2313                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
2314        * nowDate = [NSCalendarDate calendarDate];
2315   
2316    //check if should be on if within range
2317    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
2318        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
2319        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
2320   
2321    BOOL shouldBeOn = NO;
2322    if (onTime < offTime)
2323        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2324    else if (onTime > offTime)
2325        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2326    else;
2327   
2328    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2329        [self toggleSpeedLimit: nil];
2330}
2331
2332- (void) autoSpeedLimit
2333{
2334    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2335        return;
2336   
2337    //only toggle if within first few seconds of minutes
2338    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
2339    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
2340        return;
2341   
2342    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2343                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
2344   
2345    BOOL toggle;
2346    if ([fDefaults boolForKey: @"SpeedLimit"])
2347        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
2348    else
2349    {
2350        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2351                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
2352        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
2353                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
2354    }
2355   
2356    if (toggle)
2357    {
2358        [self toggleSpeedLimit: nil];
2359       
2360        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2361                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2362                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2363            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2364            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2365    }
2366}
2367
2368- (void) setLimitGlobalEnabled: (id) sender
2369{
2370    BOOL upload = [sender menu] == fUploadMenu;
2371    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2372   
2373    [fPrefsController applySpeedSettings: nil];
2374}
2375
2376- (void) setQuickLimitGlobal: (id) sender
2377{
2378    BOOL upload = [sender menu] == fUploadMenu;
2379    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2380    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2381   
2382    [fPrefsController updateLimitFields];
2383    [fPrefsController applySpeedSettings: nil];
2384}
2385
2386- (void) setRatioGlobalEnabled: (id) sender
2387{
2388    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2389}
2390
2391- (void) setQuickRatioGlobal: (id) sender
2392{
2393    [fDefaults setBool: YES forKey: @"RatioCheck"];
2394    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2395   
2396    [fPrefsController updateRatioStopField];
2397}
2398
2399- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2400{
2401    fSoundPlaying = NO;
2402}
2403
2404- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2405{
2406    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2407    {
2408        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2409            return;
2410       
2411        if (fAutoImportTimer)
2412        {
2413            if ([fAutoImportTimer isValid])
2414                [fAutoImportTimer invalidate];
2415            [fAutoImportTimer release];
2416            fAutoImportTimer = nil;
2417        }
2418       
2419        //check again in 10 seconds in case torrent file wasn't complete
2420        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2421            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2422       
2423        [self checkAutoImportDirectory];
2424    }
2425}
2426
2427- (void) changeAutoImport
2428{
2429    if (fAutoImportTimer)
2430    {
2431        if ([fAutoImportTimer isValid])
2432            [fAutoImportTimer invalidate];
2433        [fAutoImportTimer release];
2434        fAutoImportTimer = nil;
2435    }
2436   
2437    if (fAutoImportedNames)
2438    {
2439        [fAutoImportedNames release];
2440        fAutoImportedNames = nil;
2441    }
2442   
2443    [self checkAutoImportDirectory];
2444}
2445
2446- (void) checkAutoImportDirectory
2447{
2448    NSString * path;
2449    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2450        return;
2451   
2452    path = [path stringByExpandingTildeInPath];
2453   
2454    NSArray * importedNames;
2455    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2456        return;
2457   
2458    //only check files that have not been checked yet
2459    NSMutableArray * newNames = [importedNames mutableCopy];
2460   
2461    if (fAutoImportedNames)
2462        [newNames removeObjectsInArray: fAutoImportedNames];
2463    else
2464        fAutoImportedNames = [[NSMutableArray alloc] init];
2465    [fAutoImportedNames setArray: importedNames];
2466   
2467    NSString * file;
2468    int i;
2469    for (i = [newNames count] - 1; i >= 0; i--)
2470    {
2471        file = [newNames objectAtIndex: i];
2472        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2473            [newNames removeObjectAtIndex: i];
2474        else
2475            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2476    }
2477   
2478    NSEnumerator * enumerator = [newNames objectEnumerator];
2479    tr_ctor * ctor;
2480    while ((file = [enumerator nextObject]))
2481    {
2482        ctor = tr_ctorNew(fLib);
2483        tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2484       
2485        switch (tr_torrentParse(fLib, ctor, NULL))
2486        {
2487            case TR_OK:
2488                [self openFiles: [NSArray arrayWithObject: file] addType: ADD_AUTO forcePath: nil];
2489               
2490                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2491                    description: [file lastPathComponent] notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2492                    clickContext: nil];
2493                break;
2494           
2495            case TR_EINVALID:
2496                [fAutoImportedNames removeObject: [file lastPathComponent]];
2497        }
2498       
2499        tr_ctorFree(ctor);
2500    }
2501   
2502    [newNames release];
2503}
2504
2505- (void) beginCreateFile: (NSNotification *) notification
2506{
2507    if (![fDefaults boolForKey: @"AutoImport"])
2508        return;
2509   
2510    NSString * location = [notification object],
2511            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2512   
2513    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2514                                    isEqualToString: [path stringByExpandingTildeInPath]])
2515        [fAutoImportedNames addObject: [location lastPathComponent]];
2516}
2517
2518- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2519{
2520    if (item)
2521        return [[item objectForKey: @"Torrents"] count];
2522    else
2523        return [fDisplayedTorrents count];
2524}
2525
2526- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2527{
2528    if (item)
2529        return [[item objectForKey: @"Torrents"] objectAtIndex: index];
2530    else
2531        return [fDisplayedTorrents objectAtIndex: index];
2532}
2533
2534- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2535{
2536    return ![item isKindOfClass: [Torrent class]];
2537}
2538
2539- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2540{
2541    if ([item isKindOfClass: [Torrent class]])
2542        return [item hashString];
2543    else
2544    {
2545        NSString * ident = [tableColumn identifier];
2546        if ([ident isEqualToString: @"Group"])
2547        {
2548            int group = [[item objectForKey: @"Group"] intValue];
2549            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2550                                : NSLocalizedString(@"No Group", "Group table row");
2551        }
2552        else if ([ident isEqualToString: @"Color"])
2553        {
2554            int group = [[item objectForKey: @"Group"] intValue];
2555            return [[GroupsController groups] imageForIndex: group];
2556        }
2557        else if ([ident isEqualToString: @"DL Image"])
2558            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2559        else if ([ident isEqualToString: @"UL Image"])
2560            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2561                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2562        else
2563        {
2564            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2565            {
2566                uint64_t uploaded = 0, downloaded = 0;
2567                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2568                Torrent * torrent;
2569                while ((torrent = [enumerator nextObject]))
2570                {
2571                    uploaded += [torrent uploadedTotal];
2572                    downloaded += [torrent downloadedTotal];
2573                }
2574               
2575                return [NSString stringForRatio: tr_getRatio(uploaded, downloaded)];
2576            }
2577            else
2578            {
2579                BOOL upload = [ident isEqualToString: @"UL"];
2580               
2581                float rate = 0.0;
2582                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2583                Torrent * torrent;
2584                while ((torrent = [enumerator nextObject]))
2585                    rate += upload ? [torrent uploadRate] : [torrent downloadRate];
2586               
2587                return [NSString stringForSpeed: rate];
2588            }
2589        }
2590    }
2591}
2592
2593- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2594{
2595    //only allow reordering of rows if sorting by order
2596    if (([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
2597        || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2598    {
2599        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2600        NSEnumerator * enumerator = [items objectEnumerator];
2601        id torrent;
2602        while ((torrent = [enumerator nextObject]))
2603        {
2604            if (![torrent isKindOfClass: [Torrent class]])
2605                return NO;
2606           
2607            [indexSet addIndex: [fTableView rowForItem: torrent]];
2608        }
2609       
2610        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2611        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2612        return YES;
2613    }
2614    return NO;
2615}
2616
2617- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2618    proposedChildIndex: (NSInteger) index
2619{
2620    NSPasteboard * pasteboard = [info draggingPasteboard];
2621    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2622    {
2623        if ([fDefaults boolForKey: @"SortByGroup"])
2624        {
2625            if (!item)
2626                return NSDragOperationNone;
2627           
2628            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2629            {
2630                if ([item isKindOfClass: [Torrent class]])
2631                {
2632                    NSDictionary * group = [fTableView parentForItem: item];
2633                    index = [[group objectForKey: @"Torrents"] indexOfObject: item] + 1;
2634                    item = group;
2635                }
2636            }
2637            else
2638            {
2639                if ([item isKindOfClass: [Torrent class]])
2640                    item = [fTableView parentForItem: item];
2641                index = NSOutlineViewDropOnItemIndex;
2642            }
2643        }
2644        else
2645        {
2646            if (item)
2647            {
2648                index = [fTableView rowForItem: item] + 1;
2649                item = nil;
2650            }
2651        }
2652       
2653        [fTableView setDropItem: item dropChildIndex: index];
2654        return NSDragOperationGeneric;
2655    }
2656   
2657    return NSDragOperationNone;
2658}
2659
2660- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2661    childIndex: (NSInteger) newRow
2662{
2663    NSPasteboard * pasteboard = [info draggingPasteboard];
2664    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2665    {
2666        //remember selected rows
2667        NSArray * selectedValues = [fTableView selectedValues];
2668   
2669        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2670       
2671        //get the torrents to move
2672        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2673        int i;
2674        for (i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2675            [movingTorrents addObject: [fTableView itemAtRow: i]];
2676       
2677        //reset groups
2678        if (item)
2679        {
2680            //change groups
2681            int groupValue = [[item objectForKey: @"Group"] intValue];
2682            NSEnumerator * enumerator = [movingTorrents objectEnumerator];
2683            Torrent * torrent;
2684            while ((torrent = [enumerator nextObject]))
2685            {
2686                //have to reset objects here to avoid weird crash
2687                [[[fTableView parentForItem: torrent] objectForKey: @"Torrent"] removeObject: torrent];
2688                [[item objectForKey: @"Torrent"] addObject: torrent];
2689               
2690                [torrent setGroupValue: groupValue];
2691            }
2692            //part 2 of avoiding weird crash
2693            [fTableView reloadItem: nil reloadChildren: YES];
2694        }
2695       
2696        //reorder queue order
2697        if (newRow != NSOutlineViewDropOnItemIndex)
2698        {
2699            //find torrent to place under
2700            NSArray * groupTorrents = item ? [item objectForKey: @"Torrents"] : fDisplayedTorrents;
2701            Torrent * topTorrent = nil;
2702            for (i = newRow-1; i >= 0; i--)
2703            {
2704                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2705                if (![movingTorrents containsObject: tempTorrent])
2706                {
2707                    topTorrent = tempTorrent;
2708                    break;
2709                }
2710            }
2711           
2712            //remove objects to reinsert
2713            [fTorrents removeObjectsInArray: movingTorrents];
2714           
2715            //get all torrents to reorder
2716            NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: YES] autorelease];
2717            [fTorrents sortUsingDescriptors: [NSArray arrayWithObject: orderDescriptor]];
2718           
2719            //insert objects at new location
2720            int insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2721            for (i = 0; i < [movingTorrents count]; i++)
2722                [fTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2723           
2724            //redo order values
2725            for (i = 0; i < [fTorrents count]; i++)
2726                [[fTorrents objectAtIndex: i] setOrderValue: i];
2727        }
2728       
2729        [self applyFilter: nil];
2730       
2731        //set selected rows
2732        [fTableView selectValues: selectedValues];
2733    }
2734   
2735    return YES;
2736}
2737
2738- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2739{
2740    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
2741    [[QuickLookController quickLook] updateQuickLook];
2742}
2743
2744- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2745{
2746    NSPasteboard * pasteboard = [info draggingPasteboard];
2747    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2748    {
2749        //check if any torrent files can be added
2750        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2751        NSEnumerator * enumerator = [files objectEnumerator];
2752        NSString * file;
2753        BOOL torrent = NO;
2754        tr_ctor * ctor;
2755        while ((file = [enumerator nextObject]))
2756        {
2757            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2758            {
2759                ctor = tr_ctorNew(fLib);
2760                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2761                switch (tr_torrentParse(fLib, ctor, NULL))
2762                {
2763                    case TR_OK:
2764                        if (!fOverlayWindow)
2765                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2766                        [fOverlayWindow setTorrents: files];
2767                       
2768                        return NSDragOperationCopy;
2769                   
2770                    case TR_EDUPLICATE:
2771                        torrent = YES;
2772                }
2773                tr_ctorFree(ctor);
2774            }
2775        }
2776       
2777        //create a torrent file if a single file
2778        if (!torrent && [files count] == 1)
2779        {
2780            if (!fOverlayWindow)
2781                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2782            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2783           
2784            return NSDragOperationCopy;
2785        }
2786    }
2787    else if ([[pasteboard types] containsObject: NSURLPboardType])
2788    {
2789        if (!fOverlayWindow)
2790            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2791        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2792       
2793        return NSDragOperationCopy;
2794    }
2795    else;
2796   
2797    return NSDragOperationNone;
2798}
2799
2800- (void) draggingExited: (id <NSDraggingInfo>) info
2801{
2802    if (fOverlayWindow)
2803        [fOverlayWindow fadeOut];
2804}
2805
2806- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2807{
2808    if (fOverlayWindow)
2809        [fOverlayWindow fadeOut];
2810   
2811    NSPasteboard * pasteboard = [info draggingPasteboard];
2812    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2813    {
2814        BOOL torrent = NO, accept = YES;
2815       
2816        //create an array of files that can be opened
2817        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2818        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2819        NSEnumerator * enumerator = [files objectEnumerator];
2820        NSString * file;
2821        tr_ctor * ctor;
2822        while ((file = [enumerator nextObject]))
2823        {
2824            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2825            {
2826                ctor = tr_ctorNew(fLib);
2827                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2828                switch (tr_torrentParse(fLib, ctor, NULL))
2829                {
2830                    case TR_OK:
2831                        [filesToOpen addObject: file];
2832                        torrent = YES;
2833                        break;
2834                       
2835                    case TR_EDUPLICATE:
2836                        torrent = YES;
2837                }
2838                tr_ctorFree(ctor);
2839            }
2840        }
2841       
2842        if ([filesToOpen count] > 0)
2843            [self application: NSApp openFiles: filesToOpen];
2844        else
2845        {
2846            if (!torrent && [files count] == 1)
2847                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2848            else
2849                accept = NO;
2850        }
2851        [filesToOpen release];
2852       
2853        return accept;
2854    }
2855    else if ([[pasteboard types] containsObject: NSURLPboardType])
2856    {
2857        NSURL * url;
2858        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2859        {
2860            [self openURL: url];
2861            return YES;
2862        }
2863    }
2864    else;
2865   
2866    return NO;
2867}
2868
2869- (void) toggleSmallView: (id) sender
2870{
2871    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2872    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2873   
2874    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2875   
2876    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2877   
2878    //window min height
2879    NSSize contentMinSize = [fWindow contentMinSize],
2880            contentSize = [[fWindow contentView] frame].size;
2881    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2882                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2883    [fWindow setContentMinSize: contentMinSize];
2884   
2885    //resize for larger min height if not set to auto size
2886    if (![fDefaults boolForKey: @"AutoSize"])
2887    {
2888        if (!makeSmall && contentSize.height < contentMinSize.height)
2889        {
2890            NSRect frame = [fWindow frame];
2891            float heightChange = contentMinSize.height - contentSize.height;
2892            frame.size.height += heightChange;
2893            frame.origin.y -= heightChange;
2894           
2895            [fWindow setFrame: frame display: YES];
2896        }
2897    }
2898    else
2899        [self setWindowSizeToFit];
2900}
2901
2902- (void) togglePiecesBar: (id) sender
2903{
2904    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2905    [fTableView togglePiecesBar];
2906}
2907
2908- (void) toggleAvailabilityBar: (id) sender
2909{
2910    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2911    [fTableView display];
2912}
2913
2914- (void) toggleStatusString: (id) sender
2915{
2916    if ([fDefaults boolForKey: @"SmallView"])
2917        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2918    else
2919        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2920   
2921    [fTableView reloadData];
2922}
2923
2924- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2925{
2926    NSScrollView * scrollView = [fTableView enclosingScrollView];
2927   
2928    //convert pixels to points
2929    NSRect windowFrame = [fWindow frame];
2930    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2931    windowSize.height += height;
2932   
2933    if (check)
2934    {
2935        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2936       
2937        if (windowSize.height < minSize.height)
2938            windowSize.height = minSize.height;
2939        else
2940        {
2941            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2942            if ([fStatusBar isHidden])
2943                maxSize.height -= [fStatusBar frame].size.height;
2944            if ([fFilterBar isHidden])
2945                maxSize.height -= [fFilterBar frame].size.height;
2946            if (windowSize.height > maxSize.height)
2947                windowSize.height = maxSize.height;
2948        }
2949    }
2950
2951    //convert points to pixels
2952    windowSize = [scrollView convertSize: windowSize toView: nil];
2953
2954    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2955    windowFrame.size.height = windowSize.height;
2956    return windowFrame;
2957}
2958
2959- (void) toggleStatusBar: (id) sender
2960{
2961    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2962    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2963}
2964
2965//doesn't save shown state
2966- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2967{
2968    if (show != [fStatusBar isHidden])
2969        return;
2970
2971    if (show)
2972        [fStatusBar setHidden: NO];
2973
2974    NSRect frame;
2975    float heightChange = [fStatusBar frame].size.height;
2976    if (!show)
2977        heightChange *= -1;
2978   
2979    //allow bar to show even if not enough room
2980    if (show && ![fDefaults boolForKey: @"AutoSize"])
2981    {
2982        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2983        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2984        if (change < 0.0)
2985        {
2986            frame = [fWindow frame];
2987            frame.size.height += change;
2988            frame.origin.y -= change;
2989            [fWindow setFrame: frame display: NO animate: NO];
2990        }
2991    }
2992
2993    [self updateUI];
2994   
2995    NSScrollView * scrollView = [fTableView enclosingScrollView];
2996   
2997    //set views to not autoresize
2998    unsigned int statsMask = [fStatusBar autoresizingMask];
2999    unsigned int filterMask = [fFilterBar autoresizingMask];
3000    unsigned int scrollMask = [scrollView autoresizingMask];
3001    [fStatusBar setAutoresizingMask: NSViewNotSizable];
3002    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3003    [scrollView setAutoresizingMask: NSViewNotSizable];
3004   
3005    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3006    [fWindow setFrame: frame display: YES animate: animate];
3007   
3008    //re-enable autoresize
3009    [fStatusBar setAutoresizingMask: statsMask];
3010    [fFilterBar setAutoresizingMask: filterMask];
3011    [scrollView setAutoresizingMask: scrollMask];
3012   
3013    //change min size
3014    NSSize minSize = [fWindow contentMinSize];
3015    minSize.height += heightChange;
3016    [fWindow setContentMinSize: minSize];
3017   
3018    if (!show)
3019        [fStatusBar setHidden: YES];
3020}
3021
3022- (void) toggleFilterBar: (id) sender
3023{
3024    //disable filtering when hiding
3025    if (![fFilterBar isHidden])
3026    {
3027        [fSearchFilterField setStringValue: @""];
3028        [self setFilter: fNoFilterButton];
3029        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3030    }
3031
3032    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3033    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3034}
3035
3036//doesn't save shown state
3037- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3038{
3039    if (show != [fFilterBar isHidden])
3040        return;
3041
3042    if (show)
3043        [fFilterBar setHidden: NO];
3044
3045    NSRect frame;
3046    float heightChange = [fFilterBar frame].size.height;
3047    if (!show)
3048        heightChange *= -1;
3049   
3050    //allow bar to show even if not enough room
3051    if (show && ![fDefaults boolForKey: @"AutoSize"])
3052    {
3053        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3054        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3055        if (change < 0.0)
3056        {
3057            frame = [fWindow frame];
3058            frame.size.height += change;
3059            frame.origin.y -= change;
3060            [fWindow setFrame: frame display: NO animate: NO];
3061        }
3062    }
3063   
3064    NSScrollView * scrollView = [fTableView enclosingScrollView];
3065
3066    //set views to not autoresize
3067    unsigned int filterMask = [fFilterBar autoresizingMask];
3068    unsigned int scrollMask = [scrollView autoresizingMask];
3069    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3070    [scrollView setAutoresizingMask: NSViewNotSizable];
3071   
3072    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3073    [fWindow setFrame: frame display: YES animate: animate];
3074   
3075    //re-enable autoresize
3076    [fFilterBar setAutoresizingMask: filterMask];
3077    [scrollView setAutoresizingMask: scrollMask];
3078   
3079    //change min size
3080    NSSize minSize = [fWindow contentMinSize];
3081    minSize.height += heightChange;
3082    [fWindow setContentMinSize: minSize];
3083   
3084    if (!show)
3085    {
3086        [fFilterBar setHidden: YES];
3087        [fWindow makeFirstResponder: fTableView];
3088    }
3089}
3090
3091- (void) focusFilterField
3092{
3093    [fWindow makeFirstResponder: fSearchFilterField];
3094    if ([fFilterBar isHidden])
3095        [self toggleFilterBar: self];
3096}
3097
3098- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3099{
3100    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3101   
3102    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3103    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3104    [button setStringValue: @""];
3105   
3106    [item setView: button];
3107    [button release];
3108   
3109    NSSize buttonSize = NSMakeSize(36.0, 25.0);
3110    [item setMinSize: buttonSize];
3111    [item setMaxSize: buttonSize];
3112   
3113    return [item autorelease];
3114}
3115
3116- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3117{
3118    if ([ident isEqualToString: TOOLBAR_CREATE])
3119    {
3120        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3121       
3122        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3123        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3124        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3125        [item setImage: [NSImage imageNamed: @"Create.png"]];
3126        [item setTarget: self];
3127        [item setAction: @selector(createFile:)];
3128        [item setAutovalidates: NO];
3129       
3130        return item;
3131    }
3132    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3133    {
3134        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3135       
3136        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3137        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3138        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3139        [item setImage: [NSImage imageNamed: @"Open.png"]];
3140        [item setTarget: self];
3141        [item setAction: @selector(openShowSheet:)];
3142        [item setAutovalidates: NO];
3143       
3144        return item;
3145    }
3146    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3147    {
3148        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3149       
3150        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3151        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3152        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3153        [item setImage: [NSImage imageNamed: @"OpenWeb.png"]];
3154        [item setTarget: self];
3155        [item setAction: @selector(openURLShowSheet:)];
3156        [item setAutovalidates: NO];
3157       
3158        return item;
3159    }
3160    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3161    {
3162        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3163       
3164        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3165        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3166        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3167        [item setImage: [NSImage imageNamed: @"Remove.png"]];
3168        [item setTarget: self];
3169        [item setAction: @selector(removeNoDelete:)];
3170       
3171        return item;
3172    }
3173    else if ([ident isEqualToString: TOOLBAR_INFO])
3174    {
3175        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3176       
3177        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3178        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3179        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3180        [item setImage: [NSImage imageNamed: @"Info.png"]];
3181        [item setTarget: self];
3182        [item setAction: @selector(showInfo:)];
3183       
3184        return item;
3185    }
3186    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3187    {
3188        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3189       
3190        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3191        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3192        [groupItem setView: segmentedControl];
3193        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3194       
3195        [segmentedControl setSegmentCount: 2];
3196        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3197       
3198        NSSize groupSize = NSMakeSize(72.0, 25.0);
3199        [groupItem setMinSize: groupSize];
3200        [groupItem setMaxSize: groupSize];
3201       
3202        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3203        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3204        [groupItem setTarget: self];
3205        [groupItem setAction: @selector(allToolbarClicked:)];
3206       
3207        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3208       
3209        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3210        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
3211        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3212                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3213       
3214        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3215        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
3216        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3217                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3218       
3219        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3220                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3221       
3222        [segmentedControl release];
3223        return [groupItem autorelease];
3224    }
3225    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3226    {
3227        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3228       
3229        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3230        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3231        [groupItem setView: segmentedControl];
3232        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3233       
3234        [segmentedControl setSegmentCount: 2];
3235        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3236       
3237        NSSize groupSize = NSMakeSize(72.0, 25.0);
3238        [groupItem setMinSize: groupSize];
3239        [groupItem setMaxSize: groupSize];
3240       
3241        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3242        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3243        [groupItem setTarget: self];
3244        [groupItem setAction: @selector(selectedToolbarClicked:)];
3245       
3246        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3247       
3248        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3249        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
3250        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3251                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3252       
3253        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3254        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
3255        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3256                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3257       
3258        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3259                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3260       
3261        [segmentedControl release];
3262        return [groupItem autorelease];
3263    }
3264    else if ([ident isEqualToString: TOOLBAR_FILTER])
3265    {
3266        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3267       
3268        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3269        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3270        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3271        [item setImage: [NSImage imageNamed: @"Filter.png"]];
3272        [item setTarget: self];
3273        [item setAction: @selector(toggleFilterBar:)];
3274       
3275        return item;
3276    }
3277    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3278    {
3279        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3280       
3281        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3282        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3283        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3284        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3285        [item setTarget: self];
3286        [item setAction: @selector(toggleQuickLook:)];
3287       
3288        return item;
3289    }
3290    else
3291        return nil;
3292}
3293
3294- (void) allToolbarClicked: (id) sender
3295{
3296    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3297                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3298    switch (tagValue)
3299    {
3300        case TOOLBAR_PAUSE_TAG:
3301            [self stopAllTorrents: sender];
3302            break;
3303        case TOOLBAR_RESUME_TAG:
3304            [self resumeAllTorrents: sender];
3305            break;
3306    }
3307}
3308
3309- (void) selectedToolbarClicked: (id) sender
3310{
3311    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3312                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3313    switch (tagValue)
3314    {
3315        case TOOLBAR_PAUSE_TAG:
3316            [self stopSelectedTorrents: sender];
3317            break;
3318        case TOOLBAR_RESUME_TAG:
3319            [self resumeSelectedTorrents: sender];
3320            break;
3321    }
3322}
3323
3324- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3325{
3326    NSMutableArray * idents = [NSMutableArray arrayWithObjects:
3327                                TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB,
3328                                TOOLBAR_REMOVE, TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3329                                TOOLBAR_FILTER, TOOLBAR_INFO,
3330                                NSToolbarSeparatorItemIdentifier,
3331                                NSToolbarSpaceItemIdentifier,
3332                                NSToolbarFlexibleSpaceItemIdentifier,
3333                                NSToolbarCustomizeToolbarItemIdentifier, nil];
3334   
3335    //allow quicklook on leopard
3336    if ([NSApp isOnLeopardOrBetter])
3337        [idents insertObject: TOOLBAR_QUICKLOOK atIndex: 6];
3338   
3339    return idents;
3340}
3341
3342- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3343{
3344    return [NSArray arrayWithObjects:
3345            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE,
3346            NSToolbarSeparatorItemIdentifier,
3347            TOOLBAR_PAUSE_RESUME_ALL,
3348            NSToolbarFlexibleSpaceItemIdentifier,
3349            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3350}
3351
3352- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3353{
3354    NSString * ident = [toolbarItem itemIdentifier];
3355   
3356    //enable remove item
3357    if ([ident isEqualToString: TOOLBAR_REMOVE])
3358        return [fTableView numberOfSelectedRows] > 0;
3359
3360    //enable pause all item
3361    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3362    {
3363        Torrent * torrent;
3364        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3365        while ((torrent = [enumerator nextObject]))
3366            if ([torrent isActive] || [torrent waitingToStart])
3367                return YES;
3368        return NO;
3369    }
3370
3371    //enable resume all item
3372    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3373    {
3374        Torrent * torrent;
3375        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3376        while ((torrent = [enumerator nextObject]))
3377            if (![torrent isActive] && ![torrent waitingToStart])
3378                return YES;
3379        return NO;
3380    }
3381
3382    //enable pause item
3383    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3384    {
3385        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3386        Torrent * torrent;
3387        while ((torrent = [enumerator nextObject]))
3388            if ([torrent isActive] || [torrent waitingToStart])
3389                return YES;
3390        return NO;
3391    }
3392   
3393    //enable resume item
3394    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3395    {
3396        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3397        Torrent * torrent;
3398        while ((torrent = [enumerator nextObject]))
3399            if (![torrent isActive] && ![torrent waitingToStart])
3400                return YES;
3401        return NO;
3402    }
3403   
3404    //set info image
3405    if ([ident isEqualToString: TOOLBAR_INFO])
3406    {
3407        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue.png"]
3408                                                                    : [NSImage imageNamed: @"Info.png"]];
3409        return YES;
3410    }
3411   
3412    //set filter image
3413    if ([ident isEqualToString: TOOLBAR_FILTER])
3414    {
3415        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue.png"] : [NSImage imageNamed: @"Filter.png"]];
3416        return YES;
3417    }
3418   
3419    //enable quicklook item
3420    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3421        return [[QuickLookController quickLook] canQuickLook];
3422
3423    return YES;
3424}
3425
3426- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3427{
3428    SEL action = [menuItem action];
3429   
3430    if (action == @selector(toggleSpeedLimit:))
3431    {
3432        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3433        return YES;
3434    }
3435   
3436    //only enable some items if it is in a context menu or the window is useable
3437    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3438
3439    //enable open items
3440    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3441        return [fWindow attachedSheet] == nil;
3442   
3443    //enable sort options
3444    if (action == @selector(setSort:))
3445    {
3446        NSString * sortType;
3447        switch ([menuItem tag])
3448        {
3449            case SORT_ORDER_TAG:
3450                sortType = SORT_ORDER;
3451                break;
3452            case SORT_DATE_TAG:
3453                sortType = SORT_DATE;
3454                break;
3455            case SORT_NAME_TAG:
3456                sortType = SORT_NAME;
3457                break;
3458            case SORT_PROGRESS_TAG:
3459                sortType = SORT_PROGRESS;
3460                break;
3461            case SORT_STATE_TAG:
3462                sortType = SORT_STATE;
3463                break;
3464            case SORT_TRACKER_TAG:
3465                sortType = SORT_TRACKER;
3466                break;
3467            case SORT_ACTIVITY_TAG:
3468                sortType = SORT_ACTIVITY;
3469        }
3470       
3471        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3472        return [fWindow isVisible];
3473    }
3474   
3475    //enable sort options
3476    if (action == @selector(setStatusLabel:))
3477    {
3478        NSString * statusLabel;
3479        switch ([menuItem tag])
3480        {
3481            case STATUS_RATIO_TOTAL_TAG:
3482                statusLabel = STATUS_RATIO_TOTAL;
3483                break;
3484            case STATUS_RATIO_SESSION_TAG:
3485                statusLabel = STATUS_RATIO_SESSION;
3486                break;
3487            case STATUS_TRANSFER_TOTAL_TAG:
3488                statusLabel = STATUS_TRANSFER_TOTAL;
3489                break;
3490            case STATUS_TRANSFER_SESSION_TAG:
3491                statusLabel = STATUS_TRANSFER_SESSION;
3492        }
3493       
3494        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3495        return YES;
3496    }
3497   
3498    if (action == @selector(setGroup:))
3499    {
3500        BOOL checked = NO;
3501       
3502        int index = [menuItem tag];
3503        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3504        Torrent * torrent;
3505        while ((torrent = [enumerator nextObject]))
3506            if (index == [torrent groupValue])
3507            {
3508                checked = YES;
3509                break;
3510            }
3511       
3512        [menuItem setState: checked ? NSOnState : NSOffState];
3513        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3514    }
3515   
3516    if (action == @selector(setGroupFilter:))
3517    {
3518        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3519        return YES;
3520    }
3521   
3522    if (action == @selector(toggleSmallView:))
3523    {
3524        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3525        return [fWindow isVisible];
3526    }
3527   
3528    if (action == @selector(togglePiecesBar:))
3529    {
3530        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3531        return [fWindow isVisible];
3532    }
3533   
3534    if (action == @selector(toggleStatusString:))
3535    {
3536        if ([fDefaults boolForKey: @"SmallView"])
3537        {
3538            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3539            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3540        }
3541        else
3542        {
3543            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3544            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3545        }
3546       
3547        return [fWindow isVisible];
3548    }
3549   
3550    if (action == @selector(toggleAvailabilityBar:))
3551    {
3552        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3553        return [fWindow isVisible];
3554    }
3555   
3556    if (action == @selector(setLimitGlobalEnabled:))
3557    {
3558        BOOL upload = [menuItem menu] == fUploadMenu;
3559        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3560        if (limit)
3561            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3562                                    "Action menu -> upload/download limit"),
3563                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3564       
3565        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3566        return YES;
3567    }
3568   
3569    if (action == @selector(setRatioGlobalEnabled:))
3570    {
3571        BOOL check = menuItem == fCheckRatioItem;
3572        if (check)
3573            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3574                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3575       
3576        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3577        return YES;
3578    }
3579
3580    //enable show info
3581    if (action == @selector(showInfo:))
3582    {
3583        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3584                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3585        [menuItem setTitle: title];
3586
3587        return YES;
3588    }
3589   
3590    //enable prev/next inspector tab
3591    if (action == @selector(setInfoTab:))
3592        return [[fInfoController window] isVisible];
3593   
3594    //enable toggle status bar
3595    if (action == @selector(toggleStatusBar:))
3596    {
3597        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3598                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3599        [menuItem setTitle: title];
3600
3601        return [fWindow isVisible];
3602    }
3603   
3604    //enable toggle filter bar
3605    if (action == @selector(toggleFilterBar:))
3606    {
3607        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3608                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3609        [menuItem setTitle: title];
3610
3611        return [fWindow isVisible];
3612    }
3613   
3614    //enable prev/next filter button
3615    if (action == @selector(switchFilter:))
3616        return [fWindow isVisible] && ![fFilterBar isHidden];
3617   
3618    //enable quicklook item
3619    if (action == @selector(toggleQuickLook:))
3620        return [[QuickLookController quickLook] canQuickLook];
3621   
3622    //enable reveal in finder
3623    if (action == @selector(revealFile:))
3624        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3625
3626    //enable remove items
3627    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3628        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3629    {
3630        BOOL warning = NO,
3631            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3632            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3633       
3634        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3635        Torrent * torrent;
3636        while ((torrent = [enumerator nextObject]))
3637        {
3638            if (!warning && [torrent isActive])
3639            {
3640                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3641                if (warning && canDelete)
3642                    break;
3643            }
3644            if (!canDelete && [torrent publicTorrent])
3645            {
3646                canDelete = YES;
3647                if (warning)
3648                    break;
3649            }
3650        }
3651   
3652        //append or remove ellipsis when needed
3653        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3654        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3655        {
3656            if (![title hasSuffix: ellipsis])
3657                [menuItem setTitle: [title stringByAppendingEllipsis]];
3658        }
3659        else
3660        {
3661            if ([title hasSuffix: ellipsis])
3662                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3663        }
3664       
3665        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3666    }
3667
3668    //enable pause all item
3669    if (action == @selector(stopAllTorrents:))
3670    {
3671        Torrent * torrent;
3672        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3673        while ((torrent = [enumerator nextObject]))
3674            if ([torrent isActive] || [torrent waitingToStart])
3675                return YES;
3676        return NO;
3677    }
3678   
3679    //enable resume all item
3680    if (action == @selector(resumeAllTorrents:))
3681    {
3682        Torrent * torrent;
3683        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3684        while ((torrent = [enumerator nextObject]))
3685            if (![torrent isActive] && ![torrent waitingToStart])
3686                return YES;
3687        return NO;
3688    }
3689   
3690    #warning hide queue options if all queues are disabled?
3691   
3692    //enable resume all waiting item
3693    if (action == @selector(resumeWaitingTorrents:))
3694    {
3695        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3696            return NO;
3697   
3698        Torrent * torrent;
3699        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3700        while ((torrent = [enumerator nextObject]))
3701            if (![torrent isActive] && [torrent waitingToStart])
3702                return YES;
3703        return NO;
3704    }
3705   
3706    //enable resume selected waiting item
3707    if (action == @selector(resumeSelectedTorrentsNoWait:))
3708    {
3709        if (!canUseTable)
3710            return NO;
3711       
3712        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3713        Torrent * torrent;
3714        while ((torrent = [enumerator nextObject]))
3715            if (![torrent isActive])
3716                return YES;
3717        return NO;
3718    }
3719
3720    //enable pause item
3721    if (action == @selector(stopSelectedTorrents:))
3722    {
3723        if (!canUseTable)
3724            return NO;
3725   
3726        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3727        Torrent * torrent;
3728        while ((torrent = [enumerator nextObject]))
3729            if ([torrent isActive] || [torrent waitingToStart])
3730                return YES;
3731        return NO;
3732    }
3733   
3734    //enable resume item
3735    if (action == @selector(resumeSelectedTorrents:))
3736    {
3737        if (!canUseTable)
3738            return NO;
3739   
3740        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3741        Torrent * torrent;
3742        while ((torrent = [enumerator nextObject]))
3743            if (![torrent isActive] && ![torrent waitingToStart])
3744                return YES;
3745        return NO;
3746    }
3747   
3748    //enable manual announce item
3749    if (action == @selector(announceSelectedTorrents:))
3750    {
3751        if (!canUseTable)
3752            return NO;
3753       
3754        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3755        Torrent * torrent;
3756        while ((torrent = [enumerator nextObject]))
3757            if ([torrent canManualAnnounce])
3758                return YES;
3759        return NO;
3760    }
3761   
3762    //enable reset cache item
3763    if (action == @selector(verifySelectedTorrents:))
3764        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3765   
3766    //enable move torrent file item
3767    if (action == @selector(moveDataFilesSelected:))
3768        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3769   
3770    //enable copy torrent file item
3771    if (action == @selector(copyTorrentFiles:))
3772        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3773   
3774    //enable reverse sort item
3775    if (action == @selector(setSortReverse:))
3776    {
3777        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3778        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3779    }
3780   
3781    //enable group sort item
3782    if (action == @selector(setSortByGroup:))
3783    {
3784        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3785        return YES;
3786    }
3787   
3788    //check proper filter search item
3789    if (action == @selector(setFilterSearchType:))
3790    {
3791        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3792       
3793        BOOL state;
3794        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3795            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3796        else
3797            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3798       
3799        [menuItem setState: state ? NSOnState : NSOffState];
3800        return YES;
3801    }
3802   
3803    return YES;
3804}
3805
3806- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3807{
3808    NSEnumerator * enumerator;
3809    Torrent * torrent;
3810
3811    switch (messageType)
3812    {
3813        case kIOMessageSystemWillSleep:
3814            //if there are any running transfers, wait 15 seconds for them to stop
3815            enumerator = [fTorrents objectEnumerator];
3816            while ((torrent = [enumerator nextObject]))
3817                if ([torrent isActive])
3818                {
3819                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3820                    [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3821                    sleep(15);
3822                    break;
3823                }
3824
3825            IOAllowPowerChange(fRootPort, (long) messageArgument);
3826            break;
3827
3828        case kIOMessageCanSystemSleep:
3829            if ([fDefaults boolForKey: @"SleepPrevent"])
3830            {
3831                //prevent idle sleep unless no torrents are active
3832                enumerator = [fTorrents objectEnumerator];
3833                while ((torrent = [enumerator nextObject]))
3834                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3835                    {
3836                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3837                        return;
3838                    }
3839            }
3840           
3841            IOAllowPowerChange(fRootPort, (long) messageArgument);
3842            break;
3843
3844        case kIOMessageSystemHasPoweredOn:
3845            //resume sleeping transfers after we wake up
3846            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3847            [self autoSpeedLimitChange: nil];
3848            break;
3849    }
3850}
3851
3852- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3853{
3854    int seeding = 0, downloading = 0;
3855    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3856    Torrent * torrent;
3857    while ((torrent = [enumerator nextObject]))
3858    {
3859        if ([torrent isSeeding])
3860            seeding++;
3861        else if ([torrent isActive])
3862            downloading++;
3863        else;
3864    }
3865   
3866    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3867            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3868   
3869    BOOL hasSeparator = seedingItem || downloadingItem;
3870   
3871    if (seeding > 0)
3872    {
3873        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3874        if (!seedingItem)
3875        {
3876            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3877            [seedingItem setTag: DOCK_SEEDING_TAG];
3878            [fDockMenu insertItem: seedingItem atIndex: 0];
3879        }
3880        else
3881            [seedingItem setTitle: title];
3882    }
3883    else
3884    {
3885        if (seedingItem)
3886            [fDockMenu removeItem: seedingItem];
3887    }
3888   
3889    if (downloading > 0)
3890    {
3891        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3892        if (!downloadingItem)
3893        {
3894            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3895            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3896            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3897        }
3898        else
3899            [downloadingItem setTitle: title];
3900    }
3901    else
3902    {
3903        if (downloadingItem)
3904            [fDockMenu removeItem: downloadingItem];
3905    }
3906   
3907    if (seeding > 0 || downloading > 0)
3908    {
3909        if (!hasSeparator)
3910            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3911    }
3912    else
3913    {
3914        if (hasSeparator)
3915            [fDockMenu removeItemAtIndex: 0];
3916    }
3917   
3918    return fDockMenu;
3919}
3920
3921- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3922{
3923    //if auto size is enabled, the current frame shouldn't need to change
3924    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3925   
3926    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3927    return frame;
3928}
3929
3930- (void) setWindowSizeToFit
3931{
3932    if ([fDefaults boolForKey: @"AutoSize"])
3933    {
3934        NSScrollView * scrollView = [fTableView enclosingScrollView];
3935       
3936        [scrollView setHasVerticalScroller: NO];
3937        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3938        [scrollView setHasVerticalScroller: YES];
3939    }
3940}
3941
3942- (NSRect) sizedWindowFrame
3943{
3944    int groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3945                    ? [fDisplayedTorrents count] : 0;
3946   
3947    float heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3948                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3949                        - [[fTableView enclosingScrollView] frame].size.height;
3950   
3951    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3952}
3953
3954- (void) updateForExpandCollape
3955{
3956    [self setWindowSizeToFit];
3957    [self setBottomCountText: YES];
3958}
3959
3960- (void) showMainWindow: (id) sender
3961{
3962    [fWindow makeKeyAndOrderFront: nil];
3963}
3964
3965- (void) windowDidBecomeMain: (NSNotification *) notification
3966{
3967    [fBadger clearCompleted];
3968    [self updateUI];
3969}
3970
3971- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3972{
3973    //only resize horizontally if autosize is enabled
3974    if ([fDefaults boolForKey: @"AutoSize"])
3975        proposedFrameSize.height = [fWindow frame].size.height;
3976    return proposedFrameSize;
3977}
3978
3979- (void) windowDidResize: (NSNotification *) notification
3980{
3981    if (![fStatusBar isHidden])
3982        [self resizeStatusButton];
3983   
3984    if ([fFilterBar isHidden])
3985        return;
3986   
3987    //replace all buttons
3988    [fActiveFilterButton sizeToFit];
3989    [fDownloadFilterButton sizeToFit];
3990    [fSeedFilterButton sizeToFit];
3991    [fPauseFilterButton sizeToFit];
3992   
3993    NSRect activeRect = [fActiveFilterButton frame];
3994   
3995    NSRect downloadRect = [fDownloadFilterButton frame];
3996    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
3997   
3998    NSRect seedRect = [fSeedFilterButton frame];
3999    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4000   
4001    NSRect pauseRect = [fPauseFilterButton frame];
4002    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4003   
4004    //size search filter to not overlap buttons
4005    NSRect searchFrame = [fSearchFilterField frame];
4006    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
4007    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
4008   
4009    //make sure it is not too long
4010    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
4011    {
4012        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
4013        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
4014    }
4015    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
4016    {
4017        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
4018        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
4019       
4020        //resize the buttons so they don't overlay
4021        int difference = (NSMaxX(pauseRect) + 5.0) - searchFrame.origin.x - 1; //subtract 1, since 0 will be counted
4022       
4023        //decrease downloading by 8, seeding by 1, paused by 1, active by 1, repeat
4024        int download = (difference / 11 * 8) + MIN(difference % 11 + 1, 8); //8 for every 11
4025        int seed = (difference / 11) + (difference % 11 >= 8 ? 1 : 0);
4026        int paused = (difference / 11) + (difference % 11 >= 9 ? 1 : 0);
4027        int active = (difference / 11) + (difference % 11 >= 10 ? 1 : 0);
4028       
4029        activeRect.size.width -= active;
4030       
4031        downloadRect.origin.x -= active;
4032        downloadRect.size.width -= download;
4033       
4034        seedRect.origin.x -= active + download;
4035        seedRect.size.width -= seed;
4036       
4037        pauseRect.origin.x -= active + download + seed;
4038        pauseRect.size.width -= paused;
4039    }
4040    else;
4041   
4042    [fActiveFilterButton setFrame: activeRect];
4043    [fDownloadFilterButton setFrame: downloadRect];
4044    [fSeedFilterButton setFrame: seedRect];
4045    [fPauseFilterButton setFrame: pauseRect];
4046   
4047    [fSearchFilterField setFrame: searchFrame];
4048}
4049
4050- (void) applicationWillUnhide: (NSNotification *) notification
4051{
4052    [self updateUI];
4053}
4054
4055- (NSArray *) quickLookURLs
4056{
4057    NSArray * selectedTorrents = [fTableView selectedTorrents];
4058    NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
4059    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4060    Torrent * torrent;
4061   
4062    while ((torrent = [enumerator nextObject]))
4063    {
4064        if ([torrent isFolder] || [torrent isComplete])
4065            [urlArray addObject: [NSURL fileURLWithPath: [torrent dataLocation]]];
4066    }
4067   
4068    return urlArray;
4069}
4070
4071- (BOOL) canQuickLook
4072{
4073    NSArray * selectedTorrents = [fTableView selectedTorrents];
4074    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4075    Torrent * torrent;
4076   
4077    while ((torrent = [enumerator nextObject]))
4078    {
4079        if ([torrent isFolder] || [torrent isComplete])
4080            return YES;
4081    }
4082   
4083    return NO;
4084}
4085
4086- (NSRect) quickLookFrameWithURL: (NSURL *) url
4087{
4088    if ([fWindow isVisible])
4089    {
4090        NSString * fullPath = [url path];
4091        NSRange visibleRows = [fTableView rowsInRect: [fTableView bounds]];
4092       
4093        int row;
4094        for (row = 0; row < NSMaxRange(visibleRows); row++)
4095        {
4096            id item = [fTableView itemAtRow: row];
4097            if ([item isKindOfClass: [Torrent class]] && [[(Torrent *)item dataLocation] isEqualToString: fullPath])
4098            {
4099                NSRect frame = [fTableView iconRectForRow: row];
4100                frame.origin = [fTableView convertPoint: frame.origin toView: nil];
4101                frame.origin = [fWindow convertBaseToScreen: frame.origin];
4102                frame.origin.y -= frame.size.height;
4103                return frame;
4104            }
4105        }
4106    }
4107   
4108    return NSZeroRect;
4109}
4110
4111- (void) toggleQuickLook: (id) sender
4112{
4113    [[QuickLookController quickLook] toggleQuickLook];
4114}
4115
4116- (void) linkHomepage: (id) sender
4117{
4118    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4119}
4120
4121- (void) linkForums: (id) sender
4122{
4123    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4124}
4125
4126- (void) linkDonate: (id) sender
4127{
4128    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4129}
4130
4131- (void) prepareForUpdate: (NSNotification *) notification
4132{
4133    fUpdateInProgress = YES;
4134}
4135
4136- (NSDictionary *) registrationDictionaryForGrowl
4137{
4138    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4139                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4140    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4141                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4142}
4143
4144- (void) growlNotificationWasClicked: (id) clickContext
4145{
4146    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4147        return;
4148   
4149    NSString * type = [clickContext objectForKey: @"Type"], * location;
4150    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4151            && (location = [clickContext objectForKey: @"Location"]))
4152        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4153}
4154
4155- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4156{
4157    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4158   
4159    //get the torrent
4160    Torrent * torrent = nil;
4161    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4162    {
4163        NSEnumerator * enumerator = [fTorrents objectEnumerator];
4164        while ((torrent = [enumerator nextObject]))
4165            if (torrentStruct == [torrent torrentStruct])
4166                break;
4167       
4168        if (!torrent)
4169        {
4170            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4171            return;
4172        }
4173       
4174        [torrent retain];
4175    }
4176   
4177    switch (type)
4178    {
4179        case TR_RPC_TORRENT_ADDED:
4180            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4181                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4182            break;
4183       
4184        case TR_RPC_TORRENT_STARTED:
4185        case TR_RPC_TORRENT_STOPPED:
4186            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4187            break;
4188       
4189        case TR_RPC_TORRENT_REMOVING:
4190            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4191            break;
4192       
4193        case TR_RPC_TORRENT_CHANGED:
4194            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4195            break;
4196       
4197        case TR_RPC_SESSION_CHANGED:
4198            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4199            break;
4200       
4201        default:
4202            NSLog(@"Unknown RPC command received!");
4203            [torrent release];
4204    }
4205   
4206    [pool release];
4207}
4208
4209- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4210{
4211    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4212    [torrentStructPtr release];
4213   
4214    NSString * location = nil;
4215    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4216        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4217   
4218    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4219   
4220    [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
4221   
4222    [torrent update];
4223    [fTorrents addObject: torrent];
4224    [torrent release];
4225   
4226    [self updateTorrentsInQueue];
4227}
4228
4229- (void) rpcRemoveTorrent: (Torrent *) torrent
4230{
4231    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO deleteTorrent: NO fromRPC: YES];
4232    [torrent release];
4233}
4234
4235- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4236{
4237    [torrent update];
4238    [torrent release];
4239   
4240    [self updateUI];
4241    [self applyFilter: nil];
4242    [self updateTorrentHistory];
4243}
4244
4245- (void) rpcChangedTorrent: (Torrent *) torrent
4246{
4247    [torrent update];
4248   
4249    if ([[fTableView selectedTorrents] containsObject: torrent])
4250    {
4251        [fInfoController updateInfoStats]; //this will reload the file table
4252        [fInfoController updateOptions];
4253    }
4254   
4255    [torrent release];
4256}
4257
4258@end
Note: See TracBrowser for help on using the repository browser.