source: trunk/macosx/Controller.m @ 6290

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

add a warning; improve the manual reordering code

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