source: trunk/macosx/Controller.m @ 4252

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

update the news

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