source: trunk/macosx/Controller.m @ 4231

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

a little more streamlining

  • Property svn:keywords set to Date Rev Author Id
File size: 139.5 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 4231 2007-12-20 01:06:55Z livings124 $
3 *
4 * Copyright (c) 2005-2007 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import <IOKit/IOMessage.h>
26
27#import "Controller.h"
28#import "Torrent.h"
29#import "TorrentCell.h"
30#import "TorrentTableView.h"
31#import "CreatorWindowController.h"
32#import "StatsWindowController.h"
33#import "GroupsWindowController.h"
34#import "AboutWindowController.h"
35#import "ButtonToolbarItem.h"
36#import "GroupToolbarItem.h"
37#import "ToolbarSegmentedCell.h"
38#import "NSApplicationAdditions.h"
39#import "NSStringAdditions.h"
40#import "NSMenuAdditions.h"
41#import "UKKQueue.h"
42#import "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 = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1825    if ([filterType isEqualToString: FILTER_DOWNLOAD])
1826        filterDownload = YES;
1827    else if ([filterType isEqualToString: FILTER_SEED])
1828        filterSeed = YES;
1829    else if ([filterType isEqualToString: FILTER_PAUSE])
1830        filterPause = YES;
1831    else
1832        filterStatus = NO;
1833   
1834    int groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
1835    BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
1836   
1837    NSString * searchString = [fSearchFilterField stringValue];
1838    BOOL filterText = [searchString length] > 0,
1839        filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
1840   
1841    NSMutableIndexSet * indexes = [NSMutableIndexSet indexSet];
1842   
1843    //get count of each type
1844    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1845    Torrent * torrent;
1846    int i = -1;
1847    while ((torrent = [enumerator nextObject]))
1848    {
1849        i++;
1850       
1851        //check status
1852        if ([torrent isActive])
1853        {
1854            if ([torrent isSeeding])
1855            {
1856                seeding++;
1857                if (filterStatus && !filterSeed)
1858                    continue;
1859            }
1860            else
1861            {
1862                downloading++;
1863                if (filterStatus && !filterDownload)
1864                    continue;
1865            }
1866        }
1867        else
1868        {
1869            paused++;
1870            if (filterStatus && !filterPause)
1871                continue;
1872        }
1873       
1874        //checkGroup
1875        if (filterGroup)
1876            if ([torrent groupValue] != groupFilterValue)
1877                continue;
1878       
1879        //check text field
1880        if (filterText)
1881        {
1882            BOOL removeTextField = YES;
1883            if (filterTracker)
1884            {
1885                NSEnumerator * trackerEnumerator = [[torrent allTrackers] objectEnumerator], * subTrackerEnumerator;
1886                NSArray * subTrackers;
1887                NSString * tracker;
1888                while (removeTextField && (subTrackers = [trackerEnumerator nextObject]))
1889                {
1890                    subTrackerEnumerator = [subTrackers objectEnumerator];
1891                    while ((tracker = [subTrackerEnumerator nextObject]))
1892                        if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1893                        {
1894                            removeTextField = NO;
1895                            break;
1896                        }
1897                }
1898               
1899                if (removeTextField)
1900                    continue;
1901            }
1902            else
1903            {
1904                if ([[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound)
1905                    continue;
1906            }
1907        }
1908       
1909        [indexes addIndex: i];
1910    }
1911   
1912    [fDisplayedTorrents setArray: [fTorrents objectsAtIndexes: indexes]];
1913   
1914    //set button tooltips
1915    [fNoFilterButton setCount: [fTorrents count]];
1916    [fDownloadFilterButton setCount: downloading];
1917    [fSeedFilterButton setCount: seeding];
1918    [fPauseFilterButton setCount: paused];
1919   
1920    [self sortTorrentsIgnoreSelected];
1921   
1922    //set selected rows if needed
1923    if (selectedTorrents)
1924    {
1925        Torrent * torrent;
1926        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1927        NSMutableIndexSet * selectedIndexes = [NSMutableIndexSet indexSet];
1928        unsigned index;
1929        while ((torrent = [enumerator nextObject]))
1930            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1931                [selectedIndexes addIndex: index];
1932       
1933        [fTableView selectRowIndexes: selectedIndexes byExtendingSelection: NO];
1934    }
1935   
1936    //set status bar torrent count text
1937    NSString * totalTorrentsString;
1938    int totalCount = [fTorrents count];
1939    if (totalCount != 1)
1940        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1941    else
1942        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1943   
1944    if (filterStatus || filterGroup || filterText)
1945        totalTorrentsString = [NSString stringWithFormat: @"%d of %@", [fDisplayedTorrents count], totalTorrentsString];
1946   
1947    [fTotalTorrentsField setStringValue: totalTorrentsString];
1948
1949    [self setWindowSizeToFit];
1950}
1951
1952//resets filter and sorts torrents
1953- (void) setFilter: (id) sender
1954{
1955    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
1956   
1957    NSButton * prevFilterButton;
1958    if ([oldFilterType isEqualToString: FILTER_PAUSE])
1959        prevFilterButton = fPauseFilterButton;
1960    else if ([oldFilterType isEqualToString: FILTER_SEED])
1961        prevFilterButton = fSeedFilterButton;
1962    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
1963        prevFilterButton = fDownloadFilterButton;
1964    else
1965        prevFilterButton = fNoFilterButton;
1966   
1967    if (sender != prevFilterButton)
1968    {
1969        [prevFilterButton setState: NSOffState];
1970        [sender setState: NSOnState];
1971
1972        NSString * filterType;
1973        if (sender == fDownloadFilterButton)
1974            filterType = FILTER_DOWNLOAD;
1975        else if (sender == fPauseFilterButton)
1976            filterType = FILTER_PAUSE;
1977        else if (sender == fSeedFilterButton)
1978            filterType = FILTER_SEED;
1979        else
1980            filterType = FILTER_NONE;
1981
1982        [fDefaults setObject: filterType forKey: @"Filter"];
1983    }
1984    else
1985        [sender setState: NSOnState];
1986
1987    [self applyFilter: nil];
1988}
1989
1990- (void) setFilterSearchType: (id) sender
1991{
1992    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
1993   
1994    int prevTag, currentTag = [sender tag];
1995    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
1996        prevTag = FILTER_TYPE_TAG_TRACKER;
1997    else
1998        prevTag = FILTER_TYPE_TAG_NAME;
1999   
2000    if (currentTag != prevTag)
2001    {
2002        NSString * filterType;
2003        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2004            filterType = FILTER_TYPE_TRACKER;
2005        else
2006            filterType = FILTER_TYPE_NAME;
2007       
2008        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2009       
2010        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2011    }
2012   
2013    [self applyFilter: nil];
2014}
2015
2016- (void) switchFilter: (id) sender
2017{
2018    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2019   
2020    NSButton * button;
2021    if ([filterType isEqualToString: FILTER_NONE])
2022        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
2023    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2024        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
2025    else if ([filterType isEqualToString: FILTER_SEED])
2026        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2027    else if ([filterType isEqualToString: FILTER_PAUSE])
2028        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2029    else
2030        button = fNoFilterButton;
2031   
2032    [self setFilter: button];
2033}
2034
2035- (void) setStatusLabel: (id) sender
2036{
2037    NSString * statusLabel;
2038    switch ([sender tag])
2039    {
2040        case STATUS_RATIO_TOTAL_TAG:
2041            statusLabel = STATUS_RATIO_TOTAL;
2042            break;
2043        case STATUS_RATIO_SESSION_TAG:
2044            statusLabel = STATUS_RATIO_SESSION;
2045            break;
2046        case STATUS_TRANSFER_TOTAL_TAG:
2047            statusLabel = STATUS_TRANSFER_TOTAL;
2048            break;
2049        case STATUS_TRANSFER_SESSION_TAG:
2050            statusLabel = STATUS_TRANSFER_SESSION;
2051            break;
2052        default:
2053            return;
2054    }
2055   
2056    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2057    [self updateUI];
2058}
2059
2060- (void) showGroups: (id) sender
2061{
2062    [[GroupsWindowController groupsController] showWindow: self];
2063}
2064
2065- (void) menuNeedsUpdate: (NSMenu *) menu
2066{
2067    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu)
2068    {
2069        int i, keep = (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu) ? 2 : 0;
2070        for (i = [menu numberOfItems]-1 - keep; i >= 0; i--)
2071            [menu removeItemAtIndex: i];
2072       
2073        NSMenu * groupMenu = [[GroupsWindowController groupsController] groupMenuWithTarget: self action: @selector(setGroup:)
2074                                isSmall: NO];
2075        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2076                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: NO];
2077    }
2078    else if (menu == fGroupFilterMenu)
2079    {
2080        int i;
2081        for (i = [menu numberOfItems]-1; i >= 3; i--)
2082            [menu removeItemAtIndex: i];
2083       
2084        NSMenu * groupMenu = [[GroupsWindowController groupsController] groupMenuWithTarget: self action: @selector(setGroupFilter:)
2085                                isSmall: YES];
2086        [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange:
2087                NSMakeRange(0, [groupMenu numberOfItems])] atBottom: YES];
2088    }
2089    else;
2090}
2091
2092- (void) setGroup: (id) sender
2093{
2094    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2095    Torrent * torrent;
2096    while ((torrent = [enumerator nextObject]))
2097        [torrent setGroupValue: [sender tag]];
2098   
2099    [self updateUI];
2100    [self applyFilter: nil];
2101    [self updateTorrentHistory];
2102}
2103
2104- (void) setGroupFilter: (id) sender
2105{
2106    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2107    [self updateGroupsFilterButton];
2108    [self applyFilter: nil];
2109}
2110
2111- (void) updateGroupsFilterButton
2112{
2113    int index = [fDefaults integerForKey: @"FilterGroup"];
2114   
2115    NSImage * icon = nil;
2116    if (index >= 0)
2117        icon = [[GroupsWindowController groupsController] imageForIndex: index isSmall: YES];
2118    else
2119    {
2120        if ([NSApp isOnLeopardOrBetter])
2121            icon = [NSImage imageNamed: NSImageNameRemoveTemplate];
2122    }
2123    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2124   
2125    NSString * toolTip;
2126    switch (index)
2127    {
2128        case GROUP_FILTER_ALL_TAG:
2129            toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2130            break;
2131        case -1:
2132            toolTip = NSLocalizedString(@"Group: No Label", "Groups -> Button");
2133            break;
2134        default:
2135            toolTip = [NSLocalizedString(@"Group: ", "Groups -> Button") stringByAppendingString:
2136                        [[GroupsWindowController groupsController] nameForIndex: index]];
2137    }
2138    [fGroupsButton setToolTip: toolTip];
2139}
2140
2141- (void) updateGroupsFilters: (NSNotification *) notification
2142{
2143    [self updateGroupsFilterButton];
2144    [self applyFilter: nil];
2145}
2146
2147- (void) toggleSpeedLimit: (id) sender
2148{
2149    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2150    [fPrefsController applySpeedSettings: nil];
2151}
2152
2153- (void) autoSpeedLimitChange: (NSNotification *) notification
2154{
2155    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2156        return;
2157 
2158    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2159                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
2160        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2161                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
2162        * nowDate = [NSCalendarDate calendarDate];
2163   
2164    //check if should be on if within range
2165    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
2166        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
2167        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
2168   
2169    BOOL shouldBeOn = NO;
2170    if (onTime < offTime)
2171        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2172    else if (onTime > offTime)
2173        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2174    else;
2175   
2176    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2177        [self toggleSpeedLimit: nil];
2178}
2179
2180- (void) autoSpeedLimit
2181{
2182    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2183        return;
2184   
2185    //only toggle if within first few seconds of minutes
2186    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
2187    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
2188        return;
2189   
2190    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2191                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
2192   
2193    BOOL toggle;
2194    if ([fDefaults boolForKey: @"SpeedLimit"])
2195        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
2196    else
2197    {
2198        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2199                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
2200        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
2201                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
2202    }
2203   
2204    if (toggle)
2205    {
2206        [self toggleSpeedLimit: nil];
2207       
2208        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2209                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2210                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2211            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2212            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2213    }
2214}
2215
2216- (void) setLimitGlobalEnabled: (id) sender
2217{
2218    [fPrefsController applySpeedSettings: nil];
2219}
2220
2221- (void) setQuickLimitGlobal: (id) sender
2222{
2223    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
2224    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
2225   
2226    [fPrefsController updateLimitFields];
2227    [fPrefsController applySpeedSettings: nil];
2228}
2229
2230- (void) setQuickRatioGlobal: (id) sender
2231{
2232    [fDefaults setBool: YES forKey: @"RatioCheck"];
2233    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
2234   
2235    [fPrefsController updateRatioStopField];
2236}
2237
2238- (void) torrentStoppedForRatio: (NSNotification *) notification
2239{
2240    Torrent * torrent = [notification object];
2241   
2242    [self updateTorrentsInQueue];
2243    [fInfoController updateInfoStats];
2244    [fInfoController updateOptions];
2245   
2246    if ([fDefaults boolForKey: @"PlaySeedingSound"])
2247    {
2248        NSSound * sound;
2249        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
2250            [sound play];
2251    }
2252   
2253    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
2254                                    [torrent dataLocation], @"Location", nil];
2255    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
2256                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2257                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2258}
2259
2260-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2261{
2262    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2263    {
2264        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2265            return;
2266       
2267        if (fAutoImportTimer)
2268        {
2269            if ([fAutoImportTimer isValid])
2270                [fAutoImportTimer invalidate];
2271            [fAutoImportTimer release];
2272            fAutoImportTimer = nil;
2273        }
2274       
2275        //check again in 10 seconds in case torrent file wasn't complete
2276        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2277            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2278       
2279        [self checkAutoImportDirectory];
2280    }
2281}
2282
2283- (void) changeAutoImport
2284{
2285    if (fAutoImportTimer)
2286    {
2287        if ([fAutoImportTimer isValid])
2288            [fAutoImportTimer invalidate];
2289        [fAutoImportTimer release];
2290        fAutoImportTimer = nil;
2291    }
2292   
2293    if (fAutoImportedNames)
2294        [fAutoImportedNames removeAllObjects];
2295    [self checkAutoImportDirectory];
2296}
2297
2298- (void) checkAutoImportDirectory
2299{
2300    NSString * path;
2301    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2302        return;
2303   
2304    path = [path stringByExpandingTildeInPath];
2305   
2306    NSArray * importedNames;
2307    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2308        return;
2309   
2310    //only check files that have not been checked yet
2311    NSMutableArray * newNames = [importedNames mutableCopy];
2312   
2313    if (fAutoImportedNames)
2314        [newNames removeObjectsInArray: fAutoImportedNames];
2315    else
2316        fAutoImportedNames = [[NSMutableArray alloc] init];
2317    [fAutoImportedNames setArray: importedNames];
2318   
2319    NSString * file;
2320    int i;
2321    for (i = [newNames count] - 1; i >= 0; i--)
2322    {
2323        file = [newNames objectAtIndex: i];
2324        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2325            [newNames removeObjectAtIndex: i];
2326        else
2327            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2328    }
2329   
2330    BOOL ask = [[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"];
2331   
2332    NSEnumerator * enumerator = [newNames objectEnumerator];
2333    int canAdd, count;
2334    while ((file = [enumerator nextObject]))
2335    {
2336        canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL);
2337        if (canAdd == TR_OK)
2338        {
2339            if (!ask)
2340                count = [fTorrents count];
2341            [self openFiles: [NSArray arrayWithObject: file]];
2342           
2343            //check if torrent was opened
2344            if (!ask && [fTorrents count] > count)
2345                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
2346                    "Growl notification title") description: [file lastPathComponent]
2347                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
2348        }
2349        else if (canAdd == TR_EINVALID)
2350            [fAutoImportedNames removeObject: [file lastPathComponent]];
2351        else;
2352    }
2353   
2354    [newNames release];
2355}
2356
2357- (void) beginCreateFile: (NSNotification *) notification
2358{
2359    if (![fDefaults boolForKey: @"AutoImport"])
2360        return;
2361   
2362    NSString * location = [notification object],
2363            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2364   
2365    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2366                                    isEqualToString: [path stringByExpandingTildeInPath]])
2367        [fAutoImportedNames addObject: [location lastPathComponent]];
2368}
2369
2370- (int) numberOfRowsInTableView: (NSTableView *) tableview
2371{
2372    return [fDisplayedTorrents count];
2373}
2374
2375- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
2376{
2377    return nil;
2378}
2379
2380- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes toPasteboard: (NSPasteboard *) pasteboard
2381{
2382    //only allow reordering of rows if sorting by order
2383    if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2384    {
2385        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2386        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2387        return YES;
2388    }
2389    return NO;
2390}
2391
2392- (NSDragOperation) tableView: (NSTableView *) tableView validateDrop: (id <NSDraggingInfo>) info
2393    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
2394{
2395    NSPasteboard * pasteboard = [info draggingPasteboard];
2396    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2397    {
2398        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
2399        return NSDragOperationGeneric;
2400    }
2401   
2402    return NSDragOperationNone;
2403}
2404
2405- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
2406    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
2407{
2408    NSPasteboard * pasteboard = [info draggingPasteboard];
2409    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2410    {
2411        //remember selected rows if needed
2412        NSArray * selectedTorrents = nil;
2413        int numSelected = [fTableView numberOfSelectedRows];
2414        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
2415            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
2416   
2417        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
2418                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2419       
2420        //determine where to move them
2421        int i;
2422        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2423            newRow--;
2424       
2425        //reinsert into array
2426        int insertIndex = newRow > 0 ? [[fDisplayedTorrents objectAtIndex: newRow-1] orderValue] + 1 : 0;
2427       
2428        //get all torrents to reorder
2429        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
2430                                                @"orderValue" ascending: YES] autorelease];
2431        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
2432       
2433        NSMutableArray * sortedTorrents = [[fTorrents sortedArrayUsingDescriptors: descriptors] mutableCopy];
2434        [descriptors release];
2435       
2436        //remove objects to reinsert
2437        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
2438        [sortedTorrents removeObjectsInArray: movingTorrents];
2439       
2440        //insert objects at new location
2441        for (i = 0; i < [movingTorrents count]; i++)
2442            [sortedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2443       
2444        [movingTorrents release];
2445       
2446        //redo order values
2447        i = 0;
2448        for (i = 0; i < [sortedTorrents count]; i++)
2449            [[sortedTorrents objectAtIndex: i] setOrderValue: i];
2450       
2451        [sortedTorrents release];
2452       
2453        [self applyFilter: nil];
2454       
2455        //set selected rows if needed
2456        if (selectedTorrents)
2457        {
2458            Torrent * torrent;
2459            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
2460            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
2461            while ((torrent = [enumerator nextObject]))
2462                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
2463           
2464            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
2465            [indexSet release];
2466        }
2467    }
2468   
2469    return YES;
2470}
2471
2472- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2473{
2474    [fInfoController setInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
2475}
2476
2477- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2478{
2479    NSPasteboard * pasteboard = [info draggingPasteboard];
2480    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2481    {
2482        //check if any torrent files can be added
2483        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2484        NSEnumerator * enumerator = [files objectEnumerator];
2485        NSString * file;
2486        BOOL torrent = NO;
2487        int canAdd;
2488        while ((file = [enumerator nextObject]))
2489        {
2490            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2491            {
2492                switch (canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2493                {
2494                    case TR_OK:
2495                        if (!fOverlayWindow)
2496                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2497                        [fOverlayWindow setTorrents: files];
2498                       
2499                        return NSDragOperationCopy;
2500                   
2501                    case TR_EDUPLICATE:
2502                        torrent = YES;
2503                }
2504            }
2505        }
2506       
2507        //create a torrent file if a single file
2508        if (!torrent && [files count] == 1)
2509        {
2510            if (!fOverlayWindow)
2511                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2512            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2513           
2514            return NSDragOperationCopy;
2515        }
2516    }
2517    else if ([[pasteboard types] containsObject: NSURLPboardType])
2518    {
2519        if (!fOverlayWindow)
2520            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2521        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2522       
2523        return NSDragOperationCopy;
2524    }
2525    else;
2526   
2527    return NSDragOperationNone;
2528}
2529
2530- (void) draggingExited: (id <NSDraggingInfo>) info
2531{
2532    if (fOverlayWindow)
2533        [fOverlayWindow fadeOut];
2534}
2535
2536- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2537{
2538    if (fOverlayWindow)
2539        [fOverlayWindow fadeOut];
2540   
2541    NSPasteboard * pasteboard = [info draggingPasteboard];
2542    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2543    {
2544        BOOL torrent = NO, accept = YES;
2545       
2546        //create an array of files that can be opened
2547        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2548        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2549        NSEnumerator * enumerator = [files objectEnumerator];
2550        NSString * file;
2551        while ((file = [enumerator nextObject]))
2552        {
2553            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2554            {
2555                switch(tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2556                {
2557                    case TR_OK:
2558                        [filesToOpen addObject: file];
2559                        torrent = YES;
2560                        break;
2561                       
2562                    case TR_EDUPLICATE:
2563                        torrent = YES;
2564                }
2565            }
2566        }
2567       
2568        if ([filesToOpen count] > 0)
2569            [self application: NSApp openFiles: filesToOpen];
2570        else
2571        {
2572            if (!torrent && [files count] == 1)
2573                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2574            else
2575                accept = NO;
2576        }
2577        [filesToOpen release];
2578       
2579        return accept;
2580    }
2581    else if ([[pasteboard types] containsObject: NSURLPboardType])
2582    {
2583        NSURL * url;
2584        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2585        {
2586            [self openURL: url];
2587            return YES;
2588        }
2589    }
2590    else;
2591   
2592    return NO;
2593}
2594
2595- (void) toggleSmallView: (id) sender
2596{
2597    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2598    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2599   
2600    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2601   
2602    //window min height
2603    NSSize contentMinSize = [fWindow contentMinSize],
2604            contentSize = [[fWindow contentView] frame].size;
2605    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
2606                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2607    [fWindow setContentMinSize: contentMinSize];
2608   
2609    //resize for larger min height if not set to auto size
2610    if (![fDefaults boolForKey: @"AutoSize"])
2611    {
2612        if (!makeSmall && contentSize.height < contentMinSize.height)
2613        {
2614            NSRect frame = [fWindow frame];
2615            float heightChange = contentMinSize.height - contentSize.height;
2616            frame.size.height += heightChange;
2617            frame.origin.y -= heightChange;
2618           
2619            [fWindow setFrame: frame display: YES];
2620            [fTableView reloadData];
2621        }
2622    }
2623    else
2624        [self setWindowSizeToFit];
2625}
2626
2627- (void) togglePiecesBar: (id) sender
2628{
2629    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2630    [fTableView display];
2631}
2632
2633- (void) toggleAvailabilityBar: (id) sender
2634{
2635    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2636    [fTableView display];
2637}
2638
2639- (void) toggleStatusBar: (id) sender
2640{
2641    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2642    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2643}
2644
2645- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2646{
2647    //convert pixels to points
2648    NSRect windowFrame = [fWindow frame];
2649    NSSize windowSize = [fScrollView convertSize: windowFrame.size fromView: nil];
2650    windowSize.height += height;
2651   
2652    if (check)
2653    {
2654        NSSize minSize = [fScrollView convertSize: [fWindow minSize] fromView: nil];
2655       
2656        if (windowSize.height < minSize.height)
2657            windowSize.height = minSize.height;
2658        else
2659        {
2660            NSSize maxSize = [fScrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2661            if ([fStatusBar isHidden])
2662                maxSize.height -= [fStatusBar frame].size.height;
2663            if ([fFilterBar isHidden])
2664                maxSize.height -= [fFilterBar frame].size.height;
2665            if (windowSize.height > maxSize.height)
2666                windowSize.height = maxSize.height;
2667        }
2668    }
2669
2670    //convert points to pixels
2671    windowSize = [fScrollView convertSize: windowSize toView: nil];
2672
2673    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2674    windowFrame.size.height = windowSize.height;
2675    return windowFrame;
2676}
2677
2678- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2679{
2680    if (show != [fStatusBar isHidden])
2681        return;
2682
2683    if (show)
2684        [fStatusBar setHidden: NO];
2685
2686    NSRect frame;
2687    float heightChange = [fStatusBar frame].size.height;
2688    if (!show)
2689        heightChange *= -1;
2690   
2691    //allow bar to show even if not enough room
2692    if (show && ![fDefaults boolForKey: @"AutoSize"])
2693    {
2694        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2695        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2696        if (change < 0.0)
2697        {
2698            frame = [fWindow frame];
2699            frame.size.height += change;
2700            frame.origin.y -= change;
2701            [fWindow setFrame: frame display: NO animate: NO];
2702        }
2703    }
2704
2705    [self updateUI];
2706   
2707    //set views to not autoresize
2708    unsigned int statsMask = [fStatusBar autoresizingMask];
2709    unsigned int filterMask = [fFilterBar autoresizingMask];
2710    unsigned int scrollMask = [fScrollView autoresizingMask];
2711    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2712    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2713    [fScrollView setAutoresizingMask: NSViewNotSizable];
2714   
2715    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2716    [fWindow setFrame: frame display: YES animate: animate];
2717   
2718    //re-enable autoresize
2719    [fStatusBar setAutoresizingMask: statsMask];
2720    [fFilterBar setAutoresizingMask: filterMask];
2721    [fScrollView setAutoresizingMask: scrollMask];
2722   
2723    //change min size
2724    NSSize minSize = [fWindow contentMinSize];
2725    minSize.height += heightChange;
2726    [fWindow setContentMinSize: minSize];
2727   
2728    if (!show)
2729        [fStatusBar setHidden: YES];
2730}
2731
2732- (void) toggleFilterBar: (id) sender
2733{
2734    //disable filtering when hiding
2735    if (![fFilterBar isHidden])
2736    {
2737        [fSearchFilterField setStringValue: @""];
2738        [self setFilter: fNoFilterButton];
2739        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
2740    }
2741
2742    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2743    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2744}
2745
2746- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2747{
2748    if (show != [fFilterBar isHidden])
2749        return;
2750
2751    if (show)
2752        [fFilterBar setHidden: NO];
2753
2754    NSRect frame;
2755    float heightChange = [fFilterBar frame].size.height;
2756    if (!show)
2757        heightChange *= -1;
2758   
2759    //allow bar to show even if not enough room
2760    if (show && ![fDefaults boolForKey: @"AutoSize"])
2761    {
2762        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2763        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2764        if (change < 0.0)
2765        {
2766            frame = [fWindow frame];
2767            frame.size.height += change;
2768            frame.origin.y -= change;
2769            [fWindow setFrame: frame display: NO animate: NO];
2770        }
2771    }
2772
2773    //set views to not autoresize
2774    unsigned int filterMask = [fFilterBar autoresizingMask];
2775    unsigned int scrollMask = [fScrollView autoresizingMask];
2776    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2777    [fScrollView setAutoresizingMask: NSViewNotSizable];
2778   
2779    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2780    [fWindow setFrame: frame display: YES animate: animate];
2781   
2782    //re-enable autoresize
2783    [fFilterBar setAutoresizingMask: filterMask];
2784    [fScrollView setAutoresizingMask: scrollMask];
2785   
2786    //change min size
2787    NSSize minSize = [fWindow contentMinSize];
2788    minSize.height += heightChange;
2789    [fWindow setContentMinSize: minSize];
2790   
2791    if (!show)
2792    {
2793        [fFilterBar setHidden: YES];
2794        [fWindow makeFirstResponder: fTableView];
2795    }
2796}
2797
2798- (void) doNothing: (id) sender {}
2799
2800- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
2801{
2802    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
2803   
2804    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
2805    [button setBezelStyle: NSTexturedRoundedBezelStyle];
2806    [button setStringValue: @""];
2807   
2808    [item setView: button];
2809    [button release];
2810   
2811    NSSize buttonSize = NSMakeSize(36.0, 25.0);
2812    [item setMinSize: buttonSize];
2813    [item setMaxSize: buttonSize];
2814   
2815    return [item autorelease];
2816}
2817
2818- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2819{
2820    if ([ident isEqualToString: TOOLBAR_CREATE])
2821    {
2822        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2823       
2824        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
2825        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
2826        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
2827        [item setImage: [NSImage imageNamed: @"Create.png"]];
2828        [item setTarget: self];
2829        [item setAction: @selector(createFile:)];
2830        [item setAutovalidates: NO];
2831       
2832        return item;
2833    }
2834    else if ([ident isEqualToString: TOOLBAR_OPEN])
2835    {
2836        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2837       
2838        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
2839        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
2840        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
2841        [item setImage: [NSImage imageNamed: @"Open.png"]];
2842        [item setTarget: self];
2843        [item setAction: @selector(openShowSheet:)];
2844        [item setAutovalidates: NO];
2845       
2846        return item;
2847    }
2848    else if ([ident isEqualToString: TOOLBAR_REMOVE])
2849    {
2850        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2851       
2852        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
2853        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
2854        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
2855        [item setImage: [NSImage imageNamed: @"Remove.png"]];
2856        [item setTarget: self];
2857        [item setAction: @selector(removeNoDelete:)];
2858       
2859        return item;
2860    }
2861    else if ([ident isEqualToString: TOOLBAR_INFO])
2862    {
2863        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2864       
2865        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
2866        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
2867        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
2868        [item setImage: [NSImage imageNamed: @"Info.png"]];
2869        [item setTarget: self];
2870        [item setAction: @selector(showInfo:)];
2871       
2872        return item;
2873    }
2874    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
2875    {
2876        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
2877       
2878        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
2879        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
2880        [groupItem setView: segmentedControl];
2881        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
2882       
2883        [segmentedControl setSegmentCount: 2];
2884        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
2885       
2886        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
2887        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
2888        [groupItem setTarget: self];
2889        [groupItem setAction: @selector(allToolbarClicked:)];
2890       
2891        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
2892       
2893        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
2894        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
2895        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
2896                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
2897       
2898        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
2899        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
2900        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
2901                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
2902       
2903        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
2904                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
2905       
2906        NSSize groupSize = NSMakeSize(72.0, 25.0);
2907        [groupItem setMinSize: groupSize];
2908        [groupItem setMaxSize: groupSize];
2909       
2910        [segmentedControl release];
2911        return [groupItem autorelease];
2912    }
2913    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
2914    {
2915        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
2916       
2917        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
2918        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
2919        [groupItem setView: segmentedControl];
2920        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
2921       
2922        [segmentedControl setSegmentCount: 2];
2923        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
2924       
2925        NSSize groupSize = NSMakeSize(72.0, 25.0);
2926        [groupItem setMinSize: groupSize];
2927        [groupItem setMaxSize: groupSize];
2928       
2929        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
2930        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
2931        [groupItem setTarget: self];
2932        [groupItem setAction: @selector(selectedToolbarClicked:)];
2933       
2934        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
2935       
2936        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
2937        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
2938        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
2939                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
2940       
2941        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
2942        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
2943        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
2944                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
2945       
2946        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
2947                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
2948       
2949        [segmentedControl release];
2950        return [groupItem autorelease];
2951    }
2952    else if ([ident isEqualToString: TOOLBAR_FILTER])
2953    {
2954        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2955       
2956        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
2957        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
2958        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
2959        [item setImage: [NSImage imageNamed: @"Filter.png"]];
2960        [item setTarget: self];
2961        [item setAction: @selector(toggleFilterBar:)];
2962       
2963        return item;
2964    }
2965    else
2966        return nil;
2967}
2968
2969- (void) allToolbarClicked: (id) sender
2970{
2971    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
2972                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
2973    switch (tagValue)
2974    {
2975        case TOOLBAR_PAUSE_TAG:
2976            [self stopAllTorrents: sender];
2977            break;
2978        case TOOLBAR_RESUME_TAG:
2979            [self resumeAllTorrents: sender];
2980            break;
2981    }
2982}
2983
2984- (void) selectedToolbarClicked: (id) sender
2985{
2986    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
2987                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
2988    switch (tagValue)
2989    {
2990        case TOOLBAR_PAUSE_TAG:
2991            [self stopSelectedTorrents: sender];
2992            break;
2993        case TOOLBAR_RESUME_TAG:
2994            [self resumeSelectedTorrents: sender];
2995            break;
2996    }
2997}
2998
2999- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3000{
3001    return [NSArray arrayWithObjects:
3002            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
3003            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3004            TOOLBAR_FILTER, TOOLBAR_INFO,
3005            NSToolbarSeparatorItemIdentifier,
3006            NSToolbarSpaceItemIdentifier,
3007            NSToolbarFlexibleSpaceItemIdentifier,
3008            NSToolbarCustomizeToolbarItemIdentifier, nil];
3009}
3010
3011- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3012{
3013    return [NSArray arrayWithObjects:
3014            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
3015            NSToolbarSeparatorItemIdentifier,
3016            TOOLBAR_PAUSE_RESUME_ALL,
3017            NSToolbarFlexibleSpaceItemIdentifier,
3018            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3019}
3020
3021- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3022{
3023    NSString * ident = [toolbarItem itemIdentifier];
3024   
3025    //enable remove item
3026    if ([ident isEqualToString: TOOLBAR_REMOVE])
3027        return [fTableView numberOfSelectedRows] > 0;
3028
3029    //enable pause all item
3030    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3031    {
3032        Torrent * torrent;
3033        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3034        while ((torrent = [enumerator nextObject]))
3035            if ([torrent isActive] || [torrent waitingToStart])
3036                return YES;
3037        return NO;
3038    }
3039
3040    //enable resume all item
3041    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3042    {
3043        Torrent * torrent;
3044        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3045        while ((torrent = [enumerator nextObject]))
3046            if (![torrent isActive] && ![torrent waitingToStart])
3047                return YES;
3048        return NO;
3049    }
3050
3051    //enable pause item
3052    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3053    {
3054        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3055        Torrent * torrent;
3056        while ((torrent = [enumerator nextObject]))
3057            if ([torrent isActive] || [torrent waitingToStart])
3058                return YES;
3059        return NO;
3060    }
3061   
3062    //enable resume item
3063    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3064    {
3065        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3066        Torrent * torrent;
3067        while ((torrent = [enumerator nextObject]))
3068            if (![torrent isActive] && ![torrent waitingToStart])
3069                return YES;
3070        return NO;
3071    }
3072   
3073    //set info image
3074    if ([ident isEqualToString: TOOLBAR_INFO])
3075    {
3076        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue"]
3077                                                                    : [NSImage imageNamed: @"Info"]];
3078        return YES;
3079    }
3080   
3081    //set filter image
3082    if ([ident isEqualToString: TOOLBAR_FILTER])
3083    {
3084        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue"] : [NSImage imageNamed: @"Filter"]];
3085        return YES;
3086    }
3087
3088    return YES;
3089}
3090
3091- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3092{
3093    SEL action = [menuItem action];
3094   
3095    if (action == @selector(toggleSpeedLimit:))
3096    {
3097        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3098        return YES;
3099    }
3100   
3101    //only enable some items if it is in a context menu or the window is useable
3102    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3103
3104    //enable open items
3105    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3106        return [fWindow attachedSheet] == nil;
3107   
3108    //enable sort options
3109    if (action == @selector(setSort:))
3110    {
3111        NSString * sortType;
3112        switch ([menuItem tag])
3113        {
3114            case SORT_ORDER_TAG:
3115                sortType = SORT_ORDER;
3116                break;
3117            case SORT_DATE_TAG:
3118                sortType = SORT_DATE;
3119                break;
3120            case SORT_NAME_TAG:
3121                sortType = SORT_NAME;
3122                break;
3123            case SORT_PROGRESS_TAG:
3124                sortType = SORT_PROGRESS;
3125                break;
3126            case SORT_STATE_TAG:
3127                sortType = SORT_STATE;
3128                break;
3129            case SORT_TRACKER_TAG:
3130                sortType = SORT_TRACKER;
3131                break;
3132            case SORT_ACTIVITY_TAG:
3133                sortType = SORT_ACTIVITY;
3134                break;
3135            default:
3136                sortType = @"";
3137        }
3138       
3139        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3140        return [fWindow isVisible];
3141    }
3142   
3143    //enable sort options
3144    if (action == @selector(setStatusLabel:))
3145    {
3146        NSString * statusLabel;
3147        switch ([menuItem tag])
3148        {
3149            case STATUS_RATIO_TOTAL_TAG:
3150                statusLabel = STATUS_RATIO_TOTAL;
3151                break;
3152            case STATUS_RATIO_SESSION_TAG:
3153                statusLabel = STATUS_RATIO_SESSION;
3154                break;
3155            case STATUS_TRANSFER_TOTAL_TAG:
3156                statusLabel = STATUS_TRANSFER_TOTAL;
3157                break;
3158            case STATUS_TRANSFER_SESSION_TAG:
3159                statusLabel = STATUS_TRANSFER_SESSION;
3160                break;
3161            default:
3162                statusLabel = @"";;
3163        }
3164       
3165        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3166        return YES;
3167    }
3168   
3169    if (action == @selector(setGroup:))
3170    {
3171        BOOL checked = NO;
3172       
3173        int index = [menuItem tag];
3174        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3175        Torrent * torrent;
3176        while ((torrent = [enumerator nextObject]))
3177            if (index == [torrent groupValue])
3178            {
3179                checked = YES;
3180                break;
3181            }
3182       
3183        [menuItem setState: checked ? NSOnState : NSOffState];
3184        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3185    }
3186   
3187    if (action == @selector(setGroupFilter:))
3188    {
3189        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3190        return YES;
3191    }
3192   
3193    if (action == @selector(toggleSmallView:))
3194    {
3195        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3196        return [fWindow isVisible];
3197    }
3198   
3199    if (action == @selector(togglePiecesBar:))
3200    {
3201        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3202        return [fWindow isVisible];
3203    }
3204   
3205    if (action == @selector(toggleAvailabilityBar:))
3206    {
3207        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3208        return [fWindow isVisible];
3209    }
3210
3211    //enable show info
3212    if (action == @selector(showInfo:))
3213    {
3214        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3215                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3216        [menuItem setTitle: title];
3217
3218        return YES;
3219    }
3220   
3221    //enable prev/next inspector tab
3222    if (action == @selector(setInfoTab:))
3223        return [[fInfoController window] isVisible];
3224   
3225    //enable toggle status bar
3226    if (action == @selector(toggleStatusBar:))
3227    {
3228        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3229                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3230        [menuItem setTitle: title];
3231
3232        return [fWindow isVisible];
3233    }
3234   
3235    //enable toggle filter bar
3236    if (action == @selector(toggleFilterBar:))
3237    {
3238        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3239                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3240        [menuItem setTitle: title];
3241
3242        return [fWindow isVisible];
3243    }
3244   
3245    //enable prev/next filter button
3246    if (action == @selector(switchFilter:))
3247        return [fWindow isVisible] && ![fFilterBar isHidden];
3248
3249    //enable reveal in finder
3250    if (action == @selector(revealFile:))
3251        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3252
3253    //enable remove items
3254    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3255        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3256    {
3257        BOOL warning = NO,
3258            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3259            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3260       
3261        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3262        Torrent * torrent;
3263        while ((torrent = [enumerator nextObject]))
3264        {
3265            if (!warning && [torrent isActive])
3266            {
3267                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3268                if (warning && canDelete)
3269                    break;
3270            }
3271            if (!canDelete && [torrent publicTorrent])
3272            {
3273                canDelete = YES;
3274                if (warning)
3275                    break;
3276            }
3277        }
3278   
3279        //append or remove ellipsis when needed
3280        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3281        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3282        {
3283            if (![title hasSuffix: ellipsis])
3284                [menuItem setTitle: [title stringByAppendingEllipsis]];
3285        }
3286        else
3287        {
3288            if ([title hasSuffix: ellipsis])
3289                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3290        }
3291       
3292        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3293    }
3294
3295    //enable pause all item
3296    if (action == @selector(stopAllTorrents:))
3297    {
3298        Torrent * torrent;
3299        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3300        while ((torrent = [enumerator nextObject]))
3301            if ([torrent isActive] || [torrent waitingToStart])
3302                return YES;
3303        return NO;
3304    }
3305   
3306    //enable resume all item
3307    if (action == @selector(resumeAllTorrents:))
3308    {
3309        Torrent * torrent;
3310        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3311        while ((torrent = [enumerator nextObject]))
3312            if (![torrent isActive] && ![torrent waitingToStart])
3313                return YES;
3314        return NO;
3315    }
3316   
3317    //enable resume all waiting item
3318    if (action == @selector(resumeWaitingTorrents:))
3319    {
3320        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3321            return NO;
3322   
3323        Torrent * torrent;
3324        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3325        while ((torrent = [enumerator nextObject]))
3326            if (![torrent isActive] && [torrent waitingToStart])
3327                return YES;
3328        return NO;
3329    }
3330   
3331    //enable resume selected waiting item
3332    if (action == @selector(resumeSelectedTorrentsNoWait:))
3333    {
3334        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3335            return NO;
3336   
3337        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3338        Torrent * torrent;
3339        while ((torrent = [enumerator nextObject]))
3340            if (![torrent isActive])
3341                return YES;
3342        return NO;
3343    }
3344
3345    //enable pause item
3346    if (action == @selector(stopSelectedTorrents:))
3347    {
3348        if (!canUseTable)
3349            return NO;
3350   
3351        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3352        Torrent * torrent;
3353        while ((torrent = [enumerator nextObject]))
3354            if ([torrent isActive] || [torrent waitingToStart])
3355                return YES;
3356        return NO;
3357    }
3358   
3359    //enable resume item
3360    if (action == @selector(resumeSelectedTorrents:))
3361    {
3362        if (!canUseTable)
3363            return NO;
3364   
3365        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3366        Torrent * torrent;
3367        while ((torrent = [enumerator nextObject]))
3368            if (![torrent isActive] && ![torrent waitingToStart])
3369                return YES;
3370        return NO;
3371    }
3372   
3373    //enable manual announce item
3374    if (action == @selector(announceSelectedTorrents:))
3375    {
3376        if (!canUseTable)
3377            return NO;
3378       
3379        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3380        Torrent * torrent;
3381        while ((torrent = [enumerator nextObject]))
3382            if ([torrent canManualAnnounce])
3383                return YES;
3384        return NO;
3385    }
3386   
3387    //enable reset cache item
3388    if (action == @selector(resetCacheForSelectedTorrents:))
3389        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3390   
3391    //enable move torrent file item
3392    if (action == @selector(moveDataFiles:))
3393        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3394   
3395    //enable copy torrent file item
3396    if (action == @selector(copyTorrentFiles:))
3397        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3398   
3399    //enable reverse sort item
3400    if (action == @selector(setSortReverse:))
3401    {
3402        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3403        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3404    }
3405   
3406    //enable group sort item
3407    if (action == @selector(setSortByGroup:))
3408    {
3409        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3410        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3411    }
3412   
3413    //check proper filter search item
3414    if (action == @selector(setFilterSearchType:))
3415    {
3416        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3417       
3418        BOOL state;
3419        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3420            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3421        else
3422            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3423       
3424        [menuItem setState: state ? NSOnState : NSOffState];
3425        return YES;
3426    }
3427   
3428    return YES;
3429}
3430
3431- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
3432{
3433    NSEnumerator * enumerator;
3434    Torrent * torrent;
3435    BOOL allowSleep;
3436
3437    switch (messageType)
3438    {
3439        case kIOMessageSystemWillSleep:
3440            //close all connections before going to sleep and remember we should resume when we wake up
3441            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3442
3443            //wait for running transfers to stop (5 second timeout)
3444            NSDate * start = [NSDate date];
3445            BOOL timeUp = NO;
3446           
3447            enumerator = [fTorrents objectEnumerator];
3448            while (!timeUp && (torrent = [enumerator nextObject]))
3449                while ([torrent isActive] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
3450                {
3451                    usleep(100000);
3452                    [torrent update];
3453                }
3454
3455            IOAllowPowerChange(fRootPort, (long) messageArgument);
3456            break;
3457
3458        case kIOMessageCanSystemSleep:
3459            allowSleep = YES;
3460            if ([fDefaults boolForKey: @"SleepPrevent"])
3461            {
3462                //prevent idle sleep unless no torrents are active
3463                enumerator = [fTorrents objectEnumerator];
3464                while ((torrent = [enumerator nextObject]))
3465                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3466                    {
3467                        allowSleep = NO;
3468                        break;
3469                    }
3470            }
3471
3472            if (allowSleep)
3473                IOAllowPowerChange(fRootPort, (long) messageArgument);
3474            else
3475                IOCancelPowerChange(fRootPort, (long) messageArgument);
3476            break;
3477
3478        case kIOMessageSystemHasPoweredOn:
3479            //resume sleeping transfers after we wake up
3480            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3481            [self autoSpeedLimitChange: nil];
3482            break;
3483    }
3484}
3485
3486- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3487{
3488    int seeding = 0, downloading = 0;
3489    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3490    Torrent * torrent;
3491    while ((torrent = [enumerator nextObject]))
3492    {
3493        if ([torrent isSeeding])
3494            seeding++;
3495        else if ([torrent isActive])
3496            downloading++;
3497        else;
3498    }
3499   
3500    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3501            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3502   
3503    BOOL hasSeparator = seedingItem || downloadingItem;
3504   
3505    if (seeding > 0)
3506    {
3507        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding",
3508                                                        "Dock item - Seeding"), seeding];
3509        if (!seedingItem)
3510        {
3511            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3512            [seedingItem setTag: DOCK_SEEDING_TAG];
3513            [fDockMenu insertItem: seedingItem atIndex: 0];
3514        }
3515        else
3516            [seedingItem setTitle: title];
3517    }
3518    else
3519    {
3520        if (seedingItem)
3521            [fDockMenu removeItem: seedingItem];
3522    }
3523   
3524    if (downloading > 0)
3525    {
3526        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading",
3527                                                        "Dock item - Downloading"), downloading];
3528        if (!downloadingItem)
3529        {
3530            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3531            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3532            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3533        }
3534        else
3535            [downloadingItem setTitle: title];
3536    }
3537    else
3538    {
3539        if (downloadingItem)
3540            [fDockMenu removeItem: downloadingItem];
3541    }
3542   
3543    if (seeding > 0 || downloading > 0)
3544    {
3545        if (!hasSeparator)
3546            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3547    }
3548    else
3549    {
3550        if (hasSeparator)
3551            [fDockMenu removeItemAtIndex: 0];
3552    }
3553   
3554    return fDockMenu;
3555}
3556
3557- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3558{
3559    //if auto size is enabled, the current frame shouldn't need to change
3560    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3561   
3562    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3563    return frame;
3564}
3565
3566- (void) setWindowSizeToFit
3567{
3568    if ([fDefaults boolForKey: @"AutoSize"])
3569    {
3570        [fScrollView setHasVerticalScroller: NO];
3571        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3572        [fScrollView setHasVerticalScroller: YES];
3573    }
3574}
3575
3576- (NSRect) sizedWindowFrame
3577{
3578    float heightChange = [fDisplayedTorrents count] * ([fTableView rowHeight] +
3579            [fTableView intercellSpacing].height) - [fScrollView frame].size.height;
3580    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3581}
3582
3583- (void) showMainWindow: (id) sender
3584{
3585    [fWindow makeKeyAndOrderFront: nil];
3586}
3587
3588- (void) windowDidBecomeMain: (NSNotification *) notification
3589{
3590    [fBadger clearCompleted];
3591    [self updateUI];
3592}
3593
3594- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3595{
3596    //only resize horizontally if autosize is enabled
3597    if ([fDefaults boolForKey: @"AutoSize"])
3598        proposedFrameSize.height = [fWindow frame].size.height;
3599    return proposedFrameSize;
3600}
3601
3602- (void) windowDidResize: (NSNotification *) notification
3603{
3604    //size search filter to not overlap buttons
3605    float pointX = NSMaxX([fPauseFilterButton frame]) + 5.0;
3606    NSRect oldFrame = [fSearchFilterField frame],
3607            frame = NSMakeRect(pointX, oldFrame.origin.y, NSMaxX(oldFrame) - pointX, oldFrame.size.height);
3608   
3609    BOOL show = frame.size.width >= SEARCH_FILTER_MIN_WIDTH;
3610    if (show)
3611    {
3612        //make sure it is not too long
3613        if (frame.size.width > SEARCH_FILTER_MAX_WIDTH)
3614        {
3615            float different = frame.size.width - SEARCH_FILTER_MAX_WIDTH;
3616            frame.origin.x += different;
3617            frame.size.width -= different;
3618        }
3619        [fSearchFilterField setFrame: frame];
3620    }
3621   
3622    //hide search filter if it overlaps filter buttons
3623    [fSearchFilterField setHidden: !show];
3624}
3625
3626- (void) applicationWillUnhide: (NSNotification *) notification
3627{
3628    [self updateUI];
3629}
3630
3631- (void) linkHomepage: (id) sender
3632{
3633    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
3634}
3635
3636- (void) linkForums: (id) sender
3637{
3638    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
3639}
3640
3641- (void) linkDonate: (id) sender
3642{
3643    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
3644}
3645
3646- (void) prepareForUpdate: (NSNotification *) notification
3647{
3648    fUpdateInProgress = YES;
3649}
3650
3651- (NSDictionary *) registrationDictionaryForGrowl
3652{
3653    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
3654                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
3655    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
3656                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
3657}
3658
3659- (void) growlNotificationWasClicked: (id) clickContext
3660{
3661    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
3662        return;
3663   
3664    NSString * type = [clickContext objectForKey: @"Type"], * location;
3665    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
3666            && (location = [clickContext objectForKey: @"Location"]))
3667        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
3668}
3669
3670- (void) ipcQuit
3671{
3672    fRemoteQuit = YES;
3673    [NSApp terminate: self];
3674}
3675
3676- (NSArray *) ipcGetTorrentsByID: (NSArray *) idlist
3677{
3678    if (!idlist)
3679        return fTorrents;
3680   
3681    NSMutableArray * torrents = [NSMutableArray array];
3682   
3683    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * idEnum;
3684    int torId;
3685    Torrent * torrent;
3686    NSNumber * tempId;
3687    while ((torrent = [torrentEnum nextObject]))
3688    {
3689        torId = [torrent torrentID];
3690       
3691        idEnum = [idlist objectEnumerator];
3692        while ((tempId = [idEnum nextObject]))
3693        {
3694            if ([tempId intValue] == torId)
3695            {
3696                [torrents addObject: torrent];
3697                break;
3698            }
3699        }
3700    }
3701
3702    return torrents;
3703}
3704
3705- (NSArray *) ipcGetTorrentsByHash: (NSArray *) hashlist
3706{
3707    if (!hashlist)
3708        return fTorrents;
3709   
3710    NSMutableArray * torrents = [NSMutableArray array];
3711   
3712    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * hashEnum;
3713    NSString * torHash, * tempHash;
3714    Torrent * torrent;
3715    while ((torrent = [torrentEnum nextObject]))
3716    {
3717        torHash = [torrent hashString];
3718       
3719        hashEnum = [hashlist objectEnumerator];
3720        while ((tempHash = [hashEnum nextObject]))
3721        {
3722            if ([torHash caseInsensitiveCompare: tempHash] == NSOrderedSame)
3723            {
3724                [torrents addObject: torrent];
3725                break;
3726            }
3727        }
3728    }
3729   
3730    return torrents;
3731}
3732
3733- (BOOL) ipcAddTorrents: (NSArray *) torrents
3734{
3735    int oldCount = [fTorrents count];
3736   
3737    [self openFiles: torrents];
3738   
3739    return [fTorrents count] > oldCount;
3740}
3741
3742- (BOOL) ipcAddTorrentFile: (NSString *) path directory: (NSString *) directory
3743{
3744    int oldCount = [fTorrents count];
3745   
3746    [self openFiles: [NSArray arrayWithObject: path] forcePath: directory ignoreDownloadFolder: NO
3747            deleteTorrentFile: TORRENT_FILE_DEFAULT];
3748   
3749    return [fTorrents count] > oldCount;
3750}
3751
3752- (BOOL) ipcAddTorrentFileAutostart: (NSString *) path directory: (NSString *) directory autostart: (BOOL) autostart
3753{
3754    NSArray * torrents;
3755    if (autostart)
3756        torrents = [fTorrents copy];
3757    BOOL success = [self ipcAddTorrentFile: path directory: directory];
3758   
3759    if (success && autostart)
3760    {
3761        NSEnumerator * enumerator = [torrents objectEnumerator];
3762        Torrent * torrent;
3763        while ((torrent = [enumerator nextObject]))
3764            if (![torrents containsObject: torrent])
3765                break;
3766       
3767        if (torrent)
3768            [torrent startTransfer];
3769        else
3770            success = NO;
3771    }
3772   
3773    [torrents release];
3774    return success;
3775}
3776
3777- (BOOL) ipcAddTorrentData: (NSData *) data directory: (NSString *) directory
3778{
3779    /* 'data' is the contents of a torrent file, 'directory' is the
3780       directory it should download it's files to and may be nil,
3781       should return NO if torrent fails to load */
3782    return NO;
3783}
3784
3785- (BOOL) ipcAddTorrentDataAutostart: (NSData *) path directory: (NSString *) directory autostart: (BOOL) autostart
3786{
3787    /* 'data' is the contents of a torrent file, 'directory' is the
3788       directory it should download it's files to and may be nil,
3789       'autostart' is a boolean indicating if the torrent should be
3790       automatically started (or queued to start, I guess), should
3791       return NO if torrent fails to load */
3792    return NO;
3793}
3794
3795- (BOOL) ipcStartTorrents: (NSArray *) torrents
3796{
3797    if (!torrents)
3798        [self resumeAllTorrents: self];
3799    else
3800        [self resumeTorrents: torrents];
3801
3802    return YES;
3803}
3804
3805- (BOOL) ipcStopTorrents: (NSArray *) torrents
3806{
3807    if (!torrents)
3808        [self stopAllTorrents: self];
3809    else
3810        [self stopTorrents: torrents];
3811
3812    return YES;
3813}
3814
3815- (BOOL) ipcRemoveTorrents: (NSArray *) torrents
3816{
3817    if (!torrents)
3818        torrents = [NSArray arrayWithArray: fTorrents];
3819
3820    [self confirmRemoveTorrents: torrents deleteData: NO deleteTorrent: NO];
3821
3822    return YES;
3823}
3824
3825@end
Note: See TracBrowser for help on using the repository browser.