source: trunk/macosx/Controller.m @ 6260

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

add a comparison method for the transfer names to sort the exact same way the Finder does

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