source: trunk/macosx/Controller.m @ 6027

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

sort ip addresses in the rpc access table; other cleanup with this table code

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