source: trunk/macosx/Controller.m @ 4183

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

preliminary commit of group code

  • Property svn:keywords set to Date Rev Author Id
File size: 135.6 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 4183 2007-12-17 16:06:20Z 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            //resort if necessary or just update the table
1442            NSString * sortType = [fDefaults stringForKey: @"Sort"];
1443            if ([sortType isEqualToString: SORT_ORDER] || [sortType isEqualToString: SORT_DATE]
1444                    || [sortType isEqualToString: SORT_NAME])
1445                [fTableView reloadData];
1446            else
1447                [self sortTorrents];
1448           
1449            //update status bar
1450            if (![fStatusBar isHidden])
1451            {
1452                //set rates
1453                float downloadRate, uploadRate;
1454                tr_torrentRates(fLib, & downloadRate, & uploadRate);
1455               
1456                [fTotalDLField setStringValue: [NSString stringForSpeed: downloadRate]];
1457                [fTotalULField setStringValue: [NSString stringForSpeed: uploadRate]];
1458               
1459                //set status button text
1460                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1461                BOOL total;
1462                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1463                {
1464                    tr_session_stats stats;
1465                    if (total)
1466                        tr_getCumulativeSessionStats(fLib, &stats);
1467                    else
1468                        tr_getSessionStats(fLib, &stats);
1469                   
1470                    statusString = [NSLocalizedString(@"Ratio: ", "status bar -> status label")
1471                                    stringByAppendingString: [NSString stringForRatio: stats.ratio]];
1472                }
1473                else if ((total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL])
1474                            || [statusLabel isEqualToString: STATUS_TRANSFER_SESSION])
1475                {
1476                    tr_session_stats stats;
1477                    if (total)
1478                        tr_getCumulativeSessionStats(fLib, &stats);
1479                    else
1480                        tr_getSessionStats(fLib, &stats);
1481                   
1482                    statusString = [NSString stringWithFormat: NSLocalizedString(@"DL: %@  UL: %@",
1483                        "status bar -> status label (2 spaces between)"),
1484                        [NSString stringForFileSize: stats.downloadedBytes], [NSString stringForFileSize: stats.uploadedBytes]];
1485                }
1486                else
1487                    statusString = @"";
1488               
1489                if ([NSApp isOnLeopardOrBetter])
1490                {
1491                    [fStatusButton setTitle: statusString];
1492                    [fStatusButton sizeToFit];
1493                   
1494                    //width ends up being too long
1495                    NSRect statusFrame = [fStatusButton frame];
1496                    statusFrame.size.width -= 25.0;
1497                    [fStatusButton setFrame: statusFrame];
1498                }
1499                else
1500                    [fStatusTigerField setStringValue: statusString];
1501            }
1502        }
1503
1504        //update non-constant parts of info window
1505        if ([[fInfoController window] isVisible])
1506            [fInfoController updateInfoStats];
1507    }
1508   
1509    //badge dock
1510    [fBadger updateBadge];
1511}
1512
1513- (void) updateTorrentsInQueue
1514{
1515    BOOL download = [fDefaults boolForKey: @"Queue"],
1516        seed = [fDefaults boolForKey: @"QueueSeed"];
1517   
1518    int desiredDownloadActive = [self numToStartFromQueue: YES],
1519        desiredSeedActive = [self numToStartFromQueue: NO];
1520   
1521    //sort torrents by order value
1522    NSArray * sortedTorrents;
1523    if ([fTorrents count] > 1 && (desiredDownloadActive > 0 || desiredSeedActive > 0))
1524    {
1525        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1526                                                @"orderValue" ascending: YES] autorelease];
1527        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1528       
1529        sortedTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
1530        [descriptors release];
1531    }
1532    else
1533        sortedTorrents = fTorrents;
1534   
1535    Torrent * torrent;
1536    NSEnumerator * enumerator = [sortedTorrents objectEnumerator];
1537    while ((torrent = [enumerator nextObject]))
1538    {
1539        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1540        {
1541            if (![torrent allDownloaded])
1542            {
1543                if (!download || desiredDownloadActive > 0)
1544                {
1545                    [torrent startTransfer];
1546                    if ([torrent isActive])
1547                        desiredDownloadActive--;
1548                    [torrent update];
1549                }
1550            }
1551            else
1552            {
1553                if (!seed || desiredSeedActive > 0)
1554                {
1555                    [torrent startTransfer];
1556                    if ([torrent isActive])
1557                        desiredSeedActive--;
1558                    [torrent update];
1559                }
1560            }
1561        }
1562    }
1563   
1564    [self updateUI];
1565    [self applyFilter: nil];
1566    [self updateTorrentHistory];
1567}
1568
1569- (int) numToStartFromQueue: (BOOL) downloadQueue
1570{
1571    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1572        return 0;
1573   
1574    int desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1575       
1576    Torrent * torrent;
1577    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1578    while ((torrent = [enumerator nextObject]))
1579    {
1580        if ([torrent isChecking])
1581        {
1582            desired--;
1583            if (desired <= 0)
1584                return 0;
1585        }
1586        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1587        {
1588            if ([torrent allDownloaded] != downloadQueue)
1589            {
1590                desired--;
1591                if (desired <= 0)
1592                    return 0;
1593            }
1594        }
1595        else;
1596    }
1597   
1598    return desired;
1599}
1600
1601- (void) torrentFinishedDownloading: (NSNotification *) notification
1602{
1603    Torrent * torrent = [notification object];
1604    if ([torrent isActive])
1605    {
1606        if ([fDefaults boolForKey: @"PlayDownloadSound"])
1607        {
1608            NSSound * sound;
1609            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1610                [sound play];
1611        }
1612       
1613        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1614                                        [torrent dataLocation] , @"Location", nil];
1615        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1616                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1617                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1618       
1619        if (![fWindow isMainWindow])
1620            [fBadger incrementCompleted];
1621       
1622        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1623        {
1624            [torrent stopTransfer];
1625            [torrent setWaitToStart: YES];
1626        }
1627    }
1628   
1629    [self updateTorrentsInQueue];
1630}
1631
1632- (void) torrentRestartedDownloading: (NSNotification *) notification
1633{
1634    Torrent * torrent = [notification object];
1635    if ([torrent isActive])
1636    {
1637        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1638        {
1639            [torrent stopTransfer];
1640            [torrent setWaitToStart: YES];
1641        }
1642    }
1643   
1644    [self updateTorrentsInQueue];
1645}
1646
1647- (void) updateTorrentHistory
1648{
1649    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1650
1651    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1652    Torrent * torrent;
1653    while ((torrent = [enumerator nextObject]))
1654        [history addObject: [torrent history]];
1655
1656    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: SUPPORT_FOLDER] atomically: YES];
1657}
1658
1659- (void) sortTorrents
1660{
1661    //remember selected rows if needed
1662    NSArray * selectedTorrents = nil;
1663    int numSelected = [fTableView numberOfSelectedRows];
1664    if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
1665        selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
1666
1667    [self sortTorrentsIgnoreSelected]; //actually sort
1668   
1669    //set selected rows if needed
1670    if (selectedTorrents)
1671    {
1672        Torrent * torrent;
1673        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1674        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1675        while ((torrent = [enumerator nextObject]))
1676            [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
1677       
1678        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1679        [indexSet release];
1680    }
1681}
1682
1683//doesn't remember selected rows
1684- (void) sortTorrentsIgnoreSelected
1685{
1686    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1687    BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1688   
1689    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name"
1690                                            ascending: asc selector: @selector(caseInsensitiveCompare:)] autorelease],
1691                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"orderValue"
1692                                            ascending: asc] autorelease];
1693   
1694    NSArray * descriptors;
1695    if ([sortType isEqualToString: SORT_NAME])
1696        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
1697    else if ([sortType isEqualToString: SORT_STATE])
1698    {
1699        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1700                                                @"stateSortKey" ascending: !asc] autorelease],
1701                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1702                                            @"progress" ascending: !asc] autorelease],
1703                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1704                                            @"ratio" ascending: !asc] autorelease];
1705       
1706        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1707                                                            nameDescriptor, orderDescriptor, nil];
1708    }
1709    else if ([sortType isEqualToString: SORT_PROGRESS])
1710    {
1711        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1712                                            @"progress" ascending: asc] autorelease],
1713                        * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1714                                            @"progressStopRatio" ascending: asc] autorelease],
1715                        * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1716                                            @"ratio" ascending: asc] autorelease];
1717       
1718        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1719                                                            nameDescriptor, orderDescriptor, nil];
1720    }
1721    else if ([sortType isEqualToString: SORT_TRACKER])
1722    {
1723        NSSortDescriptor * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddress"
1724                                                ascending: asc selector: @selector(caseInsensitiveCompare:)] autorelease];
1725       
1726        descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, orderDescriptor, nil];
1727    }
1728    else if ([sortType isEqualToString: SORT_ORDER])
1729        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1730    else if ([sortType isEqualToString: SORT_ACTIVITY])
1731    {
1732        NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc]
1733                                                    autorelease];
1734        NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1735                                                    autorelease];
1736       
1737        descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, orderDescriptor, nil];
1738    }
1739    else
1740    {
1741        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1742   
1743        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
1744    }
1745   
1746    [fDisplayedTorrents sortUsingDescriptors: descriptors];
1747    [descriptors release];
1748   
1749    [fTableView reloadData];
1750}
1751
1752- (void) setSort: (id) sender
1753{
1754    NSString * sortType;
1755    switch ([sender tag])
1756    {
1757        case SORT_ORDER_TAG:
1758            sortType = SORT_ORDER;
1759            [fDefaults setBool: NO forKey: @"SortReverse"];
1760            break;
1761        case SORT_DATE_TAG:
1762            sortType = SORT_DATE;
1763            break;
1764        case SORT_NAME_TAG:
1765            sortType = SORT_NAME;
1766            break;
1767        case SORT_PROGRESS_TAG:
1768            sortType = SORT_PROGRESS;
1769            break;
1770        case SORT_STATE_TAG:
1771            sortType = SORT_STATE;
1772            break;
1773        case SORT_TRACKER_TAG:
1774            sortType = SORT_TRACKER;
1775            break;
1776        case SORT_ACTIVITY_TAG:
1777            sortType = SORT_ACTIVITY;
1778            break;
1779        default:
1780            return;
1781    }
1782   
1783    [fDefaults setObject: sortType forKey: @"Sort"];
1784    [self sortTorrents];
1785}
1786
1787- (void) setSortReverse: (id) sender
1788{
1789    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1790    [self sortTorrents];
1791}
1792
1793- (void) applyFilter: (id) sender
1794{
1795    //remember selected rows if needed
1796    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1797                ? [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1798
1799    NSMutableArray * tempTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1800   
1801    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1802   
1803    int downloading = 0, seeding = 0, paused = 0;
1804    BOOL isDownload = [filterType isEqualToString: FILTER_DOWNLOAD],
1805            isSeed = [filterType isEqualToString: FILTER_SEED],
1806            isPause = [filterType isEqualToString: FILTER_PAUSE];
1807    BOOL filtering = isDownload || isSeed || isPause;
1808   
1809    //get count of each type
1810    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1811    Torrent * torrent;
1812    while ((torrent = [enumerator nextObject]))
1813    {
1814        if ([torrent isActive])
1815        {
1816            if ([torrent isSeeding])
1817            {
1818                seeding++;
1819                if (isSeed)
1820                    [tempTorrents addObject: torrent];
1821            }
1822            else
1823            {
1824                downloading++;
1825                if (isDownload)
1826                    [tempTorrents addObject: torrent];
1827            }
1828        }
1829        else
1830        {
1831            paused++;
1832            if (isPause)
1833                [tempTorrents addObject: torrent];
1834        }
1835    }
1836   
1837    if (!filtering)
1838        [tempTorrents setArray: fTorrents];
1839   
1840    //set button tooltips
1841    [fNoFilterButton setCount: [fTorrents count]];
1842    [fDownloadFilterButton setCount: downloading];
1843    [fSeedFilterButton setCount: seeding];
1844    [fPauseFilterButton setCount: paused];
1845   
1846    NSString * searchString = [fSearchFilterField stringValue];
1847    if ([searchString length] > 0)
1848    {
1849        filtering = YES;
1850       
1851        Torrent * torrent;
1852        BOOL filterTracker = [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER], remove;
1853       
1854        int i;
1855        for (i = [tempTorrents count]-1; i >= 0; i--)
1856        {
1857            torrent = [tempTorrents objectAtIndex: i];
1858            remove = YES;
1859           
1860            if (filterTracker)
1861            {
1862                NSEnumerator * trackerEnumerator = [[torrent allTrackers] objectEnumerator], * subTrackerEnumerator;
1863                NSArray * subTrackers;
1864                NSString * tracker;
1865                while (remove && (subTrackers = [trackerEnumerator nextObject]))
1866                {
1867                    subTrackerEnumerator = [subTrackers objectEnumerator];
1868                    while ((tracker = [subTrackerEnumerator nextObject]))
1869                    {
1870                        if ([tracker rangeOfString: searchString options: NSCaseInsensitiveSearch].location != NSNotFound)
1871                        {
1872                            remove = NO;
1873                            break;
1874                        }
1875                    }
1876                }
1877            }
1878            else
1879                remove = [[torrent name] rangeOfString: searchString options: NSCaseInsensitiveSearch].location == NSNotFound;
1880           
1881            if (remove)
1882                [tempTorrents removeObjectAtIndex: i];
1883        }
1884    }
1885   
1886    [fDisplayedTorrents setArray: tempTorrents];
1887   
1888    [self sortTorrentsIgnoreSelected];
1889   
1890    //set selected rows if needed
1891    if (selectedTorrents)
1892    {
1893        Torrent * torrent;
1894        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1895        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1896        unsigned index;
1897        while ((torrent = [enumerator nextObject]))
1898            if ((index = [fDisplayedTorrents indexOfObject: torrent]) != NSNotFound)
1899                [indexSet addIndex: index];
1900       
1901        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1902        [indexSet release];
1903    }
1904   
1905    //set status bar torrent count text
1906    NSString * totalTorrentsString;
1907    int totalCount = [fTorrents count];
1908    if (totalCount != 1)
1909        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1910    else
1911        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1912   
1913    if (filtering)
1914        totalTorrentsString = [NSString stringWithFormat: @"%d of %@", [fDisplayedTorrents count], totalTorrentsString];
1915   
1916    [fTotalTorrentsField setStringValue: totalTorrentsString];
1917
1918    [self setWindowSizeToFit];
1919}
1920
1921//resets filter and sorts torrents
1922- (void) setFilter: (id) sender
1923{
1924    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
1925   
1926    NSButton * prevFilterButton;
1927    if ([oldFilterType isEqualToString: FILTER_PAUSE])
1928        prevFilterButton = fPauseFilterButton;
1929    else if ([oldFilterType isEqualToString: FILTER_SEED])
1930        prevFilterButton = fSeedFilterButton;
1931    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
1932        prevFilterButton = fDownloadFilterButton;
1933    else
1934        prevFilterButton = fNoFilterButton;
1935   
1936    if (sender != prevFilterButton)
1937    {
1938        [prevFilterButton setState: NSOffState];
1939        [sender setState: NSOnState];
1940
1941        NSString * filterType;
1942        if (sender == fDownloadFilterButton)
1943            filterType = FILTER_DOWNLOAD;
1944        else if (sender == fPauseFilterButton)
1945            filterType = FILTER_PAUSE;
1946        else if (sender == fSeedFilterButton)
1947            filterType = FILTER_SEED;
1948        else
1949            filterType = FILTER_NONE;
1950
1951        [fDefaults setObject: filterType forKey: @"Filter"];
1952    }
1953    else
1954        [sender setState: NSOnState];
1955
1956    [self applyFilter: nil];
1957}
1958
1959- (void) setFilterSearchType: (id) sender
1960{
1961    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
1962   
1963    int prevTag, currentTag = [sender tag];
1964    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
1965        prevTag = FILTER_TYPE_TAG_TRACKER;
1966    else
1967        prevTag = FILTER_TYPE_TAG_NAME;
1968   
1969    if (currentTag != prevTag)
1970    {
1971        NSString * filterType;
1972        if (currentTag == FILTER_TYPE_TAG_TRACKER)
1973            filterType = FILTER_TYPE_TRACKER;
1974        else
1975            filterType = FILTER_TYPE_NAME;
1976       
1977        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
1978       
1979        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
1980    }
1981   
1982    [self applyFilter: nil];
1983}
1984
1985- (void) switchFilter: (id) sender
1986{
1987    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1988   
1989    NSButton * button;
1990    if ([filterType isEqualToString: FILTER_NONE])
1991        button = sender == fNextFilterItem ? fDownloadFilterButton : fPauseFilterButton;
1992    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
1993        button = sender == fNextFilterItem ? fSeedFilterButton : fNoFilterButton;
1994    else if ([filterType isEqualToString: FILTER_SEED])
1995        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
1996    else if ([filterType isEqualToString: FILTER_PAUSE])
1997        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
1998    else
1999        button = fNoFilterButton;
2000   
2001    [self setFilter: button];
2002}
2003
2004- (void) setStatusLabel: (id) sender
2005{
2006    NSString * statusLabel;
2007    switch ([sender tag])
2008    {
2009        case STATUS_RATIO_TOTAL_TAG:
2010            statusLabel = STATUS_RATIO_TOTAL;
2011            break;
2012        case STATUS_RATIO_SESSION_TAG:
2013            statusLabel = STATUS_RATIO_SESSION;
2014            break;
2015        case STATUS_TRANSFER_TOTAL_TAG:
2016            statusLabel = STATUS_TRANSFER_TOTAL;
2017            break;
2018        case STATUS_TRANSFER_SESSION_TAG:
2019            statusLabel = STATUS_TRANSFER_SESSION;
2020            break;
2021        default:
2022            return;
2023    }
2024   
2025    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2026    [self updateUI];
2027}
2028
2029- (void) showGroups: (id) sender
2030{
2031    [[GroupsWindowController groupsController] showWindow: self];
2032}
2033
2034- (void) menuNeedsUpdate: (NSMenu *) menu
2035{
2036    #warning if not group menu, return
2037    int i, keep = menu == fGroupsSetMenu ? 2 : 0;
2038    for (i = [menu numberOfItems]-1 - keep; i >= 0; i--)
2039        [menu removeItemAtIndex: i];
2040   
2041    NSMenu * groupMenu = [[GroupsWindowController groupsController] groupMenuWithTarget: self action: @selector(setGroup:)];
2042    [menu appendItemsFromMenu: groupMenu atIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [groupMenu numberOfItems])]
2043            atBottom: NO];
2044}
2045
2046- (void) setGroup: (id) sender
2047{
2048    NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2049    Torrent * torrent;
2050    while ((torrent = [enumerator nextObject]))
2051        [torrent setGroupValue: [[sender representedObject] intValue]];
2052   
2053    [self updateUI];
2054    [self applyFilter: nil];
2055    [self updateTorrentHistory];
2056}
2057
2058- (void) toggleSpeedLimit: (id) sender
2059{
2060    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2061    [fPrefsController applySpeedSettings: nil];
2062}
2063
2064- (void) autoSpeedLimitChange: (NSNotification *) notification
2065{
2066    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2067        return;
2068 
2069    NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2070                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]],
2071        * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2072                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]],
2073        * nowDate = [NSCalendarDate calendarDate];
2074   
2075    //check if should be on if within range
2076    int onTime = [onDate hourOfDay] * 60 + [onDate minuteOfHour],
2077        offTime = [offDate hourOfDay] * 60 + [offDate minuteOfHour],
2078        nowTime = [nowDate hourOfDay] * 60 + [nowDate minuteOfHour];
2079   
2080    BOOL shouldBeOn = NO;
2081    if (onTime < offTime)
2082        shouldBeOn = onTime <= nowTime && nowTime < offTime;
2083    else if (onTime > offTime)
2084        shouldBeOn = onTime <= nowTime || nowTime < offTime;
2085    else;
2086   
2087    if ([fDefaults boolForKey: @"SpeedLimit"] != shouldBeOn)
2088        [self toggleSpeedLimit: nil];
2089}
2090
2091- (void) autoSpeedLimit
2092{
2093    if (![fDefaults boolForKey: @"SpeedLimitAuto"])
2094        return;
2095   
2096    //only toggle if within first few seconds of minutes
2097    NSCalendarDate * nowDate = [NSCalendarDate calendarDate];
2098    if ([nowDate secondOfMinute] > AUTO_SPEED_LIMIT_SECONDS)
2099        return;
2100   
2101    NSCalendarDate * offDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2102                        [[fDefaults objectForKey: @"SpeedLimitAutoOffDate"] timeIntervalSinceReferenceDate]];
2103   
2104    BOOL toggle;
2105    if ([fDefaults boolForKey: @"SpeedLimit"])
2106        toggle = [nowDate hourOfDay] == [offDate hourOfDay] && [nowDate minuteOfHour] == [offDate minuteOfHour];
2107    else
2108    {
2109        NSCalendarDate * onDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:
2110                        [[fDefaults objectForKey: @"SpeedLimitAutoOnDate"] timeIntervalSinceReferenceDate]];
2111        toggle = ([nowDate hourOfDay] == [onDate hourOfDay] && [nowDate minuteOfHour] == [onDate minuteOfHour])
2112                    && !([onDate hourOfDay] == [offDate hourOfDay] && [onDate minuteOfHour] == [offDate minuteOfHour]);
2113    }
2114   
2115    if (toggle)
2116    {
2117        [self toggleSpeedLimit: nil];
2118       
2119        [GrowlApplicationBridge notifyWithTitle: [fDefaults boolForKey: @"SpeedLimit"]
2120                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2121                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2122            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2123            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2124    }
2125}
2126
2127- (void) setLimitGlobalEnabled: (id) sender
2128{
2129    [fPrefsController applySpeedSettings: nil];
2130}
2131
2132- (void) setQuickLimitGlobal: (id) sender
2133{
2134    [fDefaults setInteger: [[sender title] intValue] forKey: [sender menu] == fUploadMenu ? @"UploadLimit" : @"DownloadLimit"];
2135    [fDefaults setBool: YES forKey: [sender menu] == fUploadMenu ? @"CheckUpload" : @"CheckDownload"];
2136   
2137    [fPrefsController updateLimitFields];
2138    [fPrefsController applySpeedSettings: nil];
2139}
2140
2141- (void) setQuickRatioGlobal: (id) sender
2142{
2143    [fDefaults setBool: YES forKey: @"RatioCheck"];
2144    [fDefaults setFloat: [[sender title] floatValue] forKey: @"RatioLimit"];
2145   
2146    [fPrefsController updateRatioStopField];
2147}
2148
2149- (void) torrentStoppedForRatio: (NSNotification *) notification
2150{
2151    Torrent * torrent = [notification object];
2152   
2153    [self updateTorrentsInQueue];
2154    [fInfoController updateInfoStats];
2155    [fInfoController updateOptions];
2156   
2157    if ([fDefaults boolForKey: @"PlaySeedingSound"])
2158    {
2159        NSSound * sound;
2160        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
2161            [sound play];
2162    }
2163   
2164    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
2165                                    [torrent dataLocation], @"Location", nil];
2166    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
2167                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
2168                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
2169}
2170
2171-(void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2172{
2173    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2174    {
2175        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2176            return;
2177       
2178        if (fAutoImportTimer)
2179        {
2180            if ([fAutoImportTimer isValid])
2181                [fAutoImportTimer invalidate];
2182            [fAutoImportTimer release];
2183            fAutoImportTimer = nil;
2184        }
2185       
2186        //check again in 10 seconds in case torrent file wasn't complete
2187        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2188            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2189       
2190        [self checkAutoImportDirectory];
2191    }
2192}
2193
2194- (void) changeAutoImport
2195{
2196    if (fAutoImportTimer)
2197    {
2198        if ([fAutoImportTimer isValid])
2199            [fAutoImportTimer invalidate];
2200        [fAutoImportTimer release];
2201        fAutoImportTimer = nil;
2202    }
2203   
2204    if (fAutoImportedNames)
2205        [fAutoImportedNames removeAllObjects];
2206    [self checkAutoImportDirectory];
2207}
2208
2209- (void) checkAutoImportDirectory
2210{
2211    NSString * path;
2212    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2213        return;
2214   
2215    path = [path stringByExpandingTildeInPath];
2216   
2217    NSArray * importedNames;
2218    if (!(importedNames = [[NSFileManager defaultManager] directoryContentsAtPath: path]))
2219        return;
2220   
2221    //only check files that have not been checked yet
2222    NSMutableArray * newNames = [importedNames mutableCopy];
2223   
2224    if (fAutoImportedNames)
2225        [newNames removeObjectsInArray: fAutoImportedNames];
2226    else
2227        fAutoImportedNames = [[NSMutableArray alloc] init];
2228    [fAutoImportedNames setArray: importedNames];
2229   
2230    NSString * file;
2231    int i;
2232    for (i = [newNames count] - 1; i >= 0; i--)
2233    {
2234        file = [newNames objectAtIndex: i];
2235        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
2236            [newNames removeObjectAtIndex: i];
2237        else
2238            [newNames replaceObjectAtIndex: i withObject: [path stringByAppendingPathComponent: file]];
2239    }
2240   
2241    BOOL ask = [[fDefaults stringForKey: @"DownloadChoice"] isEqualToString: @"Ask"];
2242   
2243    NSEnumerator * enumerator = [newNames objectEnumerator];
2244    int canAdd, count;
2245    while ((file = [enumerator nextObject]))
2246    {
2247        canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL);
2248        if (canAdd == TR_OK)
2249        {
2250            if (!ask)
2251                count = [fTorrents count];
2252            [self openFiles: [NSArray arrayWithObject: file]];
2253           
2254            //check if torrent was opened
2255            if (!ask && [fTorrents count] > count)
2256                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added",
2257                    "Growl notification title") description: [file lastPathComponent]
2258                    notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO clickContext: nil];
2259        }
2260        else if (canAdd == TR_EINVALID)
2261            [fAutoImportedNames removeObject: [file lastPathComponent]];
2262        else;
2263    }
2264   
2265    [newNames release];
2266}
2267
2268- (void) beginCreateFile: (NSNotification *) notification
2269{
2270    if (![fDefaults boolForKey: @"AutoImport"])
2271        return;
2272   
2273    NSString * location = [notification object],
2274            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2275   
2276    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2277                                    isEqualToString: [path stringByExpandingTildeInPath]])
2278        [fAutoImportedNames addObject: [location lastPathComponent]];
2279}
2280
2281- (int) numberOfRowsInTableView: (NSTableView *) tableview
2282{
2283    return [fDisplayedTorrents count];
2284}
2285
2286- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row
2287{
2288    return nil;
2289}
2290
2291- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes toPasteboard: (NSPasteboard *) pasteboard
2292{
2293    //only allow reordering of rows if sorting by order
2294    if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2295    {
2296        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2297        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2298        return YES;
2299    }
2300    return NO;
2301}
2302
2303- (NSDragOperation) tableView: (NSTableView *) tableView validateDrop: (id <NSDraggingInfo>) info
2304    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
2305{
2306    NSPasteboard * pasteboard = [info draggingPasteboard];
2307    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2308    {
2309        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
2310        return NSDragOperationGeneric;
2311    }
2312   
2313    return NSDragOperationNone;
2314}
2315
2316- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
2317    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
2318{
2319    NSPasteboard * pasteboard = [info draggingPasteboard];
2320    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2321    {
2322        //remember selected rows if needed
2323        NSArray * selectedTorrents = nil;
2324        int numSelected = [fTableView numberOfSelectedRows];
2325        if (numSelected > 0 && numSelected < [fDisplayedTorrents count])
2326            selectedTorrents = [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]];
2327   
2328        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
2329                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2330       
2331        //determine where to move them
2332        int i;
2333        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2334            newRow--;
2335       
2336        //reinsert into array
2337        int insertIndex = newRow > 0 ? [[fDisplayedTorrents objectAtIndex: newRow-1] orderValue] + 1 : 0;
2338       
2339        //get all torrents to reorder
2340        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
2341                                                @"orderValue" ascending: YES] autorelease];
2342        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
2343       
2344        NSMutableArray * sortedTorrents = [[fTorrents sortedArrayUsingDescriptors: descriptors] mutableCopy];
2345        [descriptors release];
2346       
2347        //remove objects to reinsert
2348        NSArray * movingTorrents = [[fDisplayedTorrents objectsAtIndexes: indexes] retain];
2349        [sortedTorrents removeObjectsInArray: movingTorrents];
2350       
2351        //insert objects at new location
2352        for (i = 0; i < [movingTorrents count]; i++)
2353            [sortedTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: insertIndex + i];
2354       
2355        [movingTorrents release];
2356       
2357        //redo order values
2358        i = 0;
2359        for (i = 0; i < [sortedTorrents count]; i++)
2360            [[sortedTorrents objectAtIndex: i] setOrderValue: i];
2361       
2362        [sortedTorrents release];
2363       
2364        [self applyFilter: nil];
2365       
2366        //set selected rows if needed
2367        if (selectedTorrents)
2368        {
2369            Torrent * torrent;
2370            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
2371            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
2372            while ((torrent = [enumerator nextObject]))
2373                [indexSet addIndex: [fDisplayedTorrents indexOfObject: torrent]];
2374           
2375            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
2376            [indexSet release];
2377        }
2378    }
2379   
2380    return YES;
2381}
2382
2383- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2384{
2385    [fInfoController setInfoForTorrents: [fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]]];
2386}
2387
2388- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2389{
2390    NSPasteboard * pasteboard = [info draggingPasteboard];
2391    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2392    {
2393        //check if any torrent files can be added
2394        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2395        NSEnumerator * enumerator = [files objectEnumerator];
2396        NSString * file;
2397        BOOL torrent = NO;
2398        int canAdd;
2399        while ((file = [enumerator nextObject]))
2400        {
2401            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2402            {
2403                switch (canAdd = tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2404                {
2405                    case TR_OK:
2406                        if (!fOverlayWindow)
2407                            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2408                        [fOverlayWindow setTorrents: files];
2409                       
2410                        return NSDragOperationCopy;
2411                   
2412                    case TR_EDUPLICATE:
2413                        torrent = YES;
2414                }
2415            }
2416        }
2417       
2418        //create a torrent file if a single file
2419        if (!torrent && [files count] == 1)
2420        {
2421            if (!fOverlayWindow)
2422                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2423            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2424           
2425            return NSDragOperationCopy;
2426        }
2427    }
2428    else if ([[pasteboard types] containsObject: NSURLPboardType])
2429    {
2430        if (!fOverlayWindow)
2431            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2432        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2433       
2434        return NSDragOperationCopy;
2435    }
2436    else;
2437   
2438    return NSDragOperationNone;
2439}
2440
2441- (void) draggingExited: (id <NSDraggingInfo>) info
2442{
2443    if (fOverlayWindow)
2444        [fOverlayWindow fadeOut];
2445}
2446
2447- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2448{
2449    if (fOverlayWindow)
2450        [fOverlayWindow fadeOut];
2451   
2452    NSPasteboard * pasteboard = [info draggingPasteboard];
2453    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2454    {
2455        BOOL torrent = NO, accept = YES;
2456       
2457        //create an array of files that can be opened
2458        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
2459        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2460        NSEnumerator * enumerator = [files objectEnumerator];
2461        NSString * file;
2462        while ((file = [enumerator nextObject]))
2463        {
2464            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2465            {
2466                switch(tr_torrentParse(fLib, [file UTF8String], NULL, NULL))
2467                {
2468                    case TR_OK:
2469                        [filesToOpen addObject: file];
2470                        torrent = YES;
2471                        break;
2472                       
2473                    case TR_EDUPLICATE:
2474                        torrent = YES;
2475                }
2476            }
2477        }
2478       
2479        if ([filesToOpen count] > 0)
2480            [self application: NSApp openFiles: filesToOpen];
2481        else
2482        {
2483            if (!torrent && [files count] == 1)
2484                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2485            else
2486                accept = NO;
2487        }
2488        [filesToOpen release];
2489       
2490        return accept;
2491    }
2492    else if ([[pasteboard types] containsObject: NSURLPboardType])
2493    {
2494        NSURL * url;
2495        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2496        {
2497            [self openURL: url];
2498            return YES;
2499        }
2500    }
2501    else;
2502   
2503    return NO;
2504}
2505
2506- (void) toggleSmallView: (id) sender
2507{
2508    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2509    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2510   
2511    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2512   
2513    //window min height
2514    NSSize contentMinSize = [fWindow contentMinSize],
2515            contentSize = [[fWindow contentView] frame].size;
2516    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
2517                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2518    [fWindow setContentMinSize: contentMinSize];
2519   
2520    //resize for larger min height if not set to auto size
2521    if (![fDefaults boolForKey: @"AutoSize"])
2522    {
2523        if (!makeSmall && contentSize.height < contentMinSize.height)
2524        {
2525            NSRect frame = [fWindow frame];
2526            float heightChange = contentMinSize.height - contentSize.height;
2527            frame.size.height += heightChange;
2528            frame.origin.y -= heightChange;
2529           
2530            [fWindow setFrame: frame display: YES];
2531            [fTableView reloadData];
2532        }
2533    }
2534    else
2535        [self setWindowSizeToFit];
2536}
2537
2538- (void) togglePiecesBar: (id) sender
2539{
2540    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2541    [fTableView display];
2542}
2543
2544- (void) toggleAvailabilityBar: (id) sender
2545{
2546    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2547    [fTableView display];
2548}
2549
2550- (void) toggleStatusBar: (id) sender
2551{
2552    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2553    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2554}
2555
2556- (NSRect) windowFrameByAddingHeight: (float) height checkLimits: (BOOL) check
2557{
2558    //convert pixels to points
2559    NSRect windowFrame = [fWindow frame];
2560    NSSize windowSize = [fScrollView convertSize: windowFrame.size fromView: nil];
2561    windowSize.height += height;
2562   
2563    if (check)
2564    {
2565        NSSize minSize = [fScrollView convertSize: [fWindow minSize] fromView: nil];
2566       
2567        if (windowSize.height < minSize.height)
2568            windowSize.height = minSize.height;
2569        else
2570        {
2571            NSSize maxSize = [fScrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2572            if ([fStatusBar isHidden])
2573                maxSize.height -= [fStatusBar frame].size.height;
2574            if ([fFilterBar isHidden])
2575                maxSize.height -= [fFilterBar frame].size.height;
2576            if (windowSize.height > maxSize.height)
2577                windowSize.height = maxSize.height;
2578        }
2579    }
2580
2581    //convert points to pixels
2582    windowSize = [fScrollView convertSize: windowSize toView: nil];
2583
2584    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2585    windowFrame.size.height = windowSize.height;
2586    return windowFrame;
2587}
2588
2589- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2590{
2591    if (show != [fStatusBar isHidden])
2592        return;
2593
2594    if (show)
2595        [fStatusBar setHidden: NO];
2596
2597    NSRect frame;
2598    float heightChange = [fStatusBar frame].size.height;
2599    if (!show)
2600        heightChange *= -1;
2601   
2602    //allow bar to show even if not enough room
2603    if (show && ![fDefaults boolForKey: @"AutoSize"])
2604    {
2605        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2606        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2607        if (change < 0.0)
2608        {
2609            frame = [fWindow frame];
2610            frame.size.height += change;
2611            frame.origin.y -= change;
2612            [fWindow setFrame: frame display: NO animate: NO];
2613        }
2614    }
2615
2616    [self updateUI];
2617   
2618    //set views to not autoresize
2619    unsigned int statsMask = [fStatusBar autoresizingMask];
2620    unsigned int filterMask = [fFilterBar autoresizingMask];
2621    unsigned int scrollMask = [fScrollView autoresizingMask];
2622    [fStatusBar setAutoresizingMask: NSViewNotSizable];
2623    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2624    [fScrollView setAutoresizingMask: NSViewNotSizable];
2625   
2626    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2627    [fWindow setFrame: frame display: YES animate: animate];
2628   
2629    //re-enable autoresize
2630    [fStatusBar setAutoresizingMask: statsMask];
2631    [fFilterBar setAutoresizingMask: filterMask];
2632    [fScrollView setAutoresizingMask: scrollMask];
2633   
2634    //change min size
2635    NSSize minSize = [fWindow contentMinSize];
2636    minSize.height += heightChange;
2637    [fWindow setContentMinSize: minSize];
2638   
2639    if (!show)
2640        [fStatusBar setHidden: YES];
2641}
2642
2643- (void) toggleFilterBar: (id) sender
2644{
2645    //disable filtering when hiding
2646    if (![fFilterBar isHidden])
2647    {
2648        [fSearchFilterField setStringValue: @""];
2649        [self setFilter: fNoFilterButton];
2650    }
2651
2652    [self showFilterBar: [fFilterBar isHidden] animate: YES];
2653    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
2654}
2655
2656- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
2657{
2658    if (show != [fFilterBar isHidden])
2659        return;
2660
2661    if (show)
2662        [fFilterBar setHidden: NO];
2663
2664    NSRect frame;
2665    float heightChange = [fFilterBar frame].size.height;
2666    if (!show)
2667        heightChange *= -1;
2668   
2669    //allow bar to show even if not enough room
2670    if (show && ![fDefaults boolForKey: @"AutoSize"])
2671    {
2672        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2673        float change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
2674        if (change < 0.0)
2675        {
2676            frame = [fWindow frame];
2677            frame.size.height += change;
2678            frame.origin.y -= change;
2679            [fWindow setFrame: frame display: NO animate: NO];
2680        }
2681    }
2682
2683    //set views to not autoresize
2684    unsigned int filterMask = [fFilterBar autoresizingMask];
2685    unsigned int scrollMask = [fScrollView autoresizingMask];
2686    [fFilterBar setAutoresizingMask: NSViewNotSizable];
2687    [fScrollView setAutoresizingMask: NSViewNotSizable];
2688   
2689    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2690    [fWindow setFrame: frame display: YES animate: animate];
2691   
2692    //re-enable autoresize
2693    [fFilterBar setAutoresizingMask: filterMask];
2694    [fScrollView setAutoresizingMask: scrollMask];
2695   
2696    //change min size
2697    NSSize minSize = [fWindow contentMinSize];
2698    minSize.height += heightChange;
2699    [fWindow setContentMinSize: minSize];
2700   
2701    if (!show)
2702    {
2703        [fFilterBar setHidden: YES];
2704        [fWindow makeFirstResponder: fTableView];
2705    }
2706}
2707
2708- (void) doNothing: (id) sender {}
2709
2710- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
2711{
2712    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
2713   
2714    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
2715    [button setBezelStyle: NSTexturedRoundedBezelStyle];
2716    [button setStringValue: @""];
2717   
2718    [item setView: button];
2719    [button release];
2720   
2721    NSSize buttonSize = NSMakeSize(36.0, 25.0);
2722    [item setMinSize: buttonSize];
2723    [item setMaxSize: buttonSize];
2724   
2725    return [item autorelease];
2726}
2727
2728- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
2729{
2730    if ([ident isEqualToString: TOOLBAR_CREATE])
2731    {
2732        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2733       
2734        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
2735        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
2736        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
2737        [item setImage: [NSImage imageNamed: @"Create.png"]];
2738        [item setTarget: self];
2739        [item setAction: @selector(createFile:)];
2740        [item setAutovalidates: NO];
2741       
2742        return item;
2743    }
2744    else if ([ident isEqualToString: TOOLBAR_OPEN])
2745    {
2746        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2747       
2748        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
2749        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
2750        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
2751        [item setImage: [NSImage imageNamed: @"Open.png"]];
2752        [item setTarget: self];
2753        [item setAction: @selector(openShowSheet:)];
2754        [item setAutovalidates: NO];
2755       
2756        return item;
2757    }
2758    else if ([ident isEqualToString: TOOLBAR_REMOVE])
2759    {
2760        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2761       
2762        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
2763        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
2764        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
2765        [item setImage: [NSImage imageNamed: @"Remove.png"]];
2766        [item setTarget: self];
2767        [item setAction: @selector(removeNoDelete:)];
2768       
2769        return item;
2770    }
2771    else if ([ident isEqualToString: TOOLBAR_INFO])
2772    {
2773        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2774       
2775        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
2776        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
2777        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
2778        [item setImage: [NSImage imageNamed: @"Info.png"]];
2779        [item setTarget: self];
2780        [item setAction: @selector(showInfo:)];
2781       
2782        return item;
2783    }
2784    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
2785    {
2786        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
2787       
2788        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
2789        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
2790        [groupItem setView: segmentedControl];
2791        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
2792       
2793        [segmentedControl setSegmentCount: 2];
2794        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
2795       
2796        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
2797        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
2798        [groupItem setTarget: self];
2799        [groupItem setAction: @selector(allToolbarClicked:)];
2800       
2801        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
2802       
2803        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
2804        [segmentedControl setImage: [NSImage imageNamed: @"PauseAll.png"] forSegment: TOOLBAR_PAUSE_TAG];
2805        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
2806                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
2807       
2808        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
2809        [segmentedControl setImage: [NSImage imageNamed: @"ResumeAll.png"] forSegment: TOOLBAR_RESUME_TAG];
2810        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
2811                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
2812       
2813        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
2814                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
2815       
2816        NSSize groupSize = NSMakeSize(72.0, 25.0);
2817        [groupItem setMinSize: groupSize];
2818        [groupItem setMaxSize: groupSize];
2819       
2820        [segmentedControl release];
2821        return [groupItem autorelease];
2822    }
2823    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
2824    {
2825        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
2826       
2827        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
2828        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
2829        [groupItem setView: segmentedControl];
2830        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
2831       
2832        [segmentedControl setSegmentCount: 2];
2833        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
2834       
2835        NSSize groupSize = NSMakeSize(72.0, 25.0);
2836        [groupItem setMinSize: groupSize];
2837        [groupItem setMaxSize: groupSize];
2838       
2839        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
2840        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
2841        [groupItem setTarget: self];
2842        [groupItem setAction: @selector(selectedToolbarClicked:)];
2843       
2844        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
2845       
2846        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
2847        [segmentedControl setImage: [NSImage imageNamed: @"PauseSelected.png"] forSegment: TOOLBAR_PAUSE_TAG];
2848        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
2849                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
2850       
2851        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
2852        [segmentedControl setImage: [NSImage imageNamed: @"ResumeSelected.png"] forSegment: TOOLBAR_RESUME_TAG];
2853        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
2854                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
2855       
2856        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
2857                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
2858       
2859        [segmentedControl release];
2860        return [groupItem autorelease];
2861    }
2862    else if ([ident isEqualToString: TOOLBAR_FILTER])
2863    {
2864        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
2865       
2866        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
2867        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
2868        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
2869        [item setImage: [NSImage imageNamed: @"Filter.png"]];
2870        [item setTarget: self];
2871        [item setAction: @selector(toggleFilterBar:)];
2872       
2873        return item;
2874    }
2875    else
2876        return nil;
2877}
2878
2879- (void) allToolbarClicked: (id) sender
2880{
2881    int tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
2882                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
2883    switch (tagValue)
2884    {
2885        case TOOLBAR_PAUSE_TAG:
2886            [self stopAllTorrents: sender];
2887            break;
2888        case TOOLBAR_RESUME_TAG:
2889            [self resumeAllTorrents: sender];
2890            break;
2891    }
2892}
2893
2894- (void) selectedToolbarClicked: (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 stopSelectedTorrents: sender];
2902            break;
2903        case TOOLBAR_RESUME_TAG:
2904            [self resumeSelectedTorrents: sender];
2905            break;
2906    }
2907}
2908
2909- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
2910{
2911    return [NSArray arrayWithObjects:
2912            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2913            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
2914            TOOLBAR_FILTER, TOOLBAR_INFO,
2915            NSToolbarSeparatorItemIdentifier,
2916            NSToolbarSpaceItemIdentifier,
2917            NSToolbarFlexibleSpaceItemIdentifier,
2918            NSToolbarCustomizeToolbarItemIdentifier, nil];
2919}
2920
2921- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
2922{
2923    return [NSArray arrayWithObjects:
2924            TOOLBAR_CREATE, TOOLBAR_OPEN, TOOLBAR_REMOVE,
2925            NSToolbarSeparatorItemIdentifier,
2926            TOOLBAR_PAUSE_RESUME_ALL,
2927            NSToolbarFlexibleSpaceItemIdentifier,
2928            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
2929}
2930
2931- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
2932{
2933    NSString * ident = [toolbarItem itemIdentifier];
2934   
2935    //enable remove item
2936    if ([ident isEqualToString: TOOLBAR_REMOVE])
2937        return [fTableView numberOfSelectedRows] > 0;
2938
2939    //enable pause all item
2940    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
2941    {
2942        Torrent * torrent;
2943        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2944        while ((torrent = [enumerator nextObject]))
2945            if ([torrent isActive] || [torrent waitingToStart])
2946                return YES;
2947        return NO;
2948    }
2949
2950    //enable resume all item
2951    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
2952    {
2953        Torrent * torrent;
2954        NSEnumerator * enumerator = [fTorrents objectEnumerator];
2955        while ((torrent = [enumerator nextObject]))
2956            if (![torrent isActive] && ![torrent waitingToStart])
2957                return YES;
2958        return NO;
2959    }
2960
2961    //enable pause item
2962    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
2963    {
2964        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2965        Torrent * torrent;
2966        while ((torrent = [enumerator nextObject]))
2967            if ([torrent isActive] || [torrent waitingToStart])
2968                return YES;
2969        return NO;
2970    }
2971   
2972    //enable resume item
2973    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
2974    {
2975        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
2976        Torrent * torrent;
2977        while ((torrent = [enumerator nextObject]))
2978            if (![torrent isActive] && ![torrent waitingToStart])
2979                return YES;
2980        return NO;
2981    }
2982   
2983    //set info image
2984    if ([ident isEqualToString: TOOLBAR_INFO])
2985    {
2986        [toolbarItem setImage: [[fInfoController window] isVisible] ? [NSImage imageNamed: @"InfoBlue"]
2987                                                                    : [NSImage imageNamed: @"Info"]];
2988        return YES;
2989    }
2990   
2991    //set filter image
2992    if ([ident isEqualToString: TOOLBAR_FILTER])
2993    {
2994        [toolbarItem setImage: ![fFilterBar isHidden] ? [NSImage imageNamed: @"FilterBlue"] : [NSImage imageNamed: @"Filter"]];
2995        return YES;
2996    }
2997
2998    return YES;
2999}
3000
3001- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3002{
3003    SEL action = [menuItem action];
3004   
3005    if (action == @selector(toggleSpeedLimit:))
3006    {
3007        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3008        return YES;
3009    }
3010   
3011    //only enable some items if it is in a context menu or the window is useable
3012    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3013
3014    //enable open items
3015    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3016        return [fWindow attachedSheet] == nil;
3017   
3018    //enable sort options
3019    if (action == @selector(setSort:))
3020    {
3021        NSString * sortType;
3022        switch ([menuItem tag])
3023        {
3024            case SORT_ORDER_TAG:
3025                sortType = SORT_ORDER;
3026                break;
3027            case SORT_DATE_TAG:
3028                sortType = SORT_DATE;
3029                break;
3030            case SORT_NAME_TAG:
3031                sortType = SORT_NAME;
3032                break;
3033            case SORT_PROGRESS_TAG:
3034                sortType = SORT_PROGRESS;
3035                break;
3036            case SORT_STATE_TAG:
3037                sortType = SORT_STATE;
3038                break;
3039            case SORT_TRACKER_TAG:
3040                sortType = SORT_TRACKER;
3041                break;
3042            case SORT_ACTIVITY_TAG:
3043                sortType = SORT_ACTIVITY;
3044                break;
3045            default:
3046                sortType = @"";
3047        }
3048       
3049        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3050        return [fWindow isVisible];
3051    }
3052   
3053    //enable sort options
3054    if (action == @selector(setStatusLabel:))
3055    {
3056        NSString * statusLabel;
3057        switch ([menuItem tag])
3058        {
3059            case STATUS_RATIO_TOTAL_TAG:
3060                statusLabel = STATUS_RATIO_TOTAL;
3061                break;
3062            case STATUS_RATIO_SESSION_TAG:
3063                statusLabel = STATUS_RATIO_SESSION;
3064                break;
3065            case STATUS_TRANSFER_TOTAL_TAG:
3066                statusLabel = STATUS_TRANSFER_TOTAL;
3067                break;
3068            case STATUS_TRANSFER_SESSION_TAG:
3069                statusLabel = STATUS_TRANSFER_SESSION;
3070                break;
3071            default:
3072                statusLabel = @"";;
3073        }
3074       
3075        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3076        return YES;
3077    }
3078   
3079    if (action == @selector(toggleSmallView:))
3080    {
3081        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3082        return [fWindow isVisible];
3083    }
3084   
3085    if (action == @selector(togglePiecesBar:))
3086    {
3087        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3088        return [fWindow isVisible];
3089    }
3090   
3091    if (action == @selector(toggleAvailabilityBar:))
3092    {
3093        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3094        return [fWindow isVisible];
3095    }
3096
3097    //enable show info
3098    if (action == @selector(showInfo:))
3099    {
3100        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3101                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3102        [menuItem setTitle: title];
3103
3104        return YES;
3105    }
3106   
3107    //enable prev/next inspector tab
3108    if (action == @selector(setInfoTab:))
3109        return [[fInfoController window] isVisible];
3110   
3111    //enable toggle status bar
3112    if (action == @selector(toggleStatusBar:))
3113    {
3114        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3115                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3116        [menuItem setTitle: title];
3117
3118        return [fWindow isVisible];
3119    }
3120   
3121    //enable toggle filter bar
3122    if (action == @selector(toggleFilterBar:))
3123    {
3124        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3125                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3126        [menuItem setTitle: title];
3127
3128        return [fWindow isVisible];
3129    }
3130   
3131    //enable prev/next filter button
3132    if (action == @selector(switchFilter:))
3133        return [fWindow isVisible] && ![fFilterBar isHidden];
3134
3135    //enable reveal in finder
3136    if (action == @selector(revealFile:))
3137        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3138
3139    //enable remove items
3140    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
3141        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
3142    {
3143        BOOL warning = NO,
3144            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
3145            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
3146       
3147        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3148        Torrent * torrent;
3149        while ((torrent = [enumerator nextObject]))
3150        {
3151            if (!warning && [torrent isActive])
3152            {
3153                warning = onlyDownloading ? ![torrent isSeeding] : YES;
3154                if (warning && canDelete)
3155                    break;
3156            }
3157            if (!canDelete && [torrent publicTorrent])
3158            {
3159                canDelete = YES;
3160                if (warning)
3161                    break;
3162            }
3163        }
3164   
3165        //append or remove ellipsis when needed
3166        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3167        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3168        {
3169            if (![title hasSuffix: ellipsis])
3170                [menuItem setTitle: [title stringByAppendingEllipsis]];
3171        }
3172        else
3173        {
3174            if ([title hasSuffix: ellipsis])
3175                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3176        }
3177       
3178        return canUseTable && canDelete && [fTableView numberOfSelectedRows] > 0;
3179    }
3180
3181    //enable pause all item
3182    if (action == @selector(stopAllTorrents:))
3183    {
3184        Torrent * torrent;
3185        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3186        while ((torrent = [enumerator nextObject]))
3187            if ([torrent isActive] || [torrent waitingToStart])
3188                return YES;
3189        return NO;
3190    }
3191   
3192    //enable resume all item
3193    if (action == @selector(resumeAllTorrents:))
3194    {
3195        Torrent * torrent;
3196        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3197        while ((torrent = [enumerator nextObject]))
3198            if (![torrent isActive] && ![torrent waitingToStart])
3199                return YES;
3200        return NO;
3201    }
3202   
3203    //enable resume all waiting item
3204    if (action == @selector(resumeWaitingTorrents:))
3205    {
3206        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3207            return NO;
3208   
3209        Torrent * torrent;
3210        NSEnumerator * enumerator = [fTorrents objectEnumerator];
3211        while ((torrent = [enumerator nextObject]))
3212            if (![torrent isActive] && [torrent waitingToStart])
3213                return YES;
3214        return NO;
3215    }
3216   
3217    //enable resume selected waiting item
3218    if (action == @selector(resumeSelectedTorrentsNoWait:))
3219    {
3220        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3221            return NO;
3222   
3223        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3224        Torrent * torrent;
3225        while ((torrent = [enumerator nextObject]))
3226            if (![torrent isActive])
3227                return YES;
3228        return NO;
3229    }
3230
3231    //enable pause item
3232    if (action == @selector(stopSelectedTorrents:))
3233    {
3234        if (!canUseTable)
3235            return NO;
3236   
3237        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3238        Torrent * torrent;
3239        while ((torrent = [enumerator nextObject]))
3240            if ([torrent isActive] || [torrent waitingToStart])
3241                return YES;
3242        return NO;
3243    }
3244   
3245    //enable resume item
3246    if (action == @selector(resumeSelectedTorrents:))
3247    {
3248        if (!canUseTable)
3249            return NO;
3250   
3251        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3252        Torrent * torrent;
3253        while ((torrent = [enumerator nextObject]))
3254            if (![torrent isActive] && ![torrent waitingToStart])
3255                return YES;
3256        return NO;
3257    }
3258   
3259    //enable manual announce item
3260    if (action == @selector(announceSelectedTorrents:))
3261    {
3262        if (!canUseTable)
3263            return NO;
3264       
3265        NSEnumerator * enumerator = [[fDisplayedTorrents objectsAtIndexes: [fTableView selectedRowIndexes]] objectEnumerator];
3266        Torrent * torrent;
3267        while ((torrent = [enumerator nextObject]))
3268            if ([torrent canManualAnnounce])
3269                return YES;
3270        return NO;
3271    }
3272   
3273    //enable reset cache item
3274    if (action == @selector(resetCacheForSelectedTorrents:))
3275        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3276   
3277    //enable move torrent file item
3278    if (action == @selector(moveDataFiles:))
3279        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3280   
3281    //enable copy torrent file item
3282    if (action == @selector(copyTorrentFiles:))
3283        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3284   
3285    //enable reverse sort item
3286    if (action == @selector(setSortReverse:))
3287    {
3288        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3289        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3290    }
3291   
3292    //check proper filter search item
3293    if (action == @selector(setFilterSearchType:))
3294    {
3295        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3296       
3297        BOOL state;
3298        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3299            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3300        else
3301            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3302       
3303        [menuItem setState: state ? NSOnState : NSOffState];
3304        return YES;
3305    }
3306   
3307    return YES;
3308}
3309
3310- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
3311{
3312    NSEnumerator * enumerator;
3313    Torrent * torrent;
3314    BOOL allowSleep;
3315
3316    switch (messageType)
3317    {
3318        case kIOMessageSystemWillSleep:
3319            //close all connections before going to sleep and remember we should resume when we wake up
3320            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
3321
3322            //wait for running transfers to stop (5 second timeout)
3323            NSDate * start = [NSDate date];
3324            BOOL timeUp = NO;
3325           
3326            enumerator = [fTorrents objectEnumerator];
3327            while (!timeUp && (torrent = [enumerator nextObject]))
3328                while ([torrent isActive] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
3329                {
3330                    usleep(100000);
3331                    [torrent update];
3332                }
3333
3334            IOAllowPowerChange(fRootPort, (long) messageArgument);
3335            break;
3336
3337        case kIOMessageCanSystemSleep:
3338            allowSleep = YES;
3339            if ([fDefaults boolForKey: @"SleepPrevent"])
3340            {
3341                //prevent idle sleep unless no torrents are active
3342                enumerator = [fTorrents objectEnumerator];
3343                while ((torrent = [enumerator nextObject]))
3344                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3345                    {
3346                        allowSleep = NO;
3347                        break;
3348                    }
3349            }
3350
3351            if (allowSleep)
3352                IOAllowPowerChange(fRootPort, (long) messageArgument);
3353            else
3354                IOCancelPowerChange(fRootPort, (long) messageArgument);
3355            break;
3356
3357        case kIOMessageSystemHasPoweredOn:
3358            //resume sleeping transfers after we wake up
3359            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
3360            [self autoSpeedLimitChange: nil];
3361            break;
3362    }
3363}
3364
3365- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3366{
3367    int seeding = 0, downloading = 0;
3368    NSEnumerator * enumerator = [fTorrents objectEnumerator];
3369    Torrent * torrent;
3370    while ((torrent = [enumerator nextObject]))
3371    {
3372        if ([torrent isSeeding])
3373            seeding++;
3374        else if ([torrent isActive])
3375            downloading++;
3376        else;
3377    }
3378   
3379    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3380            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3381   
3382    BOOL hasSeparator = seedingItem || downloadingItem;
3383   
3384    if (seeding > 0)
3385    {
3386        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding",
3387                                                        "Dock item - Seeding"), seeding];
3388        if (!seedingItem)
3389        {
3390            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3391            [seedingItem setTag: DOCK_SEEDING_TAG];
3392            [fDockMenu insertItem: seedingItem atIndex: 0];
3393        }
3394        else
3395            [seedingItem setTitle: title];
3396    }
3397    else
3398    {
3399        if (seedingItem)
3400            [fDockMenu removeItem: seedingItem];
3401    }
3402   
3403    if (downloading > 0)
3404    {
3405        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading",
3406                                                        "Dock item - Downloading"), downloading];
3407        if (!downloadingItem)
3408        {
3409            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3410            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3411            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3412        }
3413        else
3414            [downloadingItem setTitle: title];
3415    }
3416    else
3417    {
3418        if (downloadingItem)
3419            [fDockMenu removeItem: downloadingItem];
3420    }
3421   
3422    if (seeding > 0 || downloading > 0)
3423    {
3424        if (!hasSeparator)
3425            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3426    }
3427    else
3428    {
3429        if (hasSeparator)
3430            [fDockMenu removeItemAtIndex: 0];
3431    }
3432   
3433    return fDockMenu;
3434}
3435
3436- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3437{
3438    //if auto size is enabled, the current frame shouldn't need to change
3439    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3440   
3441    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3442    return frame;
3443}
3444
3445- (void) setWindowSizeToFit
3446{
3447    if ([fDefaults boolForKey: @"AutoSize"])
3448    {
3449        [fScrollView setHasVerticalScroller: NO];
3450        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3451        [fScrollView setHasVerticalScroller: YES];
3452    }
3453}
3454
3455- (NSRect) sizedWindowFrame
3456{
3457    float heightChange = [fDisplayedTorrents count] * ([fTableView rowHeight] +
3458            [fTableView intercellSpacing].height) - [fScrollView frame].size.height;
3459    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3460}
3461
3462- (void) showMainWindow: (id) sender
3463{
3464    [fWindow makeKeyAndOrderFront: nil];
3465}
3466
3467- (void) windowDidBecomeMain: (NSNotification *) notification
3468{
3469    [fBadger clearCompleted];
3470    [self updateUI];
3471}
3472
3473- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3474{
3475    //only resize horizontally if autosize is enabled
3476    if ([fDefaults boolForKey: @"AutoSize"])
3477        proposedFrameSize.height = [fWindow frame].size.height;
3478    return proposedFrameSize;
3479}
3480
3481- (void) windowDidResize: (NSNotification *) notification
3482{
3483    //size search filter to not overlap buttons
3484    float pointX = NSMaxX([fPauseFilterButton frame]) + 5.0;
3485    NSRect oldFrame = [fSearchFilterField frame],
3486            frame = NSMakeRect(pointX, oldFrame.origin.y, NSMaxX(oldFrame) - pointX, oldFrame.size.height);
3487   
3488    BOOL show = frame.size.width >= SEARCH_FILTER_MIN_WIDTH;
3489    if (show)
3490    {
3491        //make sure it is not too long
3492        if (frame.size.width > SEARCH_FILTER_MAX_WIDTH)
3493        {
3494            float different = frame.size.width - SEARCH_FILTER_MAX_WIDTH;
3495            frame.origin.x += different;
3496            frame.size.width -= different;
3497        }
3498        [fSearchFilterField setFrame: frame];
3499    }
3500   
3501    //hide search filter if it overlaps filter buttons
3502    [fSearchFilterField setHidden: !show];
3503}
3504
3505- (void) applicationWillUnhide: (NSNotification *) notification
3506{
3507    [self updateUI];
3508}
3509
3510- (void) linkHomepage: (id) sender
3511{
3512    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
3513}
3514
3515- (void) linkForums: (id) sender
3516{
3517    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
3518}
3519
3520- (void) linkDonate: (id) sender
3521{
3522    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
3523}
3524
3525- (void) prepareForUpdate: (NSNotification *) notification
3526{
3527    fUpdateInProgress = YES;
3528}
3529
3530- (NSDictionary *) registrationDictionaryForGrowl
3531{
3532    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
3533                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
3534    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
3535                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
3536}
3537
3538- (void) growlNotificationWasClicked: (id) clickContext
3539{
3540    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
3541        return;
3542   
3543    NSString * type = [clickContext objectForKey: @"Type"], * location;
3544    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
3545            && (location = [clickContext objectForKey: @"Location"]))
3546        [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
3547}
3548
3549- (void) ipcQuit
3550{
3551    fRemoteQuit = YES;
3552    [NSApp terminate: self];
3553}
3554
3555- (NSArray *) ipcGetTorrentsByID: (NSArray *) idlist
3556{
3557    if (!idlist)
3558        return fTorrents;
3559   
3560    NSMutableArray * torrents = [NSMutableArray array];
3561   
3562    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * idEnum;
3563    int torId;
3564    Torrent * torrent;
3565    NSNumber * tempId;
3566    while ((torrent = [torrentEnum nextObject]))
3567    {
3568        torId = [torrent torrentID];
3569       
3570        idEnum = [idlist objectEnumerator];
3571        while ((tempId = [idEnum nextObject]))
3572        {
3573            if ([tempId intValue] == torId)
3574            {
3575                [torrents addObject: torrent];
3576                break;
3577            }
3578        }
3579    }
3580
3581    return torrents;
3582}
3583
3584- (NSArray *) ipcGetTorrentsByHash: (NSArray *) hashlist
3585{
3586    if (!hashlist)
3587        return fTorrents;
3588   
3589    NSMutableArray * torrents = [NSMutableArray array];
3590   
3591    NSEnumerator * torrentEnum = [fTorrents objectEnumerator], * hashEnum;
3592    NSString * torHash, * tempHash;
3593    Torrent * torrent;
3594    while ((torrent = [torrentEnum nextObject]))
3595    {
3596        torHash = [torrent hashString];
3597       
3598        hashEnum = [hashlist objectEnumerator];
3599        while ((tempHash = [hashEnum nextObject]))
3600        {
3601            if ([torHash caseInsensitiveCompare: tempHash] == NSOrderedSame)
3602            {
3603                [torrents addObject: torrent];
3604                break;
3605            }
3606        }
3607    }
3608   
3609    return torrents;
3610}
3611
3612- (BOOL) ipcAddTorrents: (NSArray *) torrents
3613{
3614    int oldCount = [fTorrents count];
3615   
3616    [self openFiles: torrents];
3617   
3618    return [fTorrents count] > oldCount;
3619}
3620
3621- (BOOL) ipcAddTorrentFile: (NSString *) path directory: (NSString *) directory
3622{
3623    int oldCount = [fTorrents count];
3624   
3625    [self openFiles: [NSArray arrayWithObject: path] forcePath: directory ignoreDownloadFolder: NO
3626            deleteTorrentFile: TORRENT_FILE_DEFAULT];
3627   
3628    return [fTorrents count] > oldCount;
3629}
3630
3631- (BOOL) ipcAddTorrentFileAutostart: (NSString *) path directory: (NSString *) directory autostart: (BOOL) autostart
3632{
3633    NSArray * torrents;
3634    if (autostart)
3635        torrents = [fTorrents copy];
3636    BOOL success = [self ipcAddTorrentFile: path directory: directory];
3637   
3638    if (success && autostart)
3639    {
3640        NSEnumerator * enumerator = [torrents objectEnumerator];
3641        Torrent * torrent;
3642        while ((torrent = [enumerator nextObject]))
3643            if (![torrents containsObject: torrent])
3644                break;
3645       
3646        if (torrent)
3647            [torrent startTransfer];
3648        else
3649            success = NO;
3650    }
3651   
3652    [torrents release];
3653    return success;
3654}
3655
3656- (BOOL) ipcAddTorrentData: (NSData *) data directory: (NSString *) directory
3657{
3658    /* 'data' is the contents of a torrent file, 'directory' is the
3659       directory it should download it's files to and may be nil,
3660       should return NO if torrent fails to load */
3661    return NO;
3662}
3663
3664- (BOOL) ipcAddTorrentDataAutostart: (NSData *) path directory: (NSString *) directory autostart: (BOOL) autostart
3665{
3666    /* 'data' is the contents of a torrent file, 'directory' is the
3667       directory it should download it's files to and may be nil,
3668       'autostart' is a boolean indicating if the torrent should be
3669       automatically started (or queued to start, I guess), should
3670       return NO if torrent fails to load */
3671    return NO;
3672}
3673
3674- (BOOL) ipcStartTorrents: (NSArray *) torrents
3675{
3676    if (!torrents)
3677        [self resumeAllTorrents: self];
3678    else
3679        [self resumeTorrents: torrents];
3680
3681    return YES;
3682}
3683
3684- (BOOL) ipcStopTorrents: (NSArray *) torrents
3685{
3686    if (!torrents)
3687        [self stopAllTorrents: self];
3688    else
3689        [self stopTorrents: torrents];
3690
3691    return YES;
3692}
3693
3694- (BOOL) ipcRemoveTorrents: (NSArray *) torrents
3695{
3696    if (!torrents)
3697        torrents = [NSArray arrayWithArray: fTorrents];
3698
3699    [self confirmRemoveTorrents: torrents deleteData: NO deleteTorrent: NO];
3700
3701    return YES;
3702}
3703
3704@end
Note: See TracBrowser for help on using the repository browser.