source: trunk/macosx/Controller.m @ 4189

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

sort groups by their order in the table

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