source: trunk/macosx/Controller.m @ 6254

Last change on this file since 6254 was 6254, checked in by livings124, 15 years ago

if a group row is selected and the content changes, refresh the inspector

  • Property svn:keywords set to Date Rev Author Id
File size: 158.4 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 6254 2008-06-26 03:35:20Z 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        int i;
1268        for (i = lowestOrderValue; i < [fTorrents count]; i++)
1269            [[fTorrents objectAtIndex: i] setOrderValue: i];
1270    }
1271   
1272    [fTableView deselectAll: nil];
1273   
1274    [self updateTorrentsInQueue];
1275}
1276
1277- (void) removeNoDelete: (id) sender
1278{
1279    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: NO];
1280}
1281
1282- (void) removeDeleteData: (id) sender
1283{
1284    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: NO];
1285}
1286
1287- (void) removeDeleteTorrent: (id) sender
1288{
1289    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO deleteTorrent: YES];
1290}
1291
1292- (void) removeDeleteDataAndTorrent: (id) sender
1293{
1294    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES deleteTorrent: YES];
1295}
1296
1297- (void) moveDataFilesSelected: (id) sender
1298{
1299    [self moveDataFiles: [fTableView selectedTorrents]];
1300}
1301
1302- (void) moveDataFiles: (NSArray *) torrents
1303{
1304    NSOpenPanel * panel = [NSOpenPanel openPanel];
1305    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1306    [panel setAllowsMultipleSelection: NO];
1307    [panel setCanChooseFiles: NO];
1308    [panel setCanChooseDirectories: YES];
1309    [panel setCanCreateDirectories: YES];
1310   
1311    torrents = [torrents retain];
1312    int count = [torrents count];
1313    if (count == 1)
1314        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1315                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1316    else
1317        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1318                            "Move torrent -> select destination folder"), count]];
1319       
1320    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1321        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1322}
1323
1324- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (NSArray *) torrents
1325{
1326    if (code == NSOKButton)
1327    {
1328        NSEnumerator * enumerator = [torrents objectEnumerator];
1329        Torrent * torrent;
1330        while ((torrent = [enumerator nextObject]))
1331            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1332    }
1333   
1334    [torrents release];
1335}
1336
1337- (void) copyTorrentFiles: (id) sender
1338{
1339    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1340}
1341
1342- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1343{
1344    if ([torrents count] <= 0)
1345    {
1346        [torrents release];
1347        return;
1348    }
1349
1350    Torrent * torrent = [torrents objectAtIndex: 0];
1351
1352    //warn user if torrent file can't be found
1353    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1354    {
1355        NSAlert * alert = [[NSAlert alloc] init];
1356        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1357        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1358                                "Torrent file copy alert -> title"), [torrent name]]];
1359        [alert setInformativeText: [NSString stringWithFormat:
1360                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1361                                    [torrent torrentLocation]]];
1362        [alert setAlertStyle: NSWarningAlertStyle];
1363       
1364        [alert runModal];
1365        [alert release];
1366       
1367        [torrents removeObjectAtIndex: 0];
1368        [self copyTorrentFileForTorrents: torrents];
1369    }
1370    else
1371    {
1372        NSSavePanel * panel = [NSSavePanel savePanel];
1373        [panel setRequiredFileType: @"torrent"];
1374        [panel setCanSelectHiddenExtension: YES];
1375       
1376        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1377            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1378    }
1379}
1380
1381- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (NSMutableArray *) torrents
1382{
1383    //copy torrent to new location with name of data file
1384    if (code == NSOKButton)
1385        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1386   
1387    [torrents removeObjectAtIndex: 0];
1388    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1389}
1390
1391- (void) revealFile: (id) sender
1392{
1393    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
1394    Torrent * torrent;
1395    while ((torrent = [enumerator nextObject]))
1396        [torrent revealData];
1397}
1398
1399- (void) announceSelectedTorrents: (id) sender
1400{
1401    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
1402    Torrent * torrent;
1403    while ((torrent = [enumerator nextObject]))
1404    {
1405        if ([torrent canManualAnnounce])
1406            [torrent manualAnnounce];
1407    }
1408}
1409
1410- (void) verifySelectedTorrents: (id) sender
1411{
1412    [self verifyTorrents: [fTableView selectedTorrents]];
1413}
1414
1415- (void) verifyTorrents: (NSArray *) torrents
1416{
1417    NSEnumerator * enumerator = [torrents objectEnumerator];
1418    Torrent * torrent;
1419    while ((torrent = [enumerator nextObject]))
1420        [torrent resetCache];
1421   
1422    [self applyFilter: nil];
1423}
1424
1425- (void) showPreferenceWindow: (id) sender
1426{
1427    NSWindow * window = [fPrefsController window];
1428    if (![window isVisible])
1429        [window center];
1430
1431    [window makeKeyAndOrderFront: nil];
1432}
1433
1434- (void) showAboutWindow: (id) sender
1435{
1436    [[AboutWindowController aboutController] showWindow: nil];
1437}
1438
1439- (void) showInfo: (id) sender
1440{
1441    if ([[fInfoController window] isVisible])
1442        [fInfoController close];
1443    else
1444    {
1445        [fInfoController updateInfoStats];
1446        [[fInfoController window] orderFront: nil];
1447    }
1448}
1449
1450- (void) resetInfo
1451{
1452    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1453    [[QuickLookController quickLook] updateQuickLook];
1454}
1455
1456- (void) setInfoTab: (id) sender
1457{
1458    if (sender == fNextInfoTabItem)
1459        [fInfoController setNextTab];
1460    else
1461        [fInfoController setPreviousTab];
1462}
1463
1464- (void) showMessageWindow: (id) sender
1465{
1466    [fMessageController showWindow: nil];
1467}
1468
1469- (void) showStatsWindow: (id) sender
1470{
1471    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1472}
1473
1474- (void) updateUI
1475{
1476    [fTorrents makeObjectsPerformSelector: @selector(update)];
1477   
1478    if (![NSApp isHidden])
1479    {
1480        if ([fWindow isVisible])
1481        {
1482            [self sortTorrents];
1483           
1484            //update status bar
1485            if (![fStatusBar isHidden])
1486            {
1487                //set rates
1488                float downloadRate, uploadRate;
1489                tr_sessionGetSpeed(fLib, &downloadRate, &uploadRate);
1490               
1491                [fTotalDLField setStringValue: [NSString stringForSpeed: downloadRate]];
1492                [fTotalULField setStringValue: [NSString stringForSpeed: uploadRate]];
1493               
1494                //set status button text
1495                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1496                BOOL total;
1497                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1498                {
1499                    tr_session_stats stats;
1500                    if (total)
1501                        tr_sessionGetCumulativeStats(fLib, &stats);
1502                    else
1503                        tr_sessionGetStats(fLib, &stats);
1504                   
1505                    statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") stringByAppendingFormat: @": %@",
1506                                    [NSString stringForRatio: stats.ratio]];
1507                }
1508                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1509                {
1510                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1511                   
1512                    tr_session_stats stats;
1513                    if (total)
1514                        tr_sessionGetCumulativeStats(fLib, &stats);
1515                    else
1516                        tr_sessionGetStats(fLib, &stats);
1517                   
1518                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1519                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1520                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1521                }
1522               
1523                if ([NSApp isOnLeopardOrBetter])
1524                {
1525                    [fStatusButton setTitle: statusString];
1526                    [self resizeStatusButton];
1527                }
1528                else
1529                    [fStatusTigerField setStringValue: statusString];
1530            }
1531        }
1532
1533        //update non-constant parts of info window
1534        if ([[fInfoController window] isVisible])
1535            [fInfoController updateInfoStats];
1536    }
1537   
1538    //badge dock
1539    [fBadger updateBadge];
1540}
1541
1542- (void) resizeStatusButton
1543{
1544    [fStatusButton sizeToFit];
1545   
1546    //width ends up being too long
1547    NSRect statusFrame = [fStatusButton frame];
1548    statusFrame.size.width -= 25.0;
1549   
1550    float difference = NSMaxX(statusFrame) + 5.0 - [fTotalDLImageView frame].origin.x;
1551    if (difference > 0)
1552        statusFrame.size.width -= difference;
1553   
1554    [fStatusButton setFrame: statusFrame];
1555}
1556
1557- (void) setBottomCountText: (BOOL) filtering
1558{
1559    NSString * totalTorrentsString;
1560    int totalCount = [fTorrents count];
1561    if (totalCount != 1)
1562        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1563    else
1564        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1565   
1566    if (filtering)
1567    {
1568        int count = [fTableView numberOfRows]; //have to factor in collapsed rows
1569        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1570            count -= [fDisplayedTorrents count];
1571       
1572        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d of %@", "Status bar transfer count"),
1573                                count, totalTorrentsString];
1574    }
1575   
1576    [fTotalTorrentsField setStringValue: totalTorrentsString];
1577}
1578
1579- (void) updateTorrentsInQueue
1580{
1581    BOOL download = [fDefaults boolForKey: @"Queue"],
1582        seed = [fDefaults boolForKey: @"QueueSeed"];
1583   
1584    int desiredDownloadActive = [self numToStartFromQueue: YES],
1585        desiredSeedActive = [self numToStartFromQueue: NO];
1586   
1587    Torrent * torrent;
1588    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1589    while ((torrent = [enumerator nextObject]))
1590    {
1591        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1592        {
1593            if (![torrent allDownloaded])
1594            {
1595                if (!download || desiredDownloadActive > 0)
1596                {
1597                    [torrent startTransfer];
1598                    if ([torrent isActive])
1599                        desiredDownloadActive--;
1600                    [torrent update];
1601                }
1602            }
1603            else
1604            {
1605                if (!seed || desiredSeedActive > 0)
1606                {
1607                    [torrent startTransfer];
1608                    if ([torrent isActive])
1609                        desiredSeedActive--;
1610                    [torrent update];
1611                }
1612            }
1613        }
1614    }
1615   
1616    [self updateUI];
1617    [self applyFilter: nil];
1618    [self updateTorrentHistory];
1619}
1620
1621- (int) numToStartFromQueue: (BOOL) downloadQueue
1622{
1623    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1624        return 0;
1625   
1626    int desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1627       
1628    Torrent * torrent;
1629    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1630    while ((torrent = [enumerator nextObject]))
1631    {
1632        if ([torrent isChecking])
1633        {
1634            desired--;
1635            if (desired <= 0)
1636                return 0;
1637        }
1638        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1639        {
1640            if ([torrent allDownloaded] != downloadQueue)
1641            {
1642                desired--;
1643                if (desired <= 0)
1644                    return 0;
1645            }
1646        }
1647        else;
1648    }
1649   
1650    return desired;
1651}
1652
1653- (void) torrentFinishedDownloading: (NSNotification *) notification
1654{
1655    Torrent * torrent = [notification object];
1656   
1657    if ([torrent isActive])
1658    {
1659        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1660        {
1661            NSSound * sound;
1662            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1663            {
1664                [sound setDelegate: self];
1665                fSoundPlaying = YES;
1666                [sound play];
1667            }
1668        }
1669       
1670        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1671                                        [torrent dataLocation] , @"Location", nil];
1672        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1673                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1674                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1675       
1676        if (![fWindow isMainWindow])
1677            [fBadger incrementCompleted];
1678       
1679        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1680        {
1681            [torrent stopTransfer];
1682            [torrent setWaitToStart: YES];
1683        }
1684    }
1685   
1686    [self updateTorrentsInQueue];
1687}
1688
1689- (void) torrentRestartedDownloading: (NSNotification *) notification
1690{
1691    Torrent * torrent = [notification object];
1692    if ([torrent isActive])
1693    {
1694        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1695        {
1696            [torrent stopTransfer];
1697            [torrent setWaitToStart: YES];
1698        }
1699    }
1700   
1701    [self updateTorrentsInQueue];
1702}
1703
1704- (void) torrentStoppedForRatio: (NSNotification *) notification
1705{
1706    Torrent * torrent = [notification object];
1707   
1708    [self updateTorrentsInQueue];
1709   
1710    if ([[fTableView selectedTorrents] containsObject: torrent])
1711    {
1712        [fInfoController updateInfoStats];
1713        [fInfoController updateOptions];
1714    }
1715   
1716    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1717    {
1718        NSSound * sound;
1719        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1720        {
1721            [sound setDelegate: self];
1722            fSoundPlaying = YES;
1723            [sound play];
1724        }
1725    }
1726   
1727    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
1728                                    [torrent dataLocation], @"Location", nil];
1729    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1730                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1731                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1732}
1733
1734- (void) updateTorrentHistory
1735{
1736    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1737
1738    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1739    Torrent * torrent;
1740    while ((torrent = [enumerator nextObject]))
1741        [history addObject: [torrent history]];
1742
1743    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER] atomically: YES];
1744}
1745
1746- (void) setSort: (id) sender
1747{
1748    NSString * sortType;
1749    switch ([sender tag])
1750    {
1751        case SORT_ORDER_TAG:
1752            sortType = SORT_ORDER;
1753            [fDefaults setBool: NO forKey: @"SortReverse"];
1754            break;
1755        case SORT_DATE_TAG:
1756            sortType = SORT_DATE;
1757            break;
1758        case SORT_NAME_TAG:
1759            sortType = SORT_NAME;
1760            break;
1761        case SORT_PROGRESS_TAG:
1762            sortType = SORT_PROGRESS;
1763            break;
1764        case SORT_STATE_TAG:
1765            sortType = SORT_STATE;
1766            break;
1767        case SORT_TRACKER_TAG:
1768            sortType = SORT_TRACKER;
1769            break;
1770        case SORT_ACTIVITY_TAG:
1771            sortType = SORT_ACTIVITY;
1772            break;
1773        default:
1774            return;
1775    }
1776   
1777    [fDefaults setObject: sortType forKey: @"Sort"];
1778    [self sortTorrents];
1779}
1780
1781- (void) setSortByGroup: (id) sender
1782{
1783    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1784    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1785   
1786    //expand all groups
1787    if (sortByGroup)
1788        [fTableView removeAllCollapsedGroups];
1789   
1790    [self applyFilter: nil];
1791}
1792
1793- (void) setSortReverse: (id) sender
1794{
1795    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1796    [self sortTorrents];
1797}
1798
1799- (void) sortTorrents
1800{
1801    NSArray * selectedValues = [fTableView selectedValues];
1802   
1803    [self sortTorrentsIgnoreSelected]; //actually sort
1804   
1805    [fTableView selectValues: selectedValues];
1806}
1807
1808- (void) sortTorrentsIgnoreSelected
1809{
1810    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1811    BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1812   
1813    NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue" ascending: asc] autorelease];
1814   
1815    NSArray * descriptors;
1816    if ([sortType isEqualToString: SORT_ORDER])
1817        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1818    else if ([sortType isEqualToString: SORT_NAME])
1819    {
1820        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1821                                                selector: @selector(caseInsensitiveCompare:)] autorelease];
1822       
1823        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1824    }
1825    else if ([sortType isEqualToString: SORT_STATE])
1826    {
1827        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1828                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1829                        * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1830                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1831                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1832       
1833        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1834                                                            nameDescriptor, orderDescriptor, nil];
1835    }
1836    else if ([sortType isEqualToString: SORT_PROGRESS])
1837    {
1838        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1839                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1840                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1841                        * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1842                                                        ascending: asc] autorelease],
1843                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1844       
1845        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1846                                                            nameDescriptor, orderDescriptor, nil];
1847    }
1848    else if ([sortType isEqualToString: SORT_TRACKER])
1849    {
1850        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1851                                                selector: @selector(caseInsensitiveCompare:)] autorelease],
1852                        * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddressAnnounce" ascending: asc
1853                                                selector: @selector(caseInsensitiveCompare:)] autorelease];
1854       
1855        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, orderDescriptor, nil];
1856    }
1857    else if ([sortType isEqualToString: SORT_ACTIVITY])
1858    {
1859        NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1860        NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1861                                                    autorelease];
1862       
1863        descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, orderDescriptor, nil];
1864    }
1865    else
1866    {
1867        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1868   
1869        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1870    }
1871   
1872    //on Tiger add the group sort descriptor to the front
1873    if (![NSApp isOnLeopardOrBetter] && [fDefaults boolForKey: @"SortByGroup"])
1874    {
1875        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
1876       
1877        NSMutableArray * temp = [[NSMutableArray alloc] initWithCapacity: [descriptors count]+1];
1878        [temp addObject: groupDescriptor];
1879        [temp addObjectsFromArray: descriptors];
1880       
1881        [descriptors release];
1882        descriptors = temp;
1883    }
1884   
1885    //actually sort
1886    if ([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
1887    {
1888        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1889        NSDictionary * dict;
1890        while ((dict = [enumerator nextObject]))
1891            [[dict objectForKey: @"Torrents"] sortUsingDescriptors: descriptors];
1892    }
1893    else
1894        [fDisplayedTorrents sortUsingDescriptors: descriptors];
1895   
1896    [descriptors release];
1897   
1898    [fTableView reloadData];
1899}
1900
1901- (void) applyFilter: (id) sender
1902{
1903    //get all the torrents in the table
1904    NSMutableArray * previousTorrents;
1905    if ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1906    {
1907        previousTorrents = [NSMutableArray array];
1908       
1909        NSEnumerator * enumerator = [fDisplayedTorrents objectEnumerator];
1910        NSDictionary * dict;
1911        while ((dict = [enumerator nextObject]))
1912            [previousTorrents addObjectsFromArray: [dict objectForKey: @"Torrents"]];
1913    }
1914    else
1915        previousTorrents = fDisplayedTorrents;
1916   
1917    NSArray * selectedValues = [fTableView selectedValues];
1918   
1919    int active = 0, downloading = 0, seeding = 0, paused = 0;
1920    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1921    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1922    if ([filterType isEqualToString: FILTER_ACTIVE])
1923        filterActive = YES;
1924    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1925        filterDownload = YES;
1926    else if ([filterType isEqualToString: FILTER_SEED])
1927        filterSeed = YES;
1928    else if ([filterType isEqualToString: FILTER_PAUSE])
1929        filterPause = YES;
1930    else
1931        filterStatus = NO;
1932   
1933    int groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
1934    BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
1935   
1936    NSString * searchString = [fSearchFilterField stringValue];
1937    BOOL filterText = [searchString length] > 0,
1938        filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
1939   
1940    NSMutableIndexSet * indexes = [NSMutableIndexSet indexSet];
1941   
1942    //get count of each type
1943    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1944    Torrent * torrent;
1945    int i = -1;
1946    while ((torrent = [enumerator nextObject]))
1947    {
1948        i++;
1949       
1950        //check status
1951        if ([torrent isActive] && ![torrent isCheckingWaiting])
1952        {
1953            if ([torrent isSeeding])
1954            {
1955                seeding++;
1956                BOOL isActive = ![torrent isStalled];
1957                if (isActive)
1958                    active++;
1959               
1960                if (filterStatus && (!(filterActive && isActive) && !filterSeed))
1961                    continue;
1962            }
1963            else
1964            {
1965                downloading++;
1966                BOOL isActive = ![torrent isStalled];
1967                if (isActive)
1968                    active++;
1969               
1970                if (filterStatus && (!(filterActive && isActive) && !filterDownload))
1971                    continue;
1972            }
1973        }
1974        else
1975        {
1976            paused++;
1977            if (filterStatus && !filterPause)
1978                continue;
1979        }
1980       
1981        //checkGroup
1982        if (filterGroup)
1983            if ([torrent groupValue] != groupFilterValue)
1984                continue;
1985       
1986        //check text field
1987        if (filterText)
1988        {
1989            if (filterTracker)
1990            {
1991                BOOL removeTextField = YES;
1992                NSEnumerator * trackerEnumerator = [[torrent allTrackers: NO] objectEnumerator];
1993                NSString * tracker;
1994                while ((tracker = [trackerEnumerator nextObject]))
1995                {
1996                    if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1997                    {
1998                        removeTextField = NO;
1999                        break;
2000                    }
2001                }
2002               
2003                if (removeTextField)
2004                    continue;
2005            }
2006            else
2007            {
2008                if ([[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound)
2009                    continue;
2010            }
2011        }
2012       
2013        [indexes addIndex: i];
2014    }
2015   
2016    NSArray * allTorrents = [fTorrents objectsAtIndexes: indexes];
2017   
2018    //set button tooltips
2019    [fNoFilterButton setCount: [fTorrents count]];
2020    [fActiveFilterButton setCount: active];
2021    [fDownloadFilterButton setCount: downloading];
2022    [fSeedFilterButton setCount: seeding];
2023    [fPauseFilterButton setCount: paused];
2024   
2025    //clear display cache for not-shown torrents
2026    [previousTorrents removeObjectsInArray: allTorrents];
2027    enumerator = [previousTorrents objectEnumerator];
2028    while ((torrent = [enumerator nextObject]))
2029        [torrent setPreviousFinishedPieces: nil];
2030   
2031    //place torrents into groups
2032    BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter];
2033    if (groupRows)
2034    {
2035        [fDisplayedTorrents removeAllObjects];
2036       
2037        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2038        allTorrents = [allTorrents sortedArrayUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2039       
2040        NSMutableArray * groupTorrents;
2041        int oldGroupValue = -2;
2042        for (i = 0; i < [allTorrents count]; i++)
2043        {
2044            torrent = [allTorrents objectAtIndex: i];
2045            int groupValue = [torrent groupValue];
2046            if (groupValue != oldGroupValue)
2047            {
2048                groupTorrents = [NSMutableArray array];
2049                NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt: groupValue], @"Group",
2050                                        groupTorrents, @"Torrents", nil];
2051                [fDisplayedTorrents addObject: dict];
2052               
2053                oldGroupValue = groupValue;
2054            }
2055           
2056            [groupTorrents addObject: torrent];
2057        }
2058    }
2059    else
2060        [fDisplayedTorrents setArray: allTorrents];
2061   
2062    //actually sort
2063    [self sortTorrentsIgnoreSelected];
2064    [fTableView selectValues: selectedValues];
2065    [self resetInfo]; //if group is already selected, but the torrents in it change
2066   
2067    //reset expanded/collapsed rows
2068    if (groupRows)
2069    {
2070        enumerator = [fDisplayedTorrents objectEnumerator];
2071        NSDictionary * dict;
2072        while ((dict = [enumerator nextObject]))
2073        {
2074            if ([fTableView isGroupCollapsed: [[dict objectForKey: @"Group"] intValue]])
2075                [fTableView collapseItem: dict];
2076            else
2077                [fTableView expandItem: dict];
2078        }
2079    }
2080   
2081    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2082   
2083    [self setWindowSizeToFit];
2084}
2085
2086//resets filter and sorts torrents
2087- (void) setFilter: (id) sender
2088{
2089    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2090   
2091    NSButton * prevFilterButton;
2092    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2093        prevFilterButton = fPauseFilterButton;
2094    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2095        prevFilterButton = fActiveFilterButton;
2096    else if ([oldFilterType isEqualToString: FILTER_SEED])
2097        prevFilterButton = fSeedFilterButton;
2098    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2099        prevFilterButton = fDownloadFilterButton;
2100    else
2101        prevFilterButton = fNoFilterButton;
2102   
2103    if (sender != prevFilterButton)
2104    {
2105        [prevFilterButton setState: NSOffState];
2106        [sender setState: NSOnState];
2107
2108        NSString * filterType;
2109        if (sender == fActiveFilterButton)
2110            filterType = FILTER_ACTIVE;
2111        else if (sender == fDownloadFilterButton)
2112            filterType = FILTER_DOWNLOAD;
2113        else if (sender == fPauseFilterButton)
2114            filterType = FILTER_PAUSE;
2115        else if (sender == fSeedFilterButton)
2116            filterType = FILTER_SEED;
2117        else
2118            filterType = FILTER_NONE;
2119
2120        [fDefaults setObject: filterType forKey: @"Filter"];
2121    }
2122    else
2123        [sender setState: NSOnState];
2124
2125    [self applyFilter: nil];
2126}
2127
2128- (void) setFilterSearchType: (id) sender
2129{
2130    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2131   
2132    int prevTag, currentTag = [sender tag];
2133    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2134        prevTag = FILTER_TYPE_TAG_TRACKER;
2135    else
2136        prevTag = FILTER_TYPE_TAG_NAME;
2137   
2138    if (currentTag != prevTag)
2139    {
2140        NSString * filterType;
2141        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2142            filterType = FILTER_TYPE_TRACKER;
2143        else
2144            filterType = FILTER_TYPE_NAME;
2145       
2146        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2147       
2148        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2149    }
2150   
2151    [self applyFilter: nil];
2152}
2153
2154- (void) switchFilter: (id) sender
2155{
2156    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2157   
2158    NSButton * button;
2159    if ([filterType isEqualToString: FILTER_NONE])
2160        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2161    else if ([filterType isEqualToString: FILTER_ACTIVE])
2162        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2163    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2164        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2165    else if ([filterType isEqualToString: FILTER_SEED])
2166        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2167    else if ([filterType isEqualToString: FILTER_PAUSE])
2168        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2169    else
2170        button = fNoFilterButton;
2171   
2172    [self setFilter: button];
2173}
2174
2175- (void) setStatusLabel: (id) sender
2176{
2177    NSString * statusLabel;
2178    switch ([sender tag])
2179    {
2180        case STATUS_RATIO_TOTAL_TAG:
2181            statusLabel = STATUS_RATIO_TOTAL;
2182            break;
2183        case STATUS_RATIO_SESSION_TAG:
2184            statusLabel = STATUS_RATIO_SESSION;
2185            break;
2186        case STATUS_TRANSFER_TOTAL_TAG:
2187            statusLabel = STATUS_TRANSFER_TOTAL;
2188            break;
2189        case STATUS_TRANSFER_SESSION_TAG:
2190            statusLabel = STATUS_TRANSFER_SESSION;
2191            break;
2192        default:
2193            return;
2194    }
2195   
2196    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2197    [self updateUI];
2198}
2199
2200- (void) showGroups: (id) sender
2201{
2202    [[GroupsWindowController groupsWindow] showWindow: self];
2203}
2204
2205- (void) menuNeedsUpdate: (NSMenu *) menu
2206{
2207    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2208    {
2209        int i;
2210        for (i = [menu numberOfItems]-1 - 2; i >= 0; i--)
2211            [menu removeItemAtIndex: i];
2212       
2213        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2214        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2215                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: NO];
2216    }
2217    else if (menu == fGroupFilterMenu)
2218    {
2219        int i;
2220        for (i = [menu numberOfItems]-1; i >= 3; i--)
2221            [menu removeItemAtIndex: i];
2222       
2223        NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:)
2224                                isSmall: YES];
2225        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2226                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: YES];
2227    }
2228    else if (menu == fUploadMenu || menu == fDownloadMenu)
2229    {
2230        if ([menu numberOfItems] > 3)
2231            return;
2232       
2233        const int speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, -1 };
2234       
2235        NSMenuItem * item;
2236        int i;
2237        for (i = 0; speedLimitActionValue[i] != -1; i++)
2238        {
2239            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2240                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2241                    keyEquivalent: @""];
2242            [item setTarget: self];
2243            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2244            [menu addItem: item];
2245            [item release];
2246        }
2247    }
2248    else if (menu == fRatioStopMenu)
2249    {
2250        if ([menu numberOfItems] > 3)
2251            return;
2252       
2253        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2254       
2255        NSMenuItem * item;
2256        int i;
2257        for (i = 0; ratioLimitActionValue[i] != -1; i++)
2258        {
2259            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2260                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2261            [item setTarget: self];
2262            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2263            [menu addItem: item];
2264            [item release];
2265        }
2266    }
2267    else;
2268}
2269
2270- (void) setGroup: (id) sender
2271{
2272    NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
2273    Torrent * torrent;
2274    while ((torrent = [enumerator nextObject]))
2275    {
2276        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2277       
2278        [torrent setGroupValue: [sender tag]];
2279    }
2280   
2281    [self applyFilter: nil];
2282    [self updateUI];
2283    [self updateTorrentHistory];
2284}
2285
2286- (void) setGroupFilter: (id) sender
2287{
2288    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2289    [self updateGroupsFilterButton];
2290    [self applyFilter: nil];
2291}
2292
2293- (void) updateGroupsFilterButton
2294{
2295    int groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2296   
2297    NSImage * icon;
2298    NSString * toolTip;
2299    if (groupIndex == GROUP_FILTER_ALL_TAG)
2300    {
2301        icon = [NSImage imageNamed: @"PinTemplate.png"];
2302        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2303    }
2304    else
2305    {
2306        icon = [[GroupsController groups] imageForIndex: groupIndex];
2307        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2308                                                : NSLocalizedString(@"None", "Groups -> Button");
2309        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2310    }
2311   
2312    //tiger doesn't have built-in image scaling in buttons
2313    if (![NSApp isOnLeopardOrBetter])
2314    {
2315        icon = [[icon copy] autorelease];
2316        [icon setScalesWhenResized: YES];
2317        [icon setSize: NSMakeSize(12.0, 12.0)];
2318    }
2319   
2320    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2321    [fGroupsButton setToolTip: toolTip];
2322}
2323
2324- (void) updateGroupsFilters: (NSNotification *) notification
2325{
2326    [self updateGroupsFilterButton];
2327    [self applyFilter: nil];
2328}
2329
2330- (void) toggleSpeedLimit: (id) sender
2331{
2332    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2333    [fPrefsController applySpeedSettings: nil];
2334}
2335
2336- (void) autoSpeedLimitChange: (NSNotification *) notification
2337{
2338    //clear timer here in case its not being reset
2339    [fSpeedLimitTimer invalidate];
2340    fSpeedLimitTimer = nil;
2341   
2342    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2343        return;
2344   
2345    NSCalendar * calendar = [NSCalendar currentCalendar];
2346    NSDateComponents * nowComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2347                    * onComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2348                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]],
2349                    * offComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit
2350                                        fromDate: [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]];
2351   
2352    //check if should be on if within range
2353    int onTime = [onComponents hour] * 60 + [onComponents minute],
2354        offTime = [offComponents hour] * 60 + [offComponents minute],
2355        nowTime = [nowComponents hour] * 60 + [nowComponents minute];
2356   
2357    BOOL shouldBeOn = NO;
2358    if (onTime < offTime)
2359        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2360    else if (onTime > offTime)
2361        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2362    else;
2363   
2364    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2365        [self toggleSpeedLimit: nil];
2366   
2367    //no need to set the timer if both times are equal
2368    if (onTime == offTime)
2369        return;
2370   
2371    [self setAutoSpeedLimitTimer: !shouldBeOn];
2372}
2373
2374//only called by fSpeedLimitTimer
2375- (void) autoSpeedLimit: (NSTimer *) timer
2376{
2377    BOOL shouldLimit = [[timer userInfo] boolValue];
2378   
2379    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldLimit)
2380    {
2381        [self toggleSpeedLimit: nil];
2382       
2383        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2384                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2385                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2386            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2387            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2388    }
2389   
2390    [self setAutoSpeedLimitTimer: !shouldLimit];
2391}
2392
2393- (void) setAutoSpeedLimitTimer: (BOOL) nextIsLimit
2394{
2395    NSDate * timerDate = [fDefaults objectForKey: nextIsLimit ? @"SpeedLimitAutoOnDate" : @"SpeedLimitAutoOffDate"];
2396   
2397    //create date with combination of the current date and the date to go off
2398    NSCalendar * calendar = [NSCalendar currentCalendar];
2399    NSDateComponents * nowComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
2400                                        | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: [NSDate date]],
2401                    * timerComponents = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: timerDate];
2402   
2403    //check if should be the next day
2404    int nowTime = [nowComponents hour] * 60 + [nowComponents minute],
2405        timerTime = [timerComponents hour] * 60 + [timerComponents minute];
2406    if (timerTime < nowTime)
2407        [nowComponents setDay: [nowComponents day] + 1]; //properly goes to next month when appropriate
2408   
2409    [nowComponents setHour: [timerComponents hour]];
2410    [nowComponents setMinute: [timerComponents minute]];
2411    [nowComponents setSecond: 0];
2412   
2413    NSDate * dateToUse = [calendar dateFromComponents: nowComponents];
2414   
2415    fSpeedLimitTimer = [[NSTimer alloc] initWithFireDate: dateToUse interval: 0 target: self selector: @selector(autoSpeedLimit:)
2416                        userInfo: [NSNumber numberWithBool: nextIsLimit] repeats: NO];
2417   
2418    [[NSRunLoop currentRunLoop] addTimer: fSpeedLimitTimer forMode: NSDefaultRunLoopMode];
2419    [[NSRunLoop currentRunLoop] addTimer: fSpeedLimitTimer forMode: NSModalPanelRunLoopMode];
2420    [[NSRunLoop currentRunLoop] addTimer: fSpeedLimitTimer forMode: NSEventTrackingRunLoopMode];
2421    [fSpeedLimitTimer release];
2422}
2423
2424- (void) setLimitGlobalEnabled: (id) sender
2425{
2426    BOOL upload = [sender menu] == fUploadMenu;
2427    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2428   
2429    [fPrefsController applySpeedSettings: nil];
2430}
2431
2432- (void) setQuickLimitGlobal: (id) sender
2433{
2434    BOOL upload = [sender menu] == fUploadMenu;
2435    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2436    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2437   
2438    [fPrefsController updateLimitFields];
2439    [fPrefsController applySpeedSettings: nil];
2440}
2441
2442- (void) setRatioGlobalEnabled: (id) sender
2443{
2444    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2445}
2446
2447- (void) setQuickRatioGlobal: (id) sender
2448{
2449    [fDefaults setBool: YES forKey: @"RatioCheck"];
2450    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2451   
2452    [fPrefsController updateRatioStopField];
2453}
2454
2455- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2456{
2457    fSoundPlaying = NO;
2458}
2459
2460- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2461{
2462    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2463    {
2464        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2465            return;
2466       
2467        if (fAutoImportTimer)
2468        {
2469            if ([fAutoImportTimer isValid])
2470                [fAutoImportTimer invalidate];
2471            [fAutoImportTimer release];
2472            fAutoImportTimer = nil;
2473        }
2474       
2475        //check again in 10 seconds in case torrent file wasn't complete
2476        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2477            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2478       
2479        [self checkAutoImportDirectory];
2480    }
2481}
2482
2483- (void) changeAutoImport
2484{
2485    if (fAutoImportTimer)
2486    {
2487        if ([fAutoImportTimer isValid])
2488            [fAutoImportTimer invalidate];
2489        [fAutoImportTimer release];
2490        fAutoImportTimer = nil;
2491    }
2492   
2493    if (fAutoImportedNames)
2494    {
2495        [fAutoImportedNames release];
2496        fAutoImportedNames = nil;
2497    }
2498   
2499    [self checkAutoImportDirectory];
2500}
2501
2502- (void) checkAutoImportDirectory
2503{
2504    NSString * path;
2505    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2506        return;
2507   
2508    path = [path stringByExpandingTildeInPath];
2509   
2510    NSArray * importedNames;
2511    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2512        return;
2513   
2514    //only check files that have not been checked yet
2515    NSMutableArray * newNames = [importedNames mutableCopy];
2516   
2517    if (fAutoImportedNames)
2518        [newNames removeObjectsInArray: fAutoImportedNames];
2519    else
2520        fAutoImportedNames = [[NSMutableArray alloc] init];
2521    [fAutoImportedNames setArray: importedNames];
2522   
2523    NSString * file;
2524    int i;
2525    for (i = [newNames count] - 1; i >= 0; i--)
2526    {
2527        file = [newNames objectAtIndex: i];
2528        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2529            [newNames removeObjectAtIndex: i];
2530        else
2531            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2532    }
2533   
2534    NSEnumerator * enumerator = [newNames objectEnumerator];
2535    tr_ctor * ctor;
2536    while ((file = [enumerator nextObject]))
2537    {
2538        ctor = tr_ctorNew(fLib);
2539        tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2540       
2541        switch (tr_torrentParse(fLib, ctor, NULL))
2542        {
2543            case TR_OK:
2544                [self openFiles: [NSArray arrayWithObject: file] addType: ADD_AUTO forcePath: nil];
2545               
2546                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2547                    description: [file lastPathComponent] notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2548                    clickContext: nil];
2549                break;
2550           
2551            case TR_EINVALID:
2552                [fAutoImportedNames removeObject: [file lastPathComponent]];
2553        }
2554       
2555        tr_ctorFree(ctor);
2556    }
2557   
2558    [newNames release];
2559}
2560
2561- (void) beginCreateFile: (NSNotification *) notification
2562{
2563    if (![fDefaults boolForKey: @"AutoImport"])
2564        return;
2565   
2566    NSString * location = [notification object],
2567            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2568   
2569    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2570                                    isEqualToString: [path stringByExpandingTildeInPath]])
2571        [fAutoImportedNames addObject: [location lastPathComponent]];
2572}
2573
2574- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2575{
2576    if (item)
2577        return [[item objectForKey: @"Torrents"] count];
2578    else
2579        return [fDisplayedTorrents count];
2580}
2581
2582- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2583{
2584    if (item)
2585        return [[item objectForKey: @"Torrents"] objectAtIndex: index];
2586    else
2587        return [fDisplayedTorrents objectAtIndex: index];
2588}
2589
2590- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2591{
2592    return ![item isKindOfClass: [Torrent class]];
2593}
2594
2595- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2596{
2597    if ([item isKindOfClass: [Torrent class]])
2598        return [item hashString];
2599    else
2600    {
2601        NSString * ident = [tableColumn identifier];
2602        if ([ident isEqualToString: @"Group"])
2603        {
2604            int group = [[item objectForKey: @"Group"] intValue];
2605            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2606                                : NSLocalizedString(@"No Group", "Group table row");
2607        }
2608        else if ([ident isEqualToString: @"Color"])
2609        {
2610            int group = [[item objectForKey: @"Group"] intValue];
2611            return [[GroupsController groups] imageForIndex: group];
2612        }
2613        else if ([ident isEqualToString: @"DL Image"])
2614            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2615        else if ([ident isEqualToString: @"UL Image"])
2616            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2617                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2618        else
2619        {
2620            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2621            {
2622                uint64_t uploaded = 0, downloaded = 0;
2623                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2624                Torrent * torrent;
2625                while ((torrent = [enumerator nextObject]))
2626                {
2627                    uploaded += [torrent uploadedTotal];
2628                    downloaded += [torrent downloadedTotal];
2629                }
2630               
2631                return [NSString stringForRatio: tr_getRatio(uploaded, downloaded)];
2632            }
2633            else
2634            {
2635                BOOL upload = [ident isEqualToString: @"UL"];
2636               
2637                float rate = 0.0;
2638                NSEnumerator * enumerator = [[item objectForKey: @"Torrents"] objectEnumerator];
2639                Torrent * torrent;
2640                while ((torrent = [enumerator nextObject]))
2641                    rate += upload ? [torrent uploadRate] : [torrent downloadRate];
2642               
2643                return [NSString stringForSpeed: rate];
2644            }
2645        }
2646    }
2647}
2648
2649- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2650{
2651    //only allow reordering of rows if sorting by order
2652    if (([fDefaults boolForKey: @"SortByGroup"] && [NSApp isOnLeopardOrBetter])
2653        || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2654    {
2655        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2656        NSEnumerator * enumerator = [items objectEnumerator];
2657        id torrent;
2658        while ((torrent = [enumerator nextObject]))
2659        {
2660            if (![torrent isKindOfClass: [Torrent class]])
2661                return NO;
2662           
2663            [indexSet addIndex: [fTableView rowForItem: torrent]];
2664        }
2665       
2666        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2667        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2668        return YES;
2669    }
2670    return NO;
2671}
2672
2673- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2674    proposedChildIndex: (NSInteger) index
2675{
2676    NSPasteboard * pasteboard = [info draggingPasteboard];
2677    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2678    {
2679        if ([fDefaults boolForKey: @"SortByGroup"])
2680        {
2681            if (!item)
2682                return NSDragOperationNone;
2683           
2684            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2685            {
2686                if ([item isKindOfClass: [Torrent class]])
2687                {
2688                    NSDictionary * group = [fTableView parentForItem: item];
2689                    index = [[group objectForKey: @"Torrents"] indexOfObject: item] + 1;
2690                    item = group;
2691                }
2692            }
2693            else
2694            {
2695                if ([item isKindOfClass: [Torrent class]])
2696                    item = [fTableView parentForItem: item];
2697                index = NSOutlineViewDropOnItemIndex;
2698            }
2699        }
2700        else
2701        {
2702            if (item)
2703            {
2704                index = [fTableView rowForItem: item] + 1;
2705                item = nil;
2706            }
2707        }
2708       
2709        [fTableView setDropItem: item dropChildIndex: index];
2710        return NSDragOperationGeneric;
2711    }
2712   
2713    return NSDragOperationNone;
2714}
2715
2716- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2717    childIndex: (NSInteger) newRow
2718{
2719    NSPasteboard * pasteboard = [info draggingPasteboard];
2720    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2721    {
2722        //remember selected rows
2723        NSArray * selectedValues = [fTableView selectedValues];
2724   
2725        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2726       
2727        //get the torrents to move
2728        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2729        int i;
2730        for (i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2731            [movingTorrents addObject: [fTableView itemAtRow: i]];
2732       
2733        //reset groups
2734        if (item)
2735        {
2736            //change groups
2737            int groupValue = [[item objectForKey: @"Group"] intValue];
2738            NSEnumerator * enumerator = [movingTorrents objectEnumerator];
2739            Torrent * torrent;
2740            while ((torrent = [enumerator nextObject]))
2741            {
2742                //have to reset objects here to avoid weird crash
2743                [[[fTableView parentForItem: torrent] objectForKey: @"Torrent"] removeObject: torrent];
2744                [[item objectForKey: @"Torrent"] addObject: torrent];
2745               
2746                [torrent setGroupValue: groupValue];
2747            }
2748            //part 2 of avoiding weird crash
2749            [fTableView reloadItem: nil reloadChildren: YES];
2750        }
2751       
2752        //reorder queue order
2753        if (newRow != NSOutlineViewDropOnItemIndex)
2754        {
2755            //find torrent to place under
2756            NSArray * groupTorrents = item ? [item objectForKey: @"Torrents"] : fDisplayedTorrents;
2757            Torrent * topTorrent = nil;
2758            for (i = newRow-1; i >= 0; i--)
2759            {
2760                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2761                if (![movingTorrents containsObject: tempTorrent])
2762                {
2763                    topTorrent = tempTorrent;
2764                    break;
2765                }
2766            }
2767           
2768            //remove objects to reinsert
2769            [fTorrents removeObjectsInArray: movingTorrents];
2770           
2771            //insert objects at new location
2772            int insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2773            for (i = 0; i < [movingTorrents count]; i++)
2774                [fTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2775           
2776            //redo order values
2777            for (i = 0; i < [fTorrents count]; i++)
2778                [[fTorrents objectAtIndex: i] setOrderValue: i];
2779        }
2780       
2781        [self applyFilter: nil];
2782       
2783        //set selected rows
2784        [fTableView selectValues: selectedValues];
2785        [self resetInfo]; //if group is already selected, but the torrents in it change
2786    }
2787   
2788    return YES;
2789}
2790
2791- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2792{
2793    [self resetInfo];
2794}
2795
2796- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2797{
2798    NSPasteboard * pasteboard = [info draggingPasteboard];
2799    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2800    {
2801        //check if any torrent files can be added
2802        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2803        NSEnumerator * enumerator = [files objectEnumerator];
2804        NSString * file;
2805        BOOL torrent = NO;
2806        tr_ctor * ctor;
2807        while ((file = [enumerator nextObject]))
2808        {
2809            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2810            {
2811                ctor = tr_ctorNew(fLib);
2812                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2813                switch (tr_torrentParse(fLib, ctor, NULL))
2814                {
2815                    case TR_OK:
2816                        if (!fOverlayWindow)
2817                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2818                        [fOverlayWindow setTorrents: files];
2819                       
2820                        return NSDragOperationCopy;
2821                   
2822                    case TR_EDUPLICATE:
2823                        torrent = YES;
2824                }
2825                tr_ctorFree(ctor);
2826            }
2827        }
2828       
2829        //create a torrent file if a single file
2830        if (!torrent && [files count] == 1)
2831        {
2832            if (!fOverlayWindow)
2833                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2834            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2835           
2836            return NSDragOperationCopy;
2837        }
2838    }
2839    else if ([[pasteboard types] containsObject: NSURLPboardType])
2840    {
2841        if (!fOverlayWindow)
2842            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2843        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2844       
2845        return NSDragOperationCopy;
2846    }
2847    else;
2848   
2849    return NSDragOperationNone;
2850}
2851
2852- (void) draggingExited: (id <NSDraggingInfo>) info
2853{
2854    if (fOverlayWindow)
2855        [fOverlayWindow fadeOut];
2856}
2857
2858- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2859{
2860    if (fOverlayWindow)
2861        [fOverlayWindow fadeOut];
2862   
2863    NSPasteboard * pasteboard = [info draggingPasteboard];
2864    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2865    {
2866        BOOL torrent = NO, accept = YES;
2867       
2868        //create an array of files that can be opened
2869        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2870        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2871        NSEnumerator * enumerator = [files objectEnumerator];
2872        NSString * file;
2873        tr_ctor * ctor;
2874        while ((file = [enumerator nextObject]))
2875        {
2876            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2877            {
2878                ctor = tr_ctorNew(fLib);
2879                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2880                switch (tr_torrentParse(fLib, ctor, NULL))
2881                {
2882                    case TR_OK:
2883                        [filesToOpen addObject: file];
2884                        torrent = YES;
2885                        break;
2886                       
2887                    case TR_EDUPLICATE:
2888                        torrent = YES;
2889                }
2890                tr_ctorFree(ctor);
2891            }
2892        }
2893       
2894        if ([filesToOpen count] > 0)
2895            [self application: NSApp openFiles: filesToOpen];
2896        else
2897        {
2898            if (!torrent && [files count] == 1)
2899                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2900            else
2901                accept = NO;
2902        }
2903        [filesToOpen release];
2904       
2905        return accept;
2906    }
2907    else if ([[pasteboard types] containsObject: NSURLPboardType])
2908    {
2909        NSURL * url;
2910        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2911        {
2912            [self openURL: url];
2913            return YES;
2914        }
2915    }
2916    else;
2917   
2918    return NO;
2919}
2920
2921- (void) toggleSmallView: (id) sender
2922{
2923    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2924    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2925   
2926    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2927   
2928    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2929   
2930    //window min height
2931    NSSize contentMinSize = [fWindow contentMinSize],
2932            contentSize = [[fWindow contentView] frame].size;
2933    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2934                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2935    [fWindow setContentMinSize: contentMinSize];
2936   
2937    //resize for larger min height if not set to auto size
2938    if (![fDefaults boolForKey: @"AutoSize"])
2939    {
2940        if (!makeSmall && contentSize.height < contentMinSize.height)
2941        {
2942            NSRect frame = [fWindow frame];
2943            float heightChange = contentMinSize.height - contentSize.height;
2944            frame.size.height += heightChange;
2945            frame.origin.y -= heightChange;
2946           
2947            [fWindow setFrame: frame display: YES];
2948        }
2949    }
2950    else
2951        [self setWindowSizeToFit];
2952}
2953
2954- (void) togglePiecesBar: (id) sender
2955{
2956    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2957    [fTableView togglePiecesBar];
2958}
2959
2960- (void) toggleAvailabilityBar: (id) sender
2961{
2962    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2963    [fTableView display];
2964}
2965
2966- (void) toggleStatusString: (id) sender
2967{
2968    if ([fDefaults boolForKey: @"SmallView"])
2969        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2970    else
2971        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2972   
2973    [fTableView reloadData];
2974}
2975
2976- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2977{
2978    NSScrollView * scrollView = [fTableView enclosingScrollView];
2979   
2980    //convert pixels to points
2981    NSRect windowFrame = [fWindow frame];
2982    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2983    windowSize.height += height;
2984   
2985    if (check)
2986    {
2987        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2988       
2989        if (windowSize.height < minSize.height)
2990            windowSize.height = minSize.height;
2991        else
2992        {
2993            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2994            if ([fStatusBar isHidden])
2995                maxSize.height -= [fStatusBar frame].size.height;
2996            if ([fFilterBar isHidden])
2997                maxSize.height -= [fFilterBar frame].size.height;
2998            if (windowSize.height > maxSize.height)
2999                windowSize.height = maxSize.height;
3000        }
3001    }
3002
3003    //convert points to pixels
3004    windowSize = [scrollView convertSize: windowSize toView: nil];
3005
3006    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
3007    windowFrame.size.height = windowSize.height;
3008    return windowFrame;
3009}
3010
3011- (void) toggleStatusBar: (id) sender
3012{
3013    [self showStatusBar: [fStatusBar isHidden] animate: YES];
3014    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
3015}
3016
3017//doesn't save shown state
3018- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
3019{
3020    if (show != [fStatusBar isHidden])
3021        return;
3022
3023    if (show)
3024        [fStatusBar setHidden: NO];
3025
3026    NSRect frame;
3027    float heightChange = [fStatusBar frame].size.height;
3028    if (!show)
3029        heightChange *= -1;
3030   
3031    //allow bar to show even if not enough room
3032    if (show && ![fDefaults boolForKey: @"AutoSize"])
3033    {
3034        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3035        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3036        if (change < 0.0)
3037        {
3038            frame = [fWindow frame];
3039            frame.size.height += change;
3040            frame.origin.y -= change;
3041            [fWindow setFrame: frame display: NO animate: NO];
3042        }
3043    }
3044
3045    [self updateUI];
3046   
3047    NSScrollView * scrollView = [fTableView enclosingScrollView];
3048   
3049    //set views to not autoresize
3050    unsigned int statsMask = [fStatusBar autoresizingMask];
3051    unsigned int filterMask = [fFilterBar autoresizingMask];
3052    unsigned int scrollMask = [scrollView autoresizingMask];
3053    [fStatusBar setAutoresizingMask: NSViewNotSizable];
3054    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3055    [scrollView setAutoresizingMask: NSViewNotSizable];
3056   
3057    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3058    [fWindow setFrame: frame display: YES animate: animate];
3059   
3060    //re-enable autoresize
3061    [fStatusBar setAutoresizingMask: statsMask];
3062    [fFilterBar setAutoresizingMask: filterMask];
3063    [scrollView setAutoresizingMask: scrollMask];
3064   
3065    //change min size
3066    NSSize minSize = [fWindow contentMinSize];
3067    minSize.height += heightChange;
3068    [fWindow setContentMinSize: minSize];
3069   
3070    if (!show)
3071        [fStatusBar setHidden: YES];
3072}
3073
3074- (void) toggleFilterBar: (id) sender
3075{
3076    //disable filtering when hiding
3077    if (![fFilterBar isHidden])
3078    {
3079        [fSearchFilterField setStringValue: @""];
3080        [self setFilter: fNoFilterButton];
3081        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3082    }
3083
3084    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3085    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3086}
3087
3088//doesn't save shown state
3089- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3090{
3091    if (show != [fFilterBar isHidden])
3092        return;
3093
3094    if (show)
3095        [fFilterBar setHidden: NO];
3096
3097    NSRect frame;
3098    float heightChange = [fFilterBar frame].size.height;
3099    if (!show)
3100        heightChange *= -1;
3101   
3102    //allow bar to show even if not enough room
3103    if (show && ![fDefaults boolForKey: @"AutoSize"])
3104    {
3105        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3106        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3107        if (change < 0.0)
3108        {
3109            frame = [fWindow frame];
3110            frame.size.height += change;
3111            frame.origin.y -= change;
3112            [fWindow setFrame: frame display: NO animate: NO];
3113        }
3114    }
3115   
3116    NSScrollView * scrollView = [fTableView enclosingScrollView];
3117
3118    //set views to not autoresize
3119    unsigned int filterMask = [fFilterBar autoresizingMask];
3120    unsigned int scrollMask = [scrollView autoresizingMask];
3121    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3122    [scrollView setAutoresizingMask: NSViewNotSizable];
3123   
3124    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3125    [fWindow setFrame: frame display: YES animate: animate];
3126   
3127    //re-enable autoresize
3128    [fFilterBar setAutoresizingMask: filterMask];
3129    [scrollView setAutoresizingMask: scrollMask];
3130   
3131    //change min size
3132    NSSize minSize = [fWindow contentMinSize];
3133    minSize.height += heightChange;
3134    [fWindow setContentMinSize: minSize];
3135   
3136    if (!show)
3137    {
3138        [fFilterBar setHidden: YES];
3139        [fWindow makeFirstResponder: fTableView];
3140    }
3141}
3142
3143- (void) focusFilterField
3144{
3145    [fWindow makeFirstResponder: fSearchFilterField];
3146    if ([fFilterBar isHidden])
3147        [self toggleFilterBar: self];
3148}
3149
3150- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3151{
3152    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3153   
3154    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3155    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3156    [button setStringValue: @""];
3157   
3158    [item setView: button];
3159    [button release];
3160   
3161    NSSize buttonSize = NSMakeSize(36.0, 25.0);
3162    [item setMinSize: buttonSize];
3163    [item setMaxSize: buttonSize];
3164   
3165    return [item autorelease];
3166}
3167
3168- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3169{
3170    if ([ident isEqualToString: TOOLBAR_CREATE])
3171    {
3172        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3173       
3174        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3175        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3176        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3177        [item setImage: [NSImage imageNamed: @"Create.png"]];
3178        [item setTarget: self];
3179        [item setAction: @selector(createFile:)];
3180        [item setAutovalidates: NO];
3181       
3182        return item;
3183    }
3184    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3185    {
3186        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3187       
3188        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3189        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3190        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3191        [item setImage: [NSImage imageNamed: @"Open.png"]];
3192        [item setTarget: self];
3193        [item setAction: @selector(openShowSheet:)];
3194        [item setAutovalidates: NO];
3195       
3196        return item;
3197    }
3198    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3199    {
3200        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3201       
3202        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3203        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3204        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3205        [item setImage: [NSImage imageNamed: @"OpenWeb.png"]];
3206        [item setTarget: self];
3207        [item setAction: @selector(openURLShowSheet:)];
3208        [item setAutovalidates: NO];
3209       
3210        return item;
3211    }
3212    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3213    {
3214        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3215       
3216        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3217        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3218        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3219        [item setImage: [NSImage imageNamed: @"Remove.png"]];
3220        [item setTarget: self];
3221        [item setAction: @selector(removeNoDelete:)];
3222       
3223        return item;
3224    }
3225    else if ([ident isEqualToString: TOOLBAR_INFO])
3226    {
3227        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3228       
3229        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3230        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3231        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3232        [item setImage: [NSImage imageNamed: @"Info.png"]];
3233        [item setTarget: self];
3234        [item setAction: @selector(showInfo:)];
3235       
3236        return item;
3237    }
3238    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3239    {
3240        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3241       
3242        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3243        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3244        [groupItem setView: segmentedControl];
3245        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3246       
3247        [segmentedControl setSegmentCount: 2];
3248        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3249       
3250        NSSize groupSize = NSMakeSize(72.0, 25.0);
3251        [groupItem setMinSize: groupSize];
3252        [groupItem setMaxSize: groupSize];
3253       
3254        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3255        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3256        [groupItem setTarget: self];
3257        [groupItem setAction: @selector(allToolbarClicked:)];
3258       
3259        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3260       
3261        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3262        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
3263        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3264                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3265       
3266        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3267        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
3268        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3269                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3270       
3271        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3272                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3273       
3274        [segmentedControl release];
3275        return [groupItem autorelease];
3276    }
3277    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3278    {
3279        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3280       
3281        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3282        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3283        [groupItem setView: segmentedControl];
3284        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3285       
3286        [segmentedControl setSegmentCount: 2];
3287        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3288       
3289        NSSize groupSize = NSMakeSize(72.0, 25.0);
3290        [groupItem setMinSize: groupSize];
3291        [groupItem setMaxSize: groupSize];
3292       
3293        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3294        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3295        [groupItem setTarget: self];
3296        [groupItem setAction: @selector(selectedToolbarClicked:)];
3297       
3298        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3299       
3300        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3301        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
3302        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3303                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3304       
3305        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3306        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
3307        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3308                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3309       
3310        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3311                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3312       
3313        [segmentedControl release];
3314        return [groupItem autorelease];
3315    }
3316    else if ([ident isEqualToString: TOOLBAR_FILTER])
3317    {
3318        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3319       
3320        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3321        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3322        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3323        [item setImage: [NSImage imageNamed: @"Filter.png"]];
3324        [item setTarget: self];
3325        [item setAction: @selector(toggleFilterBar:)];
3326       
3327        return item;
3328    }
3329    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3330    {
3331        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3332       
3333        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3334        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3335        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3336        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3337        [item setTarget: self];
3338        [item setAction: @selector(toggleQuickLook:)];
3339       
3340        return item;
3341    }
3342    else
3343        return nil;
3344}
3345
3346- (void) allToolbarClicked: (id) sender
3347{
3348    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3349                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3350    switch (tagValue)
3351    {
3352        case TOOLBAR_PAUSE_TAG:
3353            [self stopAllTorrents: sender];
3354            break;
3355        case TOOLBAR_RESUME_TAG:
3356            [self resumeAllTorrents: sender];
3357            break;
3358    }
3359}
3360
3361- (void) selectedToolbarClicked: (id) sender
3362{
3363    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3364                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3365    switch (tagValue)
3366    {
3367        case TOOLBAR_PAUSE_TAG:
3368            [self stopSelectedTorrents: sender];
3369            break;
3370        case TOOLBAR_RESUME_TAG:
3371            [self resumeSelectedTorrents: sender];
3372            break;
3373    }
3374}
3375
3376- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3377{
3378    NSMutableArray * idents = [NSMutableArray arrayWithObjects:
3379                                TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB,
3380                                TOOLBAR_REMOVE, TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3381                                TOOLBAR_FILTER, TOOLBAR_INFO,
3382                                NSToolbarSeparatorItemIdentifier,
3383                                NSToolbarSpaceItemIdentifier,
3384                                NSToolbarFlexibleSpaceItemIdentifier,
3385                                NSToolbarCustomizeToolbarItemIdentifier, nil];
3386   
3387    //allow quicklook on leopard
3388    if ([NSApp isOnLeopardOrBetter])
3389        [idents insertObject: TOOLBAR_QUICKLOOK atIndex: 6];
3390   
3391    return idents;
3392}
3393
3394- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3395{
3396    return [NSArray arrayWithObjects:
3397            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE,
3398            NSToolbarSeparatorItemIdentifier,
3399            TOOLBAR_PAUSE_RESUME_ALL,
3400            NSToolbarFlexibleSpaceItemIdentifier,
3401            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3402}
3403
3404- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3405{
3406    NSString * ident = [toolbarItem itemIdentifier];
3407   
3408    //enable remove item
3409    if ([ident isEqualToString: TOOLBAR_REMOVE])
3410        return [fTableView numberOfSelectedRows] > 0;
3411
3412    //enable pause all item
3413    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3414    {
3415        Torrent * torrent;
3416        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3417        while ((torrent = [enumerator nextObject]))
3418            if ([torrent isActive] || [torrent waitingToStart])
3419                return YES;
3420        return NO;
3421    }
3422
3423    //enable resume all item
3424    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3425    {
3426        Torrent * torrent;
3427        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3428        while ((torrent = [enumerator nextObject]))
3429            if (![torrent isActive] && ![torrent waitingToStart])
3430                return YES;
3431        return NO;
3432    }
3433
3434    //enable pause item
3435    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3436    {
3437        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3438        Torrent * torrent;
3439        while ((torrent = [enumerator nextObject]))
3440            if ([torrent isActive] || [torrent waitingToStart])
3441                return YES;
3442        return NO;
3443    }
3444   
3445    //enable resume item
3446    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3447    {
3448        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3449        Torrent * torrent;
3450        while ((torrent = [enumerator nextObject]))
3451            if (![torrent isActive] && ![torrent waitingToStart])
3452                return YES;
3453        return NO;
3454    }
3455   
3456    //set info image
3457    if ([ident isEqualToString: TOOLBAR_INFO])
3458    {
3459        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue.png"]
3460                                                                    : [NSImage imageNamed: @"Info.png"]];
3461        return YES;
3462    }
3463   
3464    //set filter image
3465    if ([ident isEqualToString: TOOLBAR_FILTER])
3466    {
3467        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue.png"] : [NSImage imageNamed: @"Filter.png"]];
3468        return YES;
3469    }
3470   
3471    //enable quicklook item
3472    if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3473        return [[QuickLookController quickLook] canQuickLook];
3474
3475    return YES;
3476}
3477
3478- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3479{
3480    SEL action = [menuItem action];
3481   
3482    if (action == @selector(toggleSpeedLimit:))
3483    {
3484        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3485        return YES;
3486    }
3487   
3488    //only enable some items if it is in a context menu or the window is useable
3489    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3490
3491    //enable open items
3492    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3493        return [fWindow attachedSheet] == nil;
3494   
3495    //enable sort options
3496    if (action == @selector(setSort:))
3497    {
3498        NSString * sortType;
3499        switch ([menuItem tag])
3500        {
3501            case SORT_ORDER_TAG:
3502                sortType = SORT_ORDER;
3503                break;
3504            case SORT_DATE_TAG:
3505                sortType = SORT_DATE;
3506                break;
3507            case SORT_NAME_TAG:
3508                sortType = SORT_NAME;
3509                break;
3510            case SORT_PROGRESS_TAG:
3511                sortType = SORT_PROGRESS;
3512                break;
3513            case SORT_STATE_TAG:
3514                sortType = SORT_STATE;
3515                break;
3516            case SORT_TRACKER_TAG:
3517                sortType = SORT_TRACKER;
3518                break;
3519            case SORT_ACTIVITY_TAG:
3520                sortType = SORT_ACTIVITY;
3521        }
3522       
3523        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3524        return [fWindow isVisible];
3525    }
3526   
3527    //enable sort options
3528    if (action == @selector(setStatusLabel:))
3529    {
3530        NSString * statusLabel;
3531        switch ([menuItem tag])
3532        {
3533            case STATUS_RATIO_TOTAL_TAG:
3534                statusLabel = STATUS_RATIO_TOTAL;
3535                break;
3536            case STATUS_RATIO_SESSION_TAG:
3537                statusLabel = STATUS_RATIO_SESSION;
3538                break;
3539            case STATUS_TRANSFER_TOTAL_TAG:
3540                statusLabel = STATUS_TRANSFER_TOTAL;
3541                break;
3542            case STATUS_TRANSFER_SESSION_TAG:
3543                statusLabel = STATUS_TRANSFER_SESSION;
3544        }
3545       
3546        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3547        return YES;
3548    }
3549   
3550    if (action == @selector(setGroup:))
3551    {
3552        BOOL checked = NO;
3553       
3554        int index = [menuItem tag];
3555        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3556        Torrent * torrent;
3557        while ((torrent = [enumerator nextObject]))
3558            if (index == [torrent groupValue])
3559            {
3560                checked = YES;
3561                break;
3562            }
3563       
3564        [menuItem setState: checked ? NSOnState : NSOffState];
3565        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3566    }
3567   
3568    if (action == @selector(setGroupFilter:))
3569    {
3570        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3571        return YES;
3572    }
3573   
3574    if (action == @selector(toggleSmallView:))
3575    {
3576        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3577        return [fWindow isVisible];
3578    }
3579   
3580    if (action == @selector(togglePiecesBar:))
3581    {
3582        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3583        return [fWindow isVisible];
3584    }
3585   
3586    if (action == @selector(toggleStatusString:))
3587    {
3588        if ([fDefaults boolForKey: @"SmallView"])
3589        {
3590            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3591            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3592        }
3593        else
3594        {
3595            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3596            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3597        }
3598       
3599        return [fWindow isVisible];
3600    }
3601   
3602    if (action == @selector(toggleAvailabilityBar:))
3603    {
3604        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3605        return [fWindow isVisible];
3606    }
3607   
3608    if (action == @selector(setLimitGlobalEnabled:))
3609    {
3610        BOOL upload = [menuItem menu] == fUploadMenu;
3611        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3612        if (limit)
3613            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3614                                    "Action menu -> upload/download limit"),
3615                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3616       
3617        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3618        return YES;
3619    }
3620   
3621    if (action == @selector(setRatioGlobalEnabled:))
3622    {
3623        BOOL check = menuItem == fCheckRatioItem;
3624        if (check)
3625            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3626                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3627       
3628        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3629        return YES;
3630    }
3631
3632    //enable show info
3633    if (action == @selector(showInfo:))
3634    {
3635        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3636                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3637        [menuItem setTitle: title];
3638
3639        return YES;
3640    }
3641   
3642    //enable prev/next inspector tab
3643    if (action == @selector(setInfoTab:))
3644        return [[fInfoController window] isVisible];
3645   
3646    //enable toggle status bar
3647    if (action == @selector(toggleStatusBar:))
3648    {
3649        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3650                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3651        [menuItem setTitle: title];
3652
3653        return [fWindow isVisible];
3654    }
3655   
3656    //enable toggle filter bar
3657    if (action == @selector(toggleFilterBar:))
3658    {
3659        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3660                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3661        [menuItem setTitle: title];
3662
3663        return [fWindow isVisible];
3664    }
3665   
3666    //enable prev/next filter button
3667    if (action == @selector(switchFilter:))
3668        return [fWindow isVisible] && ![fFilterBar isHidden];
3669   
3670    //enable quicklook item
3671    if (action == @selector(toggleQuickLook:))
3672        return [[QuickLookController quickLook] canQuickLook];
3673   
3674    //enable reveal in finder
3675    if (action == @selector(revealFile:))
3676        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3677
3678    //enable remove items
3679    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3680        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3681    {
3682        BOOL warning = NO,
3683            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3684            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3685       
3686        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3687        Torrent * torrent;
3688        while ((torrent = [enumerator nextObject]))
3689        {
3690            if (!warning && [torrent isActive])
3691            {
3692                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3693                if (warning && canDelete)
3694                    break;
3695            }
3696            if (!canDelete && [torrent publicTorrent])
3697            {
3698                canDelete = YES;
3699                if (warning)
3700                    break;
3701            }
3702        }
3703   
3704        //append or remove ellipsis when needed
3705        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3706        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3707        {
3708            if (![title hasSuffix: ellipsis])
3709                [menuItem setTitle: [title stringByAppendingEllipsis]];
3710        }
3711        else
3712        {
3713            if ([title hasSuffix: ellipsis])
3714                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3715        }
3716       
3717        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3718    }
3719
3720    //enable pause all item
3721    if (action == @selector(stopAllTorrents:))
3722    {
3723        Torrent * torrent;
3724        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3725        while ((torrent = [enumerator nextObject]))
3726            if ([torrent isActive] || [torrent waitingToStart])
3727                return YES;
3728        return NO;
3729    }
3730   
3731    //enable resume all item
3732    if (action == @selector(resumeAllTorrents:))
3733    {
3734        Torrent * torrent;
3735        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3736        while ((torrent = [enumerator nextObject]))
3737            if (![torrent isActive] && ![torrent waitingToStart])
3738                return YES;
3739        return NO;
3740    }
3741   
3742    //enable resume all waiting item
3743    if (action == @selector(resumeWaitingTorrents:))
3744    {
3745        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3746            return NO;
3747   
3748        Torrent * torrent;
3749        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3750        while ((torrent = [enumerator nextObject]))
3751            if (![torrent isActive] && [torrent waitingToStart])
3752                return YES;
3753        return NO;
3754    }
3755   
3756    //enable resume selected waiting item
3757    if (action == @selector(resumeSelectedTorrentsNoWait:))
3758    {
3759        if (!canUseTable)
3760            return NO;
3761       
3762        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3763        Torrent * torrent;
3764        while ((torrent = [enumerator nextObject]))
3765            if (![torrent isActive])
3766                return YES;
3767        return NO;
3768    }
3769
3770    //enable pause item
3771    if (action == @selector(stopSelectedTorrents:))
3772    {
3773        if (!canUseTable)
3774            return NO;
3775   
3776        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3777        Torrent * torrent;
3778        while ((torrent = [enumerator nextObject]))
3779            if ([torrent isActive] || [torrent waitingToStart])
3780                return YES;
3781        return NO;
3782    }
3783   
3784    //enable resume item
3785    if (action == @selector(resumeSelectedTorrents:))
3786    {
3787        if (!canUseTable)
3788            return NO;
3789   
3790        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3791        Torrent * torrent;
3792        while ((torrent = [enumerator nextObject]))
3793            if (![torrent isActive] && ![torrent waitingToStart])
3794                return YES;
3795        return NO;
3796    }
3797   
3798    //enable manual announce item
3799    if (action == @selector(announceSelectedTorrents:))
3800    {
3801        if (!canUseTable)
3802            return NO;
3803       
3804        NSEnumerator * enumerator = [[fTableView selectedTorrents] objectEnumerator];
3805        Torrent * torrent;
3806        while ((torrent = [enumerator nextObject]))
3807            if ([torrent canManualAnnounce])
3808                return YES;
3809        return NO;
3810    }
3811   
3812    //enable reset cache item
3813    if (action == @selector(verifySelectedTorrents:))
3814        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3815   
3816    //enable move torrent file item
3817    if (action == @selector(moveDataFilesSelected:))
3818        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3819   
3820    //enable copy torrent file item
3821    if (action == @selector(copyTorrentFiles:))
3822        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3823   
3824    //enable reverse sort item
3825    if (action == @selector(setSortReverse:))
3826    {
3827        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3828        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3829    }
3830   
3831    //enable group sort item
3832    if (action == @selector(setSortByGroup:))
3833    {
3834        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3835        return YES;
3836    }
3837   
3838    //check proper filter search item
3839    if (action == @selector(setFilterSearchType:))
3840    {
3841        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3842       
3843        BOOL state;
3844        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3845            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3846        else
3847            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3848       
3849        [menuItem setState: state ? NSOnState : NSOffState];
3850        return YES;
3851    }
3852   
3853    return YES;
3854}
3855
3856- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3857{
3858    NSEnumerator * enumerator;
3859    Torrent * torrent;
3860
3861    switch (messageType)
3862    {
3863        case kIOMessageSystemWillSleep:
3864            //if there are any running transfers, wait 15 seconds for them to stop
3865            enumerator = [fTorrents objectEnumerator];
3866            while ((torrent = [enumerator nextObject]))
3867                if ([torrent isActive])
3868                {
3869                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3870                    [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3871                    sleep(15);
3872                    break;
3873                }
3874
3875            IOAllowPowerChange(fRootPort, (long) messageArgument);
3876            break;
3877
3878        case kIOMessageCanSystemSleep:
3879            if ([fDefaults boolForKey: @"SleepPrevent"])
3880            {
3881                //prevent idle sleep unless no torrents are active
3882                enumerator = [fTorrents objectEnumerator];
3883                while ((torrent = [enumerator nextObject]))
3884                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3885                    {
3886                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3887                        return;
3888                    }
3889            }
3890           
3891            IOAllowPowerChange(fRootPort, (long) messageArgument);
3892            break;
3893
3894        case kIOMessageSystemHasPoweredOn:
3895            //resume sleeping transfers after we wake up
3896            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3897            [self autoSpeedLimitChange: nil];
3898            break;
3899    }
3900}
3901
3902- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3903{
3904    int seeding = 0, downloading = 0;
3905    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3906    Torrent * torrent;
3907    while ((torrent = [enumerator nextObject]))
3908    {
3909        if ([torrent isSeeding])
3910            seeding++;
3911        else if ([torrent isActive])
3912            downloading++;
3913        else;
3914    }
3915   
3916    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3917            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3918   
3919    BOOL hasSeparator = seedingItem || downloadingItem;
3920   
3921    if (seeding > 0)
3922    {
3923        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3924        if (!seedingItem)
3925        {
3926            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3927            [seedingItem setTag: DOCK_SEEDING_TAG];
3928            [fDockMenu insertItem: seedingItem atIndex: 0];
3929        }
3930        else
3931            [seedingItem setTitle: title];
3932    }
3933    else
3934    {
3935        if (seedingItem)
3936            [fDockMenu removeItem: seedingItem];
3937    }
3938   
3939    if (downloading > 0)
3940    {
3941        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3942        if (!downloadingItem)
3943        {
3944            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3945            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3946            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3947        }
3948        else
3949            [downloadingItem setTitle: title];
3950    }
3951    else
3952    {
3953        if (downloadingItem)
3954            [fDockMenu removeItem: downloadingItem];
3955    }
3956   
3957    if (seeding > 0 || downloading > 0)
3958    {
3959        if (!hasSeparator)
3960            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3961    }
3962    else
3963    {
3964        if (hasSeparator)
3965            [fDockMenu removeItemAtIndex: 0];
3966    }
3967   
3968    return fDockMenu;
3969}
3970
3971- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3972{
3973    //if auto size is enabled, the current frame shouldn't need to change
3974    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3975   
3976    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3977    return frame;
3978}
3979
3980- (void) setWindowSizeToFit
3981{
3982    if ([fDefaults boolForKey: @"AutoSize"])
3983    {
3984        NSScrollView * scrollView = [fTableView enclosingScrollView];
3985       
3986        [scrollView setHasVerticalScroller: NO];
3987        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3988        [scrollView setHasVerticalScroller: YES];
3989    }
3990}
3991
3992- (NSRect) sizedWindowFrame
3993{
3994    int groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3995                    ? [fDisplayedTorrents count] : 0;
3996   
3997    float heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3998                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3999                        - [[fTableView enclosingScrollView] frame].size.height;
4000   
4001    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
4002}
4003
4004- (void) updateForExpandCollape
4005{
4006    [self setWindowSizeToFit];
4007    [self setBottomCountText: YES];
4008}
4009
4010- (void) showMainWindow: (id) sender
4011{
4012    [fWindow makeKeyAndOrderFront: nil];
4013}
4014
4015- (void) windowDidBecomeMain: (NSNotification *) notification
4016{
4017    [fBadger clearCompleted];
4018    [self updateUI];
4019}
4020
4021- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
4022{
4023    //only resize horizontally if autosize is enabled
4024    if ([fDefaults boolForKey: @"AutoSize"])
4025        proposedFrameSize.height = [fWindow frame].size.height;
4026    return proposedFrameSize;
4027}
4028
4029- (void) windowDidResize: (NSNotification *) notification
4030{
4031    if (![fStatusBar isHidden])
4032        [self resizeStatusButton];
4033   
4034    if ([fFilterBar isHidden])
4035        return;
4036   
4037    //replace all buttons
4038    [fActiveFilterButton sizeToFit];
4039    [fDownloadFilterButton sizeToFit];
4040    [fSeedFilterButton sizeToFit];
4041    [fPauseFilterButton sizeToFit];
4042   
4043    NSRect activeRect = [fActiveFilterButton frame];
4044   
4045    NSRect downloadRect = [fDownloadFilterButton frame];
4046    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
4047   
4048    NSRect seedRect = [fSeedFilterButton frame];
4049    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4050   
4051    NSRect pauseRect = [fPauseFilterButton frame];
4052    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4053   
4054    //size search filter to not overlap buttons
4055    NSRect searchFrame = [fSearchFilterField frame];
4056    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
4057    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
4058   
4059    //make sure it is not too long
4060    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
4061    {
4062        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
4063        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
4064    }
4065    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
4066    {
4067        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
4068        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
4069       
4070        //resize the buttons so they don't overlay
4071        int difference = (NSMaxX(pauseRect) + 5.0) - searchFrame.origin.x - 1; //subtract 1, since 0 will be counted
4072       
4073        //decrease downloading by 8, seeding by 1, paused by 1, active by 1, repeat
4074        int download = (difference / 11 * 8) + MIN(difference % 11 + 1, 8); //8 for every 11
4075        int seed = (difference / 11) + (difference % 11 >= 8 ? 1 : 0);
4076        int paused = (difference / 11) + (difference % 11 >= 9 ? 1 : 0);
4077        int active = (difference / 11) + (difference % 11 >= 10 ? 1 : 0);
4078       
4079        activeRect.size.width -= active;
4080       
4081        downloadRect.origin.x -= active;
4082        downloadRect.size.width -= download;
4083       
4084        seedRect.origin.x -= active + download;
4085        seedRect.size.width -= seed;
4086       
4087        pauseRect.origin.x -= active + download + seed;
4088        pauseRect.size.width -= paused;
4089    }
4090    else;
4091   
4092    [fActiveFilterButton setFrame: activeRect];
4093    [fDownloadFilterButton setFrame: downloadRect];
4094    [fSeedFilterButton setFrame: seedRect];
4095    [fPauseFilterButton setFrame: pauseRect];
4096   
4097    [fSearchFilterField setFrame: searchFrame];
4098}
4099
4100- (void) applicationWillUnhide: (NSNotification *) notification
4101{
4102    [self updateUI];
4103}
4104
4105- (NSArray *) quickLookURLs
4106{
4107    NSArray * selectedTorrents = [fTableView selectedTorrents];
4108    NSMutableArray * urlArray = [NSMutableArray arrayWithCapacity: [selectedTorrents count]];
4109    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4110    Torrent * torrent;
4111   
4112    while ((torrent = [enumerator nextObject]))
4113        if ([self canQuickLookTorrent: torrent])
4114            [urlArray addObject: [NSURL fileURLWithPath: [torrent dataLocation]]];
4115   
4116    return urlArray;
4117}
4118
4119- (BOOL) canQuickLook
4120{
4121    NSArray * selectedTorrents = [fTableView selectedTorrents];
4122    NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
4123    Torrent * torrent;
4124   
4125    while ((torrent = [enumerator nextObject]))
4126        if ([self canQuickLookTorrent: torrent])
4127            return YES;
4128   
4129    return NO;
4130}
4131
4132- (BOOL) canQuickLookTorrent: (Torrent *) torrent
4133{
4134    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent dataLocation]])
4135        return NO;
4136   
4137    return [torrent isFolder] || [torrent isComplete];
4138}
4139
4140- (NSRect) quickLookFrameWithURL: (NSURL *) url
4141{
4142    if ([fWindow isVisible])
4143    {
4144        NSString * fullPath = [url path];
4145        NSRange visibleRows = [fTableView rowsInRect: [fTableView bounds]];
4146       
4147        int row;
4148        for (row = 0; row < NSMaxRange(visibleRows); row++)
4149        {
4150            id item = [fTableView itemAtRow: row];
4151            if ([item isKindOfClass: [Torrent class]] && [[(Torrent *)item dataLocation] isEqualToString: fullPath])
4152            {
4153                NSRect frame = [fTableView iconRectForRow: row];
4154                frame.origin = [fTableView convertPoint: frame.origin toView: nil];
4155                frame.origin = [fWindow convertBaseToScreen: frame.origin];
4156                frame.origin.y -= frame.size.height;
4157                return frame;
4158            }
4159        }
4160    }
4161   
4162    return NSZeroRect;
4163}
4164
4165- (void) toggleQuickLook: (id) sender
4166{
4167    [[QuickLookController quickLook] toggleQuickLook];
4168}
4169
4170- (void) linkHomepage: (id) sender
4171{
4172    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4173}
4174
4175- (void) linkForums: (id) sender
4176{
4177    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4178}
4179
4180- (void) linkDonate: (id) sender
4181{
4182    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4183}
4184
4185- (void) prepareForUpdate: (NSNotification *) notification
4186{
4187    fUpdateInProgress = YES;
4188}
4189
4190- (NSDictionary *) registrationDictionaryForGrowl
4191{
4192    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4193                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4194    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4195                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4196}
4197
4198- (void) growlNotificationWasClicked: (id) clickContext
4199{
4200    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4201        return;
4202   
4203    NSString * type = [clickContext objectForKey: @"Type"], * location;
4204    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4205            && (location = [clickContext objectForKey: @"Location"]))
4206        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4207}
4208
4209- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4210{
4211    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4212   
4213    //get the torrent
4214    Torrent * torrent = nil;
4215    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4216    {
4217        NSEnumerator * enumerator = [fTorrents objectEnumerator];
4218        while ((torrent = [enumerator nextObject]))
4219            if (torrentStruct == [torrent torrentStruct])
4220                break;
4221       
4222        if (!torrent)
4223        {
4224            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4225            return;
4226        }
4227       
4228        [torrent retain];
4229    }
4230   
4231    switch (type)
4232    {
4233        case TR_RPC_TORRENT_ADDED:
4234            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4235                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4236            break;
4237       
4238        case TR_RPC_TORRENT_STARTED:
4239        case TR_RPC_TORRENT_STOPPED:
4240            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4241            break;
4242       
4243        case TR_RPC_TORRENT_REMOVING:
4244            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4245            break;
4246       
4247        case TR_RPC_TORRENT_CHANGED:
4248            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4249            break;
4250       
4251        case TR_RPC_SESSION_CHANGED:
4252            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4253            break;
4254       
4255        default:
4256            NSLog(@"Unknown RPC command received!");
4257            [torrent release];
4258    }
4259   
4260    [pool release];
4261}
4262
4263- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4264{
4265    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4266    [torrentStructPtr release];
4267   
4268    NSString * location = nil;
4269    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4270        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4271   
4272    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4273   
4274    [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
4275   
4276    [torrent update];
4277    [fTorrents addObject: torrent];
4278    [torrent release];
4279   
4280    [self updateTorrentsInQueue];
4281}
4282
4283- (void) rpcRemoveTorrent: (Torrent *) torrent
4284{
4285    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO deleteTorrent: NO fromRPC: YES];
4286    [torrent release];
4287}
4288
4289- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4290{
4291    [torrent update];
4292    [torrent release];
4293   
4294    [self updateUI];
4295    [self applyFilter: nil];
4296    [self updateTorrentHistory];
4297}
4298
4299- (void) rpcChangedTorrent: (Torrent *) torrent
4300{
4301    [torrent update];
4302   
4303    if ([[fTableView selectedTorrents] containsObject: torrent])
4304    {
4305        [fInfoController updateInfoStats]; //this will reload the file table
4306        [fInfoController updateOptions];
4307    }
4308   
4309    [torrent release];
4310}
4311
4312@end
Note: See TracBrowser for help on using the repository browser.