source: trunk/macosx/Controller.m @ 6289

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

fix recently introduced bug that caused resuming/pausing torrents through the menu item when groups are shown to deselect the row

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