source: trunk/macosx/Controller.m @ 6529

Last change on this file since 6529 was 6529, checked in by livings124, 13 years ago

initial Sparkle 1.5 b5 commit

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