source: trunk/macosx/Controller.m @ 4275

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

get rid of all the deprecated functions for the ctor versions

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