source: trunk/macosx/Controller.m @ 4230

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

streamline the filtering code

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