source: trunk/macosx/Controller.m @ 4191

Last change on this file since 4191 was 4191, checked in by livings124, 14 years ago

fix sizing of group labels with long file names

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