source: trunk/macosx/Controller.m @ 4253

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

remove bindings from the global ratio menu items

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