source: trunk/macosx/Controller.m @ 5824

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

allow changing groups by dragging (regardless of sort)

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