source: trunk/macosx/Controller.m @ 6274

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

groups are now stored as objects instead of dictionaries

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