source: trunk/macosx/Controller.m @ 5751

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

fix a crash when sorting by tracker order; update NEWS

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