source: trunk/macosx/Controller.m @ 6241

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

attempt to fix #1048

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