source: trunk/macosx/Controller.m @ 9267

Last change on this file since 9267 was 9267, checked in by livings124, 13 years ago

attempt number one of fixing 10.5 support

  • Property svn:keywords set to Date Rev Author Id
File size: 155.0 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 9267 2009-10-10 13:21:27Z livings124 $
3 *
4 * Copyright (c) 2005-2009 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#import <IOKit/pwr_mgt/IOPMLib.h>
27#import <Carbon/Carbon.h>
28
29#import "Controller.h"
30#import "Torrent.h"
31#import "TorrentGroup.h"
32#import "TorrentTableView.h"
33#import "CreatorWindowController.h"
34#import "StatsWindowController.h"
35#import "GroupsController.h"
36#import "AboutWindowController.h"
37#import "ButtonToolbarItem.h"
38#import "GroupToolbarItem.h"
39#import "ToolbarSegmentedCell.h"
40#import "BlocklistDownloader.h"
41#import "StatusBarView.h"
42#import "FilterButton.h"
43#import "BonjourController.h"
44#import "NSApplicationAdditions.h"
45#import "NSStringAdditions.h"
46#import "ExpandedPathToPathTransformer.h"
47#import "ExpandedPathToIconTransformer.h"
48#import "bencode.h"
49#import "utils.h"
50
51#import "UKKQueue.h"
52#import <Sparkle/Sparkle.h>
53
54#define TOOLBAR_CREATE                  @"Toolbar Create"
55#define TOOLBAR_OPEN_FILE               @"Toolbar Open"
56#define TOOLBAR_OPEN_WEB                @"Toolbar Open Web"
57#define TOOLBAR_REMOVE                  @"Toolbar Remove"
58#define TOOLBAR_INFO                    @"Toolbar Info"
59#define TOOLBAR_PAUSE_ALL               @"Toolbar Pause All"
60#define TOOLBAR_RESUME_ALL              @"Toolbar Resume All"
61#define TOOLBAR_PAUSE_RESUME_ALL        @"Toolbar Pause / Resume All"
62#define TOOLBAR_PAUSE_SELECTED          @"Toolbar Pause Selected"
63#define TOOLBAR_RESUME_SELECTED         @"Toolbar Resume Selected"
64#define TOOLBAR_PAUSE_RESUME_SELECTED   @"Toolbar Pause / Resume Selected"
65#define TOOLBAR_FILTER                  @"Toolbar Toggle Filter"
66#define TOOLBAR_QUICKLOOK               @"Toolbar QuickLook"
67
68typedef enum
69{
70    TOOLBAR_PAUSE_TAG = 0,
71    TOOLBAR_RESUME_TAG = 1
72} toolbarGroupTag;
73
74#define SORT_DATE       @"Date"
75#define SORT_NAME       @"Name"
76#define SORT_STATE      @"State"
77#define SORT_PROGRESS   @"Progress"
78#define SORT_TRACKER    @"Tracker"
79#define SORT_ORDER      @"Order"
80#define SORT_ACTIVITY   @"Activity"
81
82typedef enum
83{
84    SORT_ORDER_TAG = 0,
85    SORT_DATE_TAG = 1,
86    SORT_NAME_TAG = 2,
87    SORT_PROGRESS_TAG = 3,
88    SORT_STATE_TAG = 4,
89    SORT_TRACKER_TAG = 5,
90    SORT_ACTIVITY_TAG = 6
91} sortTag;
92
93#define FILTER_NONE     @"None"
94#define FILTER_ACTIVE   @"Active"
95#define FILTER_DOWNLOAD @"Download"
96#define FILTER_SEED     @"Seed"
97#define FILTER_PAUSE    @"Pause"
98
99#define FILTER_TYPE_NAME    @"Name"
100#define FILTER_TYPE_TRACKER @"Tracker"
101
102#define FILTER_TYPE_TAG_NAME    401
103#define FILTER_TYPE_TAG_TRACKER 402
104
105#define GROUP_FILTER_ALL_TAG    -2
106
107#define STATUS_RATIO_TOTAL      @"RatioTotal"
108#define STATUS_RATIO_SESSION    @"RatioSession"
109#define STATUS_TRANSFER_TOTAL   @"TransferTotal"
110#define STATUS_TRANSFER_SESSION @"TransferSession"
111
112typedef enum
113{
114    STATUS_RATIO_TOTAL_TAG = 0,
115    STATUS_RATIO_SESSION_TAG = 1,
116    STATUS_TRANSFER_TOTAL_TAG = 2,
117    STATUS_TRANSFER_SESSION_TAG = 3
118} statusTag;
119
120#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
121#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
122#define GROWL_AUTO_ADD          @"Torrent Auto Added"
123#define GROWL_AUTO_SPEED_LIMIT  @"Speed Limit Auto Changed"
124
125#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
126
127#define ROW_HEIGHT_REGULAR      62.0
128#define ROW_HEIGHT_SMALL        38.0
129#define WINDOW_REGULAR_WIDTH    468.0
130
131#define SEARCH_FILTER_MIN_WIDTH 48.0
132#define SEARCH_FILTER_MAX_WIDTH 95.0
133
134#define UPDATE_UI_SECONDS   1.0
135
136#define DOCK_SEEDING_TAG        101
137#define DOCK_DOWNLOADING_TAG    102
138
139#define TRANSFER_PLIST  @"/Library/Application Support/Transmission/Transfers.plist"
140
141#define WEBSITE_URL @"http://www.transmissionbt.com/"
142#define FORUM_URL   @"http://forum.transmissionbt.com/"
143#define TRAC_URL   @"http://trac.transmissionbt.com/"
144#define DONATE_URL  @"http://www.transmissionbt.com/donate.php"
145
146#define DONATE_NAG_TIME (60 * 60 * 24 * 7)
147
148static void altSpeedToggledCallback(tr_session * handle UNUSED, tr_bool active, tr_bool byUser, void * controller)
149{
150    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: [[NSNumber alloc] initWithBool: active], @"Active",
151                                [[NSNumber alloc] initWithBool: byUser], @"ByUser", nil];
152    [(Controller *)controller performSelectorOnMainThread: @selector(altSpeedToggledCallbackIsLimited:)
153        withObject: dict waitUntilDone: NO];
154}
155
156static tr_rpc_callback_status rpcCallback(tr_session * handle UNUSED, tr_rpc_callback_type type, struct tr_torrent * torrentStruct, void * controller)
157{
158    [(Controller *)controller rpcCallback: type forTorrentStruct: torrentStruct];
159    return TR_RPC_NOREMOVE; //we'll do the remove manually
160}
161
162static void sleepCallback(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
163{
164    [(Controller *)controller sleepCallback: messageType argument: messageArgument];
165}
166
167@implementation Controller
168
169+ (void) initialize
170{
171    //make sure another Transmission.app isn't running already
172    BOOL othersRunning = NO;
173   
174    #warning enable when 10.6-only
175    /*if ([NSApp isOnSnowLeopardOrBetter])
176    {
177        NSArray * apps = [NSRunningApplication runningApplicationsWithBundleIdentifier: [[NSBundle mainBundle] bundleIdentifier]];
178        othersRunning = [apps count] > 1;
179    }
180    else*/
181    {
182        NSString * bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
183        const int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
184
185        for (NSDictionary * dic in [[NSWorkspace sharedWorkspace] launchedApplications])
186        {
187            if ([[dic objectForKey: @"NSApplicationBundleIdentifier"] isEqualToString: bundleIdentifier]
188                    && [[dic objectForKey: @"NSApplicationProcessIdentifier"] intValue] != processIdentifier)
189                othersRunning = YES;
190        }
191    }
192   
193    if (othersRunning)
194    {
195        NSAlert * alert = [[NSAlert alloc] init];
196        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Transmission already running alert -> button")];
197        [alert setMessageText: NSLocalizedString(@"Transmission is already running.",
198                                                "Transmission already running alert -> title")];
199        [alert setInformativeText: NSLocalizedString(@"There is already a copy of Transmission running. "
200            "This copy cannot be opened until that instance is quit.", "Transmission already running alert -> message")];
201        [alert setAlertStyle: NSCriticalAlertStyle];
202       
203        [alert runModal];
204        [alert release];
205       
206        //kill ourselves right away
207        exit(0);
208    }
209   
210    [[NSUserDefaults standardUserDefaults] registerDefaults: [NSDictionary dictionaryWithContentsOfFile:
211        [[NSBundle mainBundle] pathForResource: @"Defaults" ofType: @"plist"]]];
212   
213    //set custom value transformers
214    ExpandedPathToPathTransformer * pathTransformer = [[[ExpandedPathToPathTransformer alloc] init] autorelease];
215    [NSValueTransformer setValueTransformer: pathTransformer forName: @"ExpandedPathToPathTransformer"];
216   
217    ExpandedPathToIconTransformer * iconTransformer = [[[ExpandedPathToIconTransformer alloc] init] autorelease];
218    [NSValueTransformer setValueTransformer: iconTransformer forName: @"ExpandedPathToIconTransformer"];
219   
220    //cover our asses
221    if ([[NSUserDefaults standardUserDefaults] boolForKey: @"WarningLegal"])
222    {
223        NSAlert * alert = [[NSAlert alloc] init];
224        [alert addButtonWithTitle: NSLocalizedString(@"I Accept", "Legal alert -> button")];
225        [alert addButtonWithTitle: NSLocalizedString(@"Quit", "Legal alert -> button")];
226        [alert setMessageText: NSLocalizedString(@"Hear ye, hear ye!", "Legal alert -> title")];
227        [alert setInformativeText: [NSString stringWithFormat: @"%@\n\n%@",
228            NSLocalizedString(@"Transmission is a file-sharing program. When you run a torrent, its data will"
229            " be made available to others by means of upload."
230            " And of course, any content you choose to share is your sole responsibility.", "Legal alert -> message"),
231            NSLocalizedString(@"You probably knew this already, so we won't tell you again.", "Legal alert -> message")]];
232        [alert setAlertStyle: NSInformationalAlertStyle];
233       
234        if ([alert runModal] == NSAlertSecondButtonReturn)
235            exit(0);
236        [alert release];
237       
238        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningLegal"];
239    }
240}
241
242- (id) init
243{
244    if ((self = [super init]))
245    {
246        fDefaults = [NSUserDefaults standardUserDefaults];
247       
248        //checks for old version speeds of -1
249        if ([fDefaults integerForKey: @"UploadLimit"] < 0)
250        {
251            [fDefaults removeObjectForKey: @"UploadLimit"];
252            [fDefaults setBool: NO forKey: @"CheckUpload"];
253        }
254        if ([fDefaults integerForKey: @"DownloadLimit"] < 0)
255        {
256            [fDefaults removeObjectForKey: @"DownloadLimit"];
257            [fDefaults setBool: NO forKey: @"CheckDownload"];
258        }
259       
260        tr_benc settings;
261        tr_bencInitDict(&settings, 34);
262        tr_sessionGetDefaultSettings(&settings);
263       
264        const BOOL usesSpeedLimitSched = [fDefaults boolForKey: @"SpeedLimitAuto"];
265        if (!usesSpeedLimitSched)
266            tr_bencDictAddBool(&settings, TR_PREFS_KEY_ALT_SPEED_ENABLED, [fDefaults boolForKey: @"SpeedLimit"]);
267       
268        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_UP, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]);
269        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_DOWN, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]);
270       
271        tr_bencDictAddBool(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_ENABLED, [fDefaults boolForKey: @"SpeedLimitAuto"]);
272        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_BEGIN, [PrefsController dateToTimeSum:
273                                                                            [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]]);
274        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_END, [PrefsController dateToTimeSum:
275                                                                            [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]]);
276        tr_bencDictAddInt(&settings, TR_PREFS_KEY_ALT_SPEED_TIME_DAY, [fDefaults integerForKey: @"SpeedLimitAutoDay"]);
277       
278        tr_bencDictAddInt(&settings, TR_PREFS_KEY_DSPEED, [fDefaults integerForKey: @"DownloadLimit"]);
279        tr_bencDictAddBool(&settings, TR_PREFS_KEY_DSPEED_ENABLED, [fDefaults boolForKey: @"CheckDownload"]);
280        tr_bencDictAddInt(&settings, TR_PREFS_KEY_USPEED, [fDefaults integerForKey: @"UploadLimit"]);
281        tr_bencDictAddBool(&settings, TR_PREFS_KEY_USPEED_ENABLED, [fDefaults boolForKey: @"CheckUpload"]);
282       
283        tr_bencDictAddBool(&settings, TR_PREFS_KEY_BLOCKLIST_ENABLED, [fDefaults boolForKey: @"Blocklist"]);
284        tr_bencDictAddBool(&settings, TR_PREFS_KEY_DHT_ENABLED, [fDefaults boolForKey: @"DHTGlobal"]);
285        tr_bencDictAddStr(&settings, TR_PREFS_KEY_DOWNLOAD_DIR, [[[fDefaults stringForKey: @"DownloadFolder"]
286                                                                    stringByExpandingTildeInPath] UTF8String]);
287       
288        tr_bencDictAddInt(&settings, TR_PREFS_KEY_MSGLEVEL, [fDefaults integerForKey: @"MessageLevel"]);
289        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_GLOBAL, [fDefaults integerForKey: @"PeersTotal"]);
290        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_LIMIT_TORRENT, [fDefaults integerForKey: @"PeersTorrent"]);
291       
292        const BOOL randomPort = [fDefaults boolForKey: @"RandomPort"];
293        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PEER_PORT_RANDOM_ON_START, randomPort);
294        if (!randomPort)
295            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_PORT, [fDefaults integerForKey: @"BindPort"]);
296       
297        //hidden pref
298        if ([fDefaults objectForKey: @"PeerSocketTOS"])
299            tr_bencDictAddInt(&settings, TR_PREFS_KEY_PEER_SOCKET_TOS, [fDefaults integerForKey: @"PeerSocketTOS"]);
300       
301        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PEX_ENABLED, [fDefaults boolForKey: @"PEXGlobal"]);
302        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PORT_FORWARDING, [fDefaults boolForKey: @"NatTraversal"]);
303        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PROXY_AUTH_ENABLED, [fDefaults boolForKey: @"ProxyAuthorize"]);
304        tr_bencDictAddBool(&settings, TR_PREFS_KEY_PROXY_ENABLED, [fDefaults boolForKey: @"Proxy"]);
305        tr_bencDictAddInt(&settings, TR_PREFS_KEY_PROXY_PORT, [fDefaults integerForKey: @"ProxyPort"]);
306        tr_bencDictAddStr(&settings, TR_PREFS_KEY_PROXY, [[fDefaults stringForKey: @"ProxyAddress"] UTF8String]);
307        tr_bencDictAddStr(&settings, TR_PREFS_KEY_PROXY_USERNAME,  [[fDefaults stringForKey: @"ProxyUsername"] UTF8String]);
308        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_AUTH_REQUIRED,  [fDefaults boolForKey: @"RPCAuthorize"]);
309        tr_bencDictAddReal(&settings, TR_PREFS_KEY_RATIO, [fDefaults floatForKey: @"RatioLimit"]);
310        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RATIO_ENABLED, [fDefaults boolForKey: @"RatioCheck"]);
311        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_ENABLED,  [fDefaults boolForKey: @"RPC"]);
312        tr_bencDictAddInt(&settings, TR_PREFS_KEY_RPC_PORT,  [fDefaults integerForKey: @"RPCPort"]);
313        tr_bencDictAddStr(&settings, TR_PREFS_KEY_RPC_USERNAME,  [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
314        tr_bencDictAddBool(&settings, TR_PREFS_KEY_RPC_WHITELIST_ENABLED,  [fDefaults boolForKey: @"RPCUseWhitelist"]);
315       
316        fLib = tr_sessionInit("macosx", tr_getDefaultConfigDir("Transmission"), YES, &settings);
317        tr_bencFree(&settings);
318       
319        [NSApp setDelegate: self];
320       
321        fTorrents = [[NSMutableArray alloc] init];
322        fDisplayedTorrents = [[NSMutableArray alloc] init];
323       
324        fMessageController = [[MessageWindowController alloc] init];
325        fInfoController = [[InfoWindowController alloc] init];
326       
327        [PrefsController setHandle: fLib];
328        fPrefsController = [[PrefsController alloc] init];
329       
330        fSoundPlaying = NO;
331       
332        tr_sessionSetAltSpeedFunc(fLib, altSpeedToggledCallback, self);
333        if (usesSpeedLimitSched)
334            [fDefaults setBool: tr_sessionUsesAltSpeed(fLib) forKey: @"SpeedLimit"];
335       
336        tr_sessionSetRPCCallback(fLib, rpcCallback, self);
337       
338        [GrowlApplicationBridge setGrowlDelegate: self];
339       
340        [[UKKQueue sharedFileWatcher] setDelegate: self];
341       
342        [[SUUpdater sharedUpdater] setDelegate: self];
343        fUpdateInProgress = NO;
344       
345        fPauseOnLaunch = (GetCurrentKeyModifiers() & (optionKey | rightOptionKey)) != 0;
346    }
347    return self;
348}
349
350- (void) awakeFromNib
351{
352    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"TRMainToolbar"];
353    [toolbar setDelegate: self];
354    [toolbar setAllowsUserCustomization: YES];
355    [toolbar setAutosavesConfiguration: YES];
356    [toolbar setDisplayMode: NSToolbarDisplayModeIconOnly];
357    [fWindow setToolbar: toolbar];
358    [toolbar release];
359   
360    [fWindow setDelegate: self]; //do manually to avoid placement issue
361   
362    [fWindow makeFirstResponder: fTableView];
363    [fWindow setExcludedFromWindowsMenu: YES];
364   
365    //set table size
366    if ([fDefaults boolForKey: @"SmallView"])
367        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
368   
369    //window min height
370    NSSize contentMinSize = [fWindow contentMinSize];
371    contentMinSize.height = [[fWindow contentView] frame].size.height - [[fTableView enclosingScrollView] frame].size.height
372                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
373    [fWindow setContentMinSize: contentMinSize];
374    [fWindow setContentBorderThickness: [[fTableView enclosingScrollView] frame].origin.y forEdge: NSMinYEdge];
375       
376    [[fTotalTorrentsField cell] setBackgroundStyle: NSBackgroundStyleRaised];
377   
378    [self updateGroupsFilterButton];
379   
380    //set up filter bar
381    NSView * contentView = [fWindow contentView];
382    NSSize windowSize = [contentView convertSize: [fWindow frame].size fromView: nil];
383    [fFilterBar setHidden: YES];
384   
385    NSRect filterBarFrame = [fFilterBar frame];
386    filterBarFrame.size.width = windowSize.width;
387    [fFilterBar setFrame: filterBarFrame];
388   
389    [contentView addSubview: fFilterBar];
390    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
391
392    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
393   
394    //set up status bar
395    [fStatusBar setHidden: YES];
396   
397    [self updateSpeedFieldsToolTips];
398   
399    NSRect statusBarFrame = [fStatusBar frame];
400    statusBarFrame.size.width = windowSize.width;
401    [fStatusBar setFrame: statusBarFrame];
402   
403    [contentView addSubview: fStatusBar];
404    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
405    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
406   
407    [fActionButton setToolTip: NSLocalizedString(@"Shortcuts for changing global settings.",
408                                "Main window -> 1st bottom left button (action) tooltip")];
409    [fSpeedLimitButton setToolTip: NSLocalizedString(@"Speed Limit overrides the total bandwidth limits with its own limits.",
410                                "Main window -> 2nd bottom left button (turtle) tooltip")];
411   
412    [fTableView registerForDraggedTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE]];
413    [fWindow registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType, NSURLPboardType, nil]];
414
415    //register for sleep notifications
416    IONotificationPortRef notify;
417    io_object_t iterator;
418    if ((fRootPort = IORegisterForSystemPower(self, & notify, sleepCallback, &iterator)))
419        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify), kCFRunLoopCommonModes);
420    else
421        NSLog(@"Could not IORegisterForSystemPower");
422   
423    //load previous transfers
424    NSArray * history = [[NSArray alloc] initWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST]];
425   
426    //old version saved transfer info in prefs file
427    if (!history)
428    {
429        if ((history = [fDefaults arrayForKey: @"History"]))
430        {
431            [history retain];
432            [fDefaults removeObjectForKey: @"History"];
433        }
434    }
435   
436    if (history)
437    {
438        for (NSDictionary * historyItem in history)
439        {
440            Torrent * torrent;
441            if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib forcePause: fPauseOnLaunch]))
442            {
443                [fTorrents addObject: torrent];
444                [torrent release];
445            }
446        }
447        [history release];
448    }
449   
450    //set filter
451    NSString * filterType = [fDefaults stringForKey: @"Filter"];
452   
453    NSButton * currentFilterButton;
454    if ([filterType isEqualToString: FILTER_ACTIVE])
455        currentFilterButton = fActiveFilterButton;
456    else if ([filterType isEqualToString: FILTER_PAUSE])
457        currentFilterButton = fPauseFilterButton;
458    else if ([filterType isEqualToString: FILTER_SEED])
459        currentFilterButton = fSeedFilterButton;
460    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
461        currentFilterButton = fDownloadFilterButton;
462    else
463    {
464        //safety
465        if (![filterType isEqualToString: FILTER_NONE])
466            [fDefaults setObject: FILTER_NONE forKey: @"Filter"];
467        currentFilterButton = fNoFilterButton;
468    }
469    [currentFilterButton setState: NSOnState];
470   
471    //set filter search type
472    NSString * filterSearchType = [fDefaults stringForKey: @"FilterSearchType"];
473   
474    NSMenu * filterSearchMenu = [[fSearchFilterField cell] searchMenuTemplate];
475    NSString * filterSearchTypeTitle;
476    if ([filterSearchType isEqualToString: FILTER_TYPE_TRACKER])
477        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_TRACKER] title];
478    else
479    {
480        //safety
481        if (![filterType isEqualToString: FILTER_TYPE_NAME])
482            [fDefaults setObject: FILTER_TYPE_NAME forKey: @"FilterSearchType"];
483        filterSearchTypeTitle = [[filterSearchMenu itemWithTag: FILTER_TYPE_TAG_NAME] title];
484    }
485    [[fSearchFilterField cell] setPlaceholderString: filterSearchTypeTitle];
486   
487    fBadger = [[Badger alloc] initWithLib: fLib];
488   
489    //observe notifications
490    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
491   
492    [nc addObserver: self selector: @selector(updateUI)
493                    name: @"UpdateUI" object: nil];
494   
495    [nc addObserver: self selector: @selector(torrentFinishedDownloading:)
496                    name: @"TorrentFinishedDownloading" object: nil];
497   
498    [nc addObserver: self selector: @selector(torrentRestartedDownloading:)
499                    name: @"TorrentRestartedDownloading" object: nil];
500   
501    //avoids need of setting delegate
502    [nc addObserver: self selector: @selector(torrentTableViewSelectionDidChange:)
503                    name: NSOutlineViewSelectionDidChangeNotification object: fTableView];
504   
505    [nc addObserver: self selector: @selector(changeAutoImport)
506                    name: @"AutoImportSettingChange" object: nil];
507   
508    [nc addObserver: self selector: @selector(setWindowSizeToFit)
509                    name: @"AutoSizeSettingChange" object: nil];
510   
511    [nc addObserver: self selector: @selector(updateForExpandCollape)
512                    name: @"OutlineExpandCollapse" object: nil];
513   
514    [nc addObserver: fWindow selector: @selector(makeKeyWindow)
515                    name: @"MakeWindowKey" object: nil];
516   
517    //check if torrent should now start
518    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
519                    name: @"TorrentStoppedForRatio" object: nil];
520   
521    [nc addObserver: self selector: @selector(updateTorrentsInQueue)
522                    name: @"UpdateQueue" object: nil];
523   
524    //open newly created torrent file
525    [nc addObserver: self selector: @selector(beginCreateFile:)
526                    name: @"BeginCreateTorrentFile" object: nil];
527   
528    //open newly created torrent file
529    [nc addObserver: self selector: @selector(openCreatedFile:)
530                    name: @"OpenCreatedTorrentFile" object: nil];
531   
532    //update when groups change
533    [nc addObserver: self selector: @selector(updateGroupsFilters:)
534                    name: @"UpdateGroups" object: nil];
535   
536    //update when speed limits are changed
537    [nc addObserver: self selector: @selector(updateSpeedFieldsToolTips)
538                    name: @"SpeedLimitUpdate" object: nil];
539
540    //timer to update the interface every second
541    [self updateUI];
542    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_UI_SECONDS target: self
543                selector: @selector(updateUI) userInfo: nil repeats: YES];
544    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
545    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
546   
547    [self applyFilter: nil];
548   
549    [fWindow makeKeyAndOrderFront: nil];
550   
551    if ([fDefaults boolForKey: @"InfoVisible"])
552        [self showInfo: nil];
553}
554
555- (void) applicationDidFinishLaunching: (NSNotification *) notification
556{
557    [NSApp setServicesProvider: self];
558   
559    //register for dock icon drags
560    [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self andSelector: @selector(handleOpenContentsEvent:replyEvent:)
561        forEventClass: kCoreEventClass andEventID: kAEOpenContents];
562   
563    //auto importing
564    [self checkAutoImportDirectory];
565   
566    //registering the Web UI to Bonjour
567    if ([fDefaults boolForKey: @"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"])
568        [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]];
569   
570    //shamelessly ask for donations
571    if ([fDefaults boolForKey: @"WarningDonate"])
572    {
573        tr_session_stats stats;
574        tr_sessionGetCumulativeStats(fLib, &stats);
575        const BOOL firstLaunch = stats.sessionCount <= 1;
576       
577        NSDate * lastDonateDate = [fDefaults objectForKey: @"DonateAskDate"];
578        const BOOL timePassed = !lastDonateDate || (-1 * [lastDonateDate timeIntervalSinceNow]) >= DONATE_NAG_TIME;
579       
580        if (!firstLaunch && timePassed)
581        {
582            NSAlert * alert = [[NSAlert alloc] init];
583            [alert setMessageText: NSLocalizedString(@"Support open-source indie software", "Donation beg -> title")];
584           
585            NSString * donateMessage = [NSString stringWithFormat: @"%@\n\n%@",
586                NSLocalizedString(@"Transmission is a full-featured torrent application."
587                    " A lot of time and effort have gone into development, coding, and refinement."
588                    " If you enjoy using it, please consider showing your love with a donation.", "Donation beg -> message"),
589                NSLocalizedString(@"Donate or not, there will be no difference to your torrenting experience.", "Donation beg -> message")];
590           
591            [alert setInformativeText: donateMessage];
592            [alert setAlertStyle: NSInformationalAlertStyle];
593           
594            [alert addButtonWithTitle: [NSLocalizedString(@"Donate", "Donation beg -> button") stringByAppendingEllipsis]];
595            NSButton * noDonateButton = [alert addButtonWithTitle: NSLocalizedString(@"Nope", "Donation beg -> button")];
596            [noDonateButton setKeyEquivalent: @"\e"]; //escape key
597           
598            const BOOL allowNeverAgain = lastDonateDate != nil; //hide the "don't show again" check the first time - give them time to try the app
599            [alert setShowsSuppressionButton: allowNeverAgain];
600            if (allowNeverAgain)
601                [[alert suppressionButton] setTitle: NSLocalizedString(@"Don't bug me about this ever again.", "Donation beg -> button")];
602           
603            const NSInteger donateResult = [alert runModal];
604            if (donateResult == NSAlertFirstButtonReturn)
605                [self linkDonate: self];
606           
607            if (allowNeverAgain)
608                [fDefaults setBool: ([[alert suppressionButton] state] != NSOnState) forKey: @"WarningDonate"];
609           
610            [alert release];
611           
612            [fDefaults setObject: [NSDate date] forKey: @"DonateAskDate"];
613        }
614    }
615}
616
617- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
618{
619    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
620        [fWindow makeKeyAndOrderFront: nil];
621    return NO;
622}
623
624- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
625{
626    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
627    {
628        NSInteger active = 0, downloading = 0;
629        for (Torrent * torrent  in fTorrents)
630            if ([torrent isActive] && ![torrent isStalled])
631            {
632                active++;
633                if (![torrent allDownloaded])
634                    downloading++;
635            }
636       
637        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
638        {
639            NSString * message = active == 1
640                ? NSLocalizedString(@"There is an active transfer that will be paused on quit."
641                    " The transfer will automatically resume on the next launch.", "Confirm Quit panel -> message")
642                : [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers that will be paused on quit."
643                    " The transfers will automatically resume on the next launch.", "Confirm Quit panel -> message"), active];
644
645            NSBeginAlertSheet(NSLocalizedString(@"Are you sure you want to quit?", "Confirm Quit panel -> title"),
646                                NSLocalizedString(@"Quit", "Confirm Quit panel -> button"),
647                                NSLocalizedString(@"Cancel", "Confirm Quit panel -> button"), nil, fWindow, self,
648                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
649            return NSTerminateLater;
650        }
651    }
652   
653    return NSTerminateNow;
654}
655
656- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
657{
658    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
659}
660
661- (void) applicationWillTerminate: (NSNotification *) notification
662{
663    //stop the Bonjour service
664    [[BonjourController defaultController] stop];
665
666    //stop blocklist download
667    if ([BlocklistDownloader isRunning])
668        [[BlocklistDownloader downloader] cancelDownload];
669   
670    //stop timers and notification checking
671    [[NSNotificationCenter defaultCenter] removeObserver: self];
672   
673    [fTimer invalidate];
674   
675    if (fAutoImportTimer)
676    {   
677        if ([fAutoImportTimer isValid])
678            [fAutoImportTimer invalidate];
679        [fAutoImportTimer release];
680    }
681   
682    [fBadger setQuitting];
683   
684    //remove all torrent downloads
685    if (fPendingTorrentDownloads)
686    {
687        for (NSDictionary * downloadDict in fPendingTorrentDownloads)
688        {
689            NSURLDownload * download = [downloadDict objectForKey: @"Download"];
690            [download cancel];
691            [download release];
692        }
693        [fPendingTorrentDownloads removeAllObjects];
694    }
695   
696    //remember window states and close all windows
697    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
698   
699    const BOOL quickLookOpen = [NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists]
700                                && [[QLPreviewPanelSL sharedPreviewPanel] isVisible];
701    for (NSWindow * window in [NSApp windows])
702    {
703        if (!quickLookOpen || window != [QLPreviewPanelSL sharedPreviewPanel]) //hide quicklook window last to avoid animation
704            [window orderOut: nil];
705    }
706   
707    if (quickLookOpen)
708    {
709        [[QLPreviewPanelSL sharedPreviewPanel] updateController];
710        [[QLPreviewPanelSL sharedPreviewPanel] orderOut: nil];
711    }
712   
713    [self showStatusBar: NO animate: NO];
714    [self showFilterBar: NO animate: NO];
715   
716    //save history
717    [self updateTorrentHistory];
718    [fTableView saveCollapsedGroups];
719   
720    //remaining calls the same as dealloc
721    [fInfoController release];
722    [fMessageController release];
723    [fPrefsController release];
724   
725    [fTorrents release];
726    [fDisplayedTorrents release];
727   
728    [fOverlayWindow release];
729    [fBadger release];
730   
731    [fAutoImportedNames release];
732    [fPendingTorrentDownloads release];
733   
734    //complete cleanup
735    tr_sessionClose(fLib);
736}
737
738- (void) handleOpenContentsEvent: (NSAppleEventDescriptor *) event replyEvent: (NSAppleEventDescriptor *) replyEvent
739{
740    NSString * urlString = nil;
741
742    NSAppleEventDescriptor * directObject = [event paramDescriptorForKeyword: keyDirectObject];
743    if ([directObject descriptorType] == typeAEList)
744    {
745        for (NSUInteger i = 1; i <= [directObject numberOfItems]; i++)
746            if ((urlString = [[directObject descriptorAtIndex: i] stringValue]))
747                break;
748    }
749    else
750        urlString = [directObject stringValue];
751   
752    if (urlString)
753        [self openURL: [NSURL URLWithString: urlString]];
754}
755
756- (void) download: (NSURLDownload *) download decideDestinationWithSuggestedFilename: (NSString *) suggestedName
757{
758    if ([[suggestedName pathExtension] caseInsensitiveCompare: @"torrent"] != NSOrderedSame)
759    {
760        [download cancel];
761       
762        NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Download not a torrent -> title"),
763            [NSString stringWithFormat: NSLocalizedString(@"It appears that the file \"%@\" from %@ is not a torrent file.",
764            "Download not a torrent -> message"), suggestedName,
765            [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]],
766            NSLocalizedString(@"OK", "Download not a torrent -> button"), nil, nil);
767       
768        [download release];
769    }
770    else
771        [download setDestination: [NSTemporaryDirectory() stringByAppendingPathComponent: [suggestedName lastPathComponent]]
772                    allowOverwrite: NO];
773}
774
775-(void) download: (NSURLDownload *) download didCreateDestination: (NSString *) path
776{
777    if (!fPendingTorrentDownloads)
778        fPendingTorrentDownloads = [[NSMutableDictionary alloc] init];
779   
780    [fPendingTorrentDownloads setObject: [NSDictionary dictionaryWithObjectsAndKeys:
781                    path, @"Path", download, @"Download", nil] forKey: [[download request] URL]];
782}
783
784- (void) download: (NSURLDownload *) download didFailWithError: (NSError *) error
785{
786    NSRunAlertPanel(NSLocalizedString(@"Torrent download failed", "Torrent download error -> title"),
787        [NSString stringWithFormat: NSLocalizedString(@"The torrent could not be downloaded from %@: %@.",
788        "Torrent download failed -> message"),
789        [[[[download request] URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
790        [error localizedDescription]], NSLocalizedString(@"OK", "Torrent download failed -> button"), nil, nil);
791   
792    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
793    if ([fPendingTorrentDownloads count] == 0)
794    {
795        [fPendingTorrentDownloads release];
796        fPendingTorrentDownloads = nil;
797    }
798   
799    [download release];
800}
801
802- (void) downloadDidFinish: (NSURLDownload *) download
803{
804    NSString * path = [[fPendingTorrentDownloads objectForKey: [[download request] URL]] objectForKey: @"Path"];
805   
806    [self openFiles: [NSArray arrayWithObject: path] addType: ADD_URL forcePath: nil];
807   
808    //delete the torrent file after opening
809    [[NSFileManager defaultManager] removeItemAtPath: path error: NULL];
810   
811    [fPendingTorrentDownloads removeObjectForKey: [[download request] URL]];
812    if ([fPendingTorrentDownloads count] == 0)
813    {
814        [fPendingTorrentDownloads release];
815        fPendingTorrentDownloads = nil;
816    }
817   
818    [download release];
819}
820
821- (void) application: (NSApplication *) app openFiles: (NSArray *) filenames
822{
823    [self openFiles: filenames addType: ADD_MANUAL forcePath: nil];
824}
825
826- (void) openFiles: (NSArray *) filenames addType: (addType) type forcePath: (NSString *) path
827{
828    #warning checks could probably be removed, since location is checked when starting
829    if (!path && [fDefaults boolForKey: @"UseIncompleteDownloadFolder"]
830        && access([[[fDefaults stringForKey: @"IncompleteDownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
831    {
832        NSOpenPanel * panel = [NSOpenPanel openPanel];
833       
834        [panel setPrompt: NSLocalizedString(@"Select", "Default incomplete folder cannot be used alert -> prompt")];
835        [panel setAllowsMultipleSelection: NO];
836        [panel setCanChooseFiles: NO];
837        [panel setCanChooseDirectories: YES];
838        [panel setCanCreateDirectories: YES];
839
840        [panel setMessage: NSLocalizedString(@"The incomplete folder cannot be used. Choose a new location or cancel for none.",
841                                        "Default incomplete folder cannot be used alert -> message")];
842       
843        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: filenames, @"Filenames",
844                                                        [NSNumber numberWithInt: type], @"AddType", nil];
845       
846        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
847                didEndSelector: @selector(incompleteChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
848        return;
849    }
850   
851    if (!path && [fDefaults boolForKey: @"DownloadLocationConstant"]
852        && access([[[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath] UTF8String], 0))
853    {
854        NSOpenPanel * panel = [NSOpenPanel openPanel];
855       
856        [panel setPrompt: NSLocalizedString(@"Select", "Default folder cannot be used alert -> prompt")];
857        [panel setAllowsMultipleSelection: NO];
858        [panel setCanChooseFiles: NO];
859        [panel setCanChooseDirectories: YES];
860        [panel setCanCreateDirectories: YES];
861
862        [panel setMessage: NSLocalizedString(@"The download folder cannot be used. Choose a new location.",
863                                        "Default folder cannot be used alert -> message")];
864       
865        NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: filenames, @"Filenames",
866                                                        [NSNumber numberWithInt: type], @"AddType", nil];
867       
868        [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: fWindow modalDelegate: self
869                didEndSelector: @selector(downloadChoiceClosed:returnCode:contextInfo:) contextInfo: dict];
870        return;
871    }
872   
873    BOOL deleteTorrentFile, canToggleDelete = NO;
874    switch (type)
875    {
876        case ADD_CREATED:
877            deleteTorrentFile = NO;
878            break;
879        case ADD_URL:
880            deleteTorrentFile = YES;
881            break;
882        default:
883            deleteTorrentFile = [fDefaults boolForKey: @"DeleteOriginalTorrent"];
884            canToggleDelete = YES;
885    }
886   
887    tr_info info;
888    for (NSString * torrentPath in filenames)
889    {
890        //ensure torrent doesn't already exist
891        tr_ctor * ctor = tr_ctorNew(fLib);
892        tr_ctorSetMetainfoFromFile(ctor, [torrentPath UTF8String]);
893        int result = tr_torrentParse(ctor, &info);
894        if (result != TR_PARSE_OK)
895        {
896            if (result == TR_PARSE_DUPLICATE)
897                [self duplicateOpenAlert: [NSString stringWithUTF8String: info.name]];
898            else if (result == TR_PARSE_ERR)
899            {
900                if (type != ADD_AUTO)
901                    [self invalidOpenAlert: [torrentPath lastPathComponent]];
902            }
903            else //this shouldn't happen
904                NSLog(@"Unknown error code (%d) when attempting to open \"%@\"", result, torrentPath);
905           
906            tr_ctorFree(ctor);
907            tr_metainfoFree(&info);
908            continue;
909        }
910       
911        tr_ctorFree(ctor);
912       
913        //determine download location
914        NSString * location;
915        BOOL lockDestination = NO; //don't override the location with a group location if it has a hardcoded path
916        if (path)
917        {
918            location = [path stringByExpandingTildeInPath];
919            lockDestination = YES;
920        }
921        else if ([fDefaults boolForKey: @"DownloadLocationConstant"])
922            location = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
923        else if (type != ADD_URL)
924            location = [torrentPath stringByDeletingLastPathComponent];
925        else
926            location = nil;
927       
928        //determine to show the options window
929        BOOL showWindow = type == ADD_SHOW_OPTIONS || ([fDefaults boolForKey: @"DownloadAsk"]
930                            && (info.isMultifile || ![fDefaults boolForKey: @"DownloadAskMulti"])
931                            && (type != ADD_AUTO || ![fDefaults boolForKey: @"DownloadAskManual"]));
932        tr_metainfoFree(&info);
933       
934        Torrent * torrent;
935        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath location: location
936                            deleteTorrentFile: showWindow ? NO : deleteTorrentFile lib: fLib]))
937            continue;
938       
939        //change the location if the group calls for it (this has to wait until after the torrent is create)
940        if (!lockDestination && [[GroupsController groups] usesCustomDownloadLocationForIndex: [torrent groupValue]])
941        {
942            location = [[GroupsController groups] customDownloadLocationForIndex: [torrent groupValue]];
943            [torrent changeDownloadFolder: location];
944        }
945       
946        //verify the data right away if it was newly created
947        if (type == ADD_CREATED)
948            [torrent resetCache];
949       
950        //add it to the "File -> Open Recent" menu
951        [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
952       
953        //show the add window or add directly
954        if (showWindow || !location)
955        {
956            AddWindowController * addController = [[AddWindowController alloc] initWithTorrent: torrent destination: location
957                                                    lockDestination: lockDestination controller: self torrentFile: torrentPath
958                                                    deleteTorrent: deleteTorrentFile canToggleDelete: canToggleDelete];
959            [addController showWindow: self];
960        }
961        else
962        {
963            [torrent setWaitToStart: [fDefaults boolForKey: @"AutoStartDownload"]];
964           
965            [torrent update];
966            [fTorrents addObject: torrent];
967            [torrent release];
968        }
969    }
970
971    [self updateTorrentsInQueue];
972}
973
974- (void) askOpenConfirmed: (AddWindowController *) addController add: (BOOL) add
975{
976    Torrent * torrent = [addController torrent];
977    [addController release];
978   
979    if (add)
980    {
981        [torrent update];
982        [fTorrents addObject: torrent];
983        [torrent release];
984       
985        [self updateTorrentsInQueue];
986    }
987    else
988    {
989        [torrent closeRemoveTorrent];
990        [torrent release];
991    }
992}
993
994- (void) openCreatedFile: (NSNotification *) notification
995{
996    NSDictionary * dict = [notification userInfo];
997    [self openFiles: [NSArray arrayWithObject: [dict objectForKey: @"File"]] addType: ADD_CREATED
998                        forcePath: [dict objectForKey: @"Path"]];
999    [dict release];
1000}
1001
1002- (void) incompleteChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
1003{
1004    if (code == NSOKButton)
1005        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
1006    else
1007        [fDefaults setBool: NO forKey: @"UseIncompleteDownloadFolder"];
1008   
1009    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
1010}
1011
1012- (void) downloadChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (NSDictionary *) dictionary
1013{
1014    if (code == NSOKButton)
1015    {
1016        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"DownloadFolder"];
1017        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
1018    }
1019    else
1020        [dictionary release];
1021}
1022
1023- (void) openFilesWithDict: (NSDictionary *) dictionary
1024{
1025    [self openFiles: [dictionary objectForKey: @"Filenames"] addType: [[dictionary objectForKey: @"AddType"] intValue] forcePath: nil];
1026   
1027    [dictionary release];
1028}
1029
1030//called on by applescript
1031- (void) open: (NSArray *) files
1032{
1033    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: files, @"Filenames",
1034                                [NSNumber numberWithInt: ADD_MANUAL], @"AddType", nil];
1035    [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dict waitUntilDone: NO];
1036}
1037
1038- (void) openShowSheet: (id) sender
1039{
1040    NSOpenPanel * panel = [NSOpenPanel openPanel];
1041
1042    [panel setAllowsMultipleSelection: YES];
1043    [panel setCanChooseFiles: YES];
1044    [panel setCanChooseDirectories: NO];
1045
1046    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]
1047        modalForWindow: fWindow modalDelegate: self didEndSelector: @selector(openSheetClosed:returnCode:contextInfo:)
1048        contextInfo: [NSNumber numberWithBool: sender == fOpenIgnoreDownloadFolder]];
1049}
1050
1051- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSNumber *) useOptions
1052{
1053    if (code == NSOKButton)
1054    {
1055        NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: [panel filenames], @"Filenames",
1056            [NSNumber numberWithInt: [useOptions boolValue] ? ADD_SHOW_OPTIONS : ADD_MANUAL], @"AddType", nil];
1057        [self performSelectorOnMainThread: @selector(openFilesWithDict:) withObject: dictionary waitUntilDone: NO];
1058    }
1059}
1060
1061- (void) invalidOpenAlert: (NSString *) filename
1062{
1063    if (![fDefaults boolForKey: @"WarningInvalidOpen"])
1064        return;
1065   
1066    NSAlert * alert = [[NSAlert alloc] init];
1067    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"\"%@\" is not a valid torrent file.",
1068                            "Open invalid alert -> title"), filename]];
1069    [alert setInformativeText:
1070            NSLocalizedString(@"The torrent file cannot be opened because it contains invalid data.",
1071                            "Open invalid alert -> message")];
1072    [alert setAlertStyle: NSWarningAlertStyle];
1073    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open invalid alert -> button")];
1074   
1075    [alert runModal];
1076    if ([[alert suppressionButton] state] == NSOnState)
1077        [fDefaults setBool: NO forKey: @"WarningInvalidOpen"];
1078    [alert release];
1079}
1080
1081- (void) duplicateOpenAlert: (NSString *) name
1082{
1083    if (![fDefaults boolForKey: @"WarningDuplicate"])
1084        return;
1085   
1086    NSAlert * alert = [[NSAlert alloc] init];
1087    [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"A transfer of \"%@\" already exists.",
1088                            "Open duplicate alert -> title"), name]];
1089    [alert setInformativeText:
1090            NSLocalizedString(@"The torrent file cannot be opened because it is a duplicate of an already added transfer.",
1091                            "Open duplicate alert -> message")];
1092    [alert setAlertStyle: NSWarningAlertStyle];
1093    [alert addButtonWithTitle: NSLocalizedString(@"OK", "Open duplicate alert -> button")];
1094    [alert setShowsSuppressionButton: YES];
1095   
1096    [alert runModal];
1097    if ([[alert suppressionButton] state])
1098        [fDefaults setBool: NO forKey: @"WarningDuplicate"];
1099    [alert release];
1100}
1101
1102- (void) openURL: (NSURL *) url
1103{
1104    [[NSURLDownload alloc] initWithRequest: [NSURLRequest requestWithURL: url] delegate: self];
1105}
1106
1107- (void) openURLShowSheet: (id) sender
1108{
1109    [NSApp beginSheet: fURLSheetWindow modalForWindow: fWindow modalDelegate: self
1110            didEndSelector: @selector(urlSheetDidEnd:returnCode:contextInfo:) contextInfo: nil];
1111}
1112
1113- (void) openURLEndSheet: (id) sender
1114{
1115    [fURLSheetWindow orderOut: sender];
1116    [NSApp endSheet: fURLSheetWindow returnCode: 1];
1117}
1118
1119- (void) openURLCancelEndSheet: (id) sender
1120{
1121    [fURLSheetWindow orderOut: sender];
1122    [NSApp endSheet: fURLSheetWindow returnCode: 0];
1123}
1124
1125- (void) controlTextDidChange: (NSNotification *) notification
1126{
1127    if ([notification object] != fURLSheetTextField)
1128        return;
1129   
1130    NSString * string = [fURLSheetTextField stringValue];
1131    BOOL enable = YES;
1132    if ([string isEqualToString: @""])
1133        enable = NO;
1134    else
1135    {
1136        NSRange prefixRange = [string rangeOfString: @"://"];
1137        if (prefixRange.location != NSNotFound && [string length] == NSMaxRange(prefixRange))
1138            enable = NO;
1139    }
1140   
1141    [fURLSheetOpenButton setEnabled: enable];
1142}
1143
1144- (void) urlSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
1145{
1146    [fURLSheetTextField selectText: self];
1147    if (returnCode != 1)
1148        return;
1149   
1150    NSString * urlString = [fURLSheetTextField stringValue];
1151    if ([urlString rangeOfString: @"://"].location == NSNotFound)
1152    {
1153        if ([urlString rangeOfString: @"."].location == NSNotFound)
1154        {
1155            NSInteger beforeCom;
1156            if ((beforeCom = [urlString rangeOfString: @"/"].location) != NSNotFound)
1157                urlString = [NSString stringWithFormat: @"http://www.%@.com/%@",
1158                                [urlString substringToIndex: beforeCom],
1159                                [urlString substringFromIndex: beforeCom + 1]];
1160            else
1161                urlString = [NSString stringWithFormat: @"http://www.%@.com/", urlString];
1162        }
1163        else
1164            urlString = [@"http://" stringByAppendingString: urlString];
1165    }
1166   
1167    NSURL * url = [NSURL URLWithString: urlString];
1168    [self performSelectorOnMainThread: @selector(openURL:) withObject: url waitUntilDone: NO];
1169}
1170
1171- (void) createFile: (id) sender
1172{
1173    [CreatorWindowController createTorrentFile: fLib];
1174}
1175
1176- (void) resumeSelectedTorrents: (id) sender
1177{
1178    [self resumeTorrents: [fTableView selectedTorrents]];
1179}
1180
1181- (void) resumeAllTorrents: (id) sender
1182{
1183    [self resumeTorrents: fTorrents];
1184}
1185
1186- (void) resumeTorrents: (NSArray *) torrents
1187{
1188    for (Torrent * torrent in torrents)
1189        [torrent setWaitToStart: YES];
1190   
1191    [self updateTorrentsInQueue];
1192}
1193
1194- (void) resumeSelectedTorrentsNoWait:  (id) sender
1195{
1196    [self resumeTorrentsNoWait: [fTableView selectedTorrents]];
1197}
1198
1199- (void) resumeWaitingTorrents: (id) sender
1200{
1201    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1202   
1203    for (Torrent * torrent in fTorrents)
1204        if (![torrent isActive] && [torrent waitingToStart])
1205            [torrents addObject: torrent];
1206   
1207    [self resumeTorrentsNoWait: torrents];
1208}
1209
1210- (void) resumeTorrentsNoWait: (NSArray *) torrents
1211{
1212    //iterate through instead of all at once to ensure no conflicts
1213    for (Torrent * torrent in torrents)
1214        [torrent startTransfer];
1215   
1216    [self updateUI];
1217    [self applyFilter: nil];
1218    [self updateTorrentHistory];
1219}
1220
1221- (void) stopSelectedTorrents: (id) sender
1222{
1223    [self stopTorrents: [fTableView selectedTorrents]];
1224}
1225
1226- (void) stopAllTorrents: (id) sender
1227{
1228    [self stopTorrents: fTorrents];
1229}
1230
1231- (void) stopTorrents: (NSArray *) torrents
1232{
1233    //don't want any of these starting then stopping
1234    for (Torrent * torrent in torrents)
1235        [torrent setWaitToStart: NO];
1236
1237    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
1238   
1239    [self updateUI];
1240    [self applyFilter: nil];
1241    [self updateTorrentHistory];
1242}
1243
1244- (void) removeTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1245{
1246    [torrents retain];
1247    NSInteger active = 0, downloading = 0;
1248
1249    if ([fDefaults boolForKey: @"CheckRemove"])
1250    {
1251        for (Torrent * torrent in torrents)
1252            if ([torrent isActive])
1253            {
1254                active++;
1255                if (![torrent isSeeding])
1256                    downloading++;
1257            }
1258
1259        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
1260        {
1261            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
1262                                    torrents, @"Torrents",
1263                                    [NSNumber numberWithBool: deleteData], @"DeleteData", nil];
1264           
1265            NSString * title, * message;
1266           
1267            const NSInteger selected = [torrents count];
1268            if (selected == 1)
1269            {
1270                NSString * torrentName = [[torrents objectAtIndex: 0] name];
1271               
1272                if (deleteData)
1273                    title = [NSString stringWithFormat:
1274                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list"
1275                                " and trash the data file?", "Removal confirm panel -> title"), torrentName];
1276                else
1277                    title = [NSString stringWithFormat:
1278                                NSLocalizedString(@"Are you sure you want to remove \"%@\" from the transfer list?",
1279                                "Removal confirm panel -> title"), torrentName];
1280               
1281                message = NSLocalizedString(@"This transfer is active."
1282                            " Once removed, continuing the transfer will require the torrent file.",
1283                            "Removal confirm panel -> message");
1284            }
1285            else
1286            {
1287                if (deleteData)
1288                    title = [NSString stringWithFormat:
1289                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list"
1290                                " and trash the data files?", "Removal confirm panel -> title"), selected];
1291                else
1292                    title = [NSString stringWithFormat:
1293                                NSLocalizedString(@"Are you sure you want to remove %d transfers from the transfer list?",
1294                                "Removal confirm panel -> title"), selected];
1295               
1296                if (selected == active)
1297                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d active transfers.",
1298                                "Removal confirm panel -> message part 1"), active];
1299                else
1300                    message = [NSString stringWithFormat: NSLocalizedString(@"There are %d transfers (%d active).",
1301                                "Removal confirm panel -> message part 1"), selected, active];
1302                message = [message stringByAppendingFormat: @" %@",
1303                                NSLocalizedString(@"Once removed, continuing the transfers will require the torrent files.",
1304                                "Removal confirm panel -> message part 2")];
1305            }
1306           
1307            NSBeginAlertSheet(title, NSLocalizedString(@"Remove", "Removal confirm panel -> button"),
1308                NSLocalizedString(@"Cancel", "Removal confirm panel -> button"), nil, fWindow, self,
1309                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
1310            return;
1311        }
1312    }
1313   
1314    [self confirmRemoveTorrents: torrents deleteData: deleteData];
1315}
1316
1317- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (NSInteger) returnCode contextInfo: (NSDictionary *) dict
1318{
1319    NSArray * torrents = [dict objectForKey: @"Torrents"];
1320    if (returnCode == NSAlertDefaultReturn)
1321        [self confirmRemoveTorrents: torrents deleteData: [[dict objectForKey: @"DeleteData"] boolValue]];
1322    else
1323        [torrents release];
1324   
1325    [dict release];
1326}
1327
1328- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData
1329{
1330    //don't want any of these starting then stopping
1331    for (Torrent * torrent in torrents)
1332        [torrent setWaitToStart: NO];
1333   
1334    [fTorrents removeObjectsInArray: torrents];
1335   
1336    for (Torrent * torrent in torrents)
1337    {
1338        //let's expand all groups that have removed items - they either don't exist anymore, are already expanded, or are collapsed (rpc)
1339        [fTableView removeCollapsedGroup: [torrent groupValue]];
1340       
1341        if (deleteData)
1342            [torrent trashData];
1343       
1344        [torrent closeRemoveTorrent];
1345    }
1346   
1347    [torrents release];
1348   
1349    [fTableView deselectAll: nil];
1350   
1351    [self updateTorrentsInQueue];
1352}
1353
1354- (void) removeNoDelete: (id) sender
1355{
1356    [self removeTorrents: [fTableView selectedTorrents] deleteData: NO];
1357}
1358
1359- (void) removeDeleteData: (id) sender
1360{
1361    [self removeTorrents: [fTableView selectedTorrents] deleteData: YES];
1362}
1363
1364- (void) moveDataFilesSelected: (id) sender
1365{
1366    [self moveDataFiles: [fTableView selectedTorrents]];
1367}
1368
1369- (void) moveDataFiles: (NSArray *) torrents
1370{
1371    NSOpenPanel * panel = [NSOpenPanel openPanel];
1372    [panel setPrompt: NSLocalizedString(@"Select", "Move torrent -> prompt")];
1373    [panel setAllowsMultipleSelection: NO];
1374    [panel setCanChooseFiles: NO];
1375    [panel setCanChooseDirectories: YES];
1376    [panel setCanCreateDirectories: YES];
1377   
1378    torrents = [torrents retain];
1379    NSInteger count = [torrents count];
1380    if (count == 1)
1381        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for \"%@\".",
1382                            "Move torrent -> select destination folder"), [[torrents objectAtIndex: 0] name]]];
1383    else
1384        [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the new folder for %d data files.",
1385                            "Move torrent -> select destination folder"), count]];
1386       
1387    [panel beginSheetForDirectory: nil file: nil modalForWindow: fWindow modalDelegate: self
1388        didEndSelector: @selector(moveDataFileChoiceClosed:returnCode:contextInfo:) contextInfo: torrents];
1389}
1390
1391- (void) moveDataFileChoiceClosed: (NSOpenPanel *) panel returnCode: (NSInteger) code contextInfo: (NSArray *) torrents
1392{
1393    if (code == NSOKButton)
1394    {
1395        for (Torrent * torrent in torrents)
1396            [torrent moveTorrentDataFileTo: [[panel filenames] objectAtIndex: 0]];
1397    }
1398   
1399    [torrents release];
1400}
1401
1402- (void) copyTorrentFiles: (id) sender
1403{
1404    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray: [fTableView selectedTorrents]]];
1405}
1406
1407- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
1408{
1409    if ([torrents count] <= 0)
1410    {
1411        [torrents release];
1412        return;
1413    }
1414
1415    Torrent * torrent = [torrents objectAtIndex: 0];
1416
1417    //warn user if torrent file can't be found
1418    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
1419    {
1420        NSAlert * alert = [[NSAlert alloc] init];
1421        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file copy alert -> button")];
1422        [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Copy of \"%@\" Cannot Be Created",
1423                                "Torrent file copy alert -> title"), [torrent name]]];
1424        [alert setInformativeText: [NSString stringWithFormat:
1425                NSLocalizedString(@"The torrent file (%@) cannot be found.", "Torrent file copy alert -> message"),
1426                                    [torrent torrentLocation]]];
1427        [alert setAlertStyle: NSWarningAlertStyle];
1428       
1429        [alert runModal];
1430        [alert release];
1431       
1432        [torrents removeObjectAtIndex: 0];
1433        [self copyTorrentFileForTorrents: torrents];
1434    }
1435    else
1436    {
1437        NSSavePanel * panel = [NSSavePanel savePanel];
1438        [panel setAllowedFileTypes: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]];
1439        [panel setCanSelectHiddenExtension: YES];
1440       
1441        [panel beginSheetForDirectory: nil file: [torrent name] modalForWindow: fWindow modalDelegate: self
1442            didEndSelector: @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
1443    }
1444}
1445
1446- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (NSMutableArray *) torrents
1447{
1448    //copy torrent to new location with name of data file
1449    if (code == NSOKButton)
1450        [[torrents objectAtIndex: 0] copyTorrentFileTo: [panel filename]];
1451   
1452    [torrents removeObjectAtIndex: 0];
1453    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:) withObject: torrents waitUntilDone: NO];
1454}
1455
1456- (void) revealFile: (id) sender
1457{
1458    NSArray * selected = [fTableView selectedTorrents];
1459    if ([NSApp isOnSnowLeopardOrBetter])
1460    {
1461        NSMutableArray * paths = [NSMutableArray arrayWithCapacity: [selected count]];
1462        for (Torrent * torrent in [fTableView selectedTorrents])
1463            [paths addObject: [NSURL fileURLWithPath: [torrent dataLocation]]];
1464       
1465        [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: paths];
1466    }
1467    else
1468    {
1469        for (Torrent * torrent in selected)
1470            [[NSWorkspace sharedWorkspace] selectFile: [torrent dataLocation] inFileViewerRootedAtPath: nil];
1471    }
1472}
1473
1474- (void) announceSelectedTorrents: (id) sender
1475{
1476    for (Torrent * torrent in [fTableView selectedTorrents])
1477    {
1478        if ([torrent canManualAnnounce])
1479            [torrent manualAnnounce];
1480    }
1481}
1482
1483- (void) verifySelectedTorrents: (id) sender
1484{
1485    [self verifyTorrents: [fTableView selectedTorrents]];
1486}
1487
1488- (void) verifyTorrents: (NSArray *) torrents
1489{
1490    for (Torrent * torrent in torrents)
1491        [torrent resetCache];
1492   
1493    [self applyFilter: nil];
1494}
1495
1496- (void) showPreferenceWindow: (id) sender
1497{
1498    NSWindow * window = [fPrefsController window];
1499    if (![window isVisible])
1500        [window center];
1501
1502    [window makeKeyAndOrderFront: nil];
1503}
1504
1505- (void) showAboutWindow: (id) sender
1506{
1507    [[AboutWindowController aboutController] showWindow: nil];
1508}
1509
1510- (void) showInfo: (id) sender
1511{
1512    if ([[fInfoController window] isVisible])
1513        [fInfoController close];
1514    else
1515    {
1516        [fInfoController updateInfoStats];
1517        [[fInfoController window] orderFront: nil];
1518    }
1519}
1520
1521- (void) resetInfo
1522{
1523    [fInfoController setInfoForTorrents: [fTableView selectedTorrents]];
1524   
1525    if ([NSApp isOnSnowLeopardOrBetter] && [QLPreviewPanelSL sharedPreviewPanelExists] && [[QLPreviewPanelSL sharedPreviewPanel] isVisible])
1526        [[QLPreviewPanelSL sharedPreviewPanel] reloadData];
1527}
1528
1529- (void) setInfoTab: (id) sender
1530{
1531    if (sender == fNextInfoTabItem)
1532        [fInfoController setNextTab];
1533    else
1534        [fInfoController setPreviousTab];
1535}
1536
1537- (void) showMessageWindow: (id) sender
1538{
1539    [fMessageController showWindow: nil];
1540}
1541
1542- (void) showStatsWindow: (id) sender
1543{
1544    [[StatsWindowController statsWindow: fLib] showWindow: nil];
1545}
1546
1547- (void) updateUI
1548{
1549    [fTorrents makeObjectsPerformSelector: @selector(update)];
1550   
1551    if (![NSApp isHidden])
1552    {
1553        if ([fWindow isVisible])
1554        {
1555            [self sortTorrents];
1556           
1557            //update status bar
1558            if (![fStatusBar isHidden])
1559            {
1560                //set rates
1561                [fTotalDLField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_DOWN)]];
1562                [fTotalULField setStringValue: [NSString stringForSpeed: tr_sessionGetPieceSpeed(fLib, TR_UP)]];
1563               
1564                //set status button text
1565                NSString * statusLabel = [fDefaults stringForKey: @"StatusLabel"], * statusString;
1566                BOOL total;
1567                if ((total = [statusLabel isEqualToString: STATUS_RATIO_TOTAL]) || [statusLabel isEqualToString: STATUS_RATIO_SESSION])
1568                {
1569                    tr_session_stats stats;
1570                    if (total)
1571                        tr_sessionGetCumulativeStats(fLib, &stats);
1572                    else
1573                        tr_sessionGetStats(fLib, &stats);
1574                   
1575                    statusString = [NSLocalizedString(@"Ratio", "status bar -> status label") stringByAppendingFormat: @": %@",
1576                                    [NSString stringForRatio: stats.ratio]];
1577                }
1578                else //STATUS_TRANSFER_TOTAL or STATUS_TRANSFER_SESSION
1579                {
1580                    total = [statusLabel isEqualToString: STATUS_TRANSFER_TOTAL];
1581                   
1582                    tr_session_stats stats;
1583                    if (total)
1584                        tr_sessionGetCumulativeStats(fLib, &stats);
1585                    else
1586                        tr_sessionGetStats(fLib, &stats);
1587                   
1588                    statusString = [NSString stringWithFormat: @"%@: %@  %@: %@",
1589                            NSLocalizedString(@"DL", "status bar -> status label"), [NSString stringForFileSize: stats.downloadedBytes],
1590                            NSLocalizedString(@"UL", "status bar -> status label"), [NSString stringForFileSize: stats.uploadedBytes]];
1591                }
1592               
1593                [fStatusButton setTitle: statusString];
1594                [self resizeStatusButton];
1595            }
1596        }
1597
1598        //update non-constant parts of info window
1599        if ([[fInfoController window] isVisible])
1600            [fInfoController updateInfoStats];
1601    }
1602   
1603    //badge dock
1604    [fBadger updateBadge];
1605}
1606
1607- (void) resizeStatusButton
1608{
1609    [fStatusButton sizeToFit];
1610   
1611    //width ends up being too long
1612    NSRect statusFrame = [fStatusButton frame];
1613    statusFrame.size.width -= 25.0;
1614   
1615    CGFloat difference = NSMaxX(statusFrame) + 5.0 - [fTotalDLImageView frame].origin.x;
1616    if (difference > 0)
1617        statusFrame.size.width -= difference;
1618   
1619    [fStatusButton setFrame: statusFrame];
1620}
1621
1622- (void) setBottomCountText: (BOOL) filtering
1623{
1624    NSString * totalTorrentsString;
1625    NSInteger totalCount = [fTorrents count];
1626    if (totalCount != 1)
1627        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Status bar transfer count"), totalCount];
1628    else
1629        totalTorrentsString = NSLocalizedString(@"1 transfer", "Status bar transfer count");
1630   
1631    if (filtering)
1632    {
1633        NSInteger count = [fTableView numberOfRows]; //have to factor in collapsed rows
1634        if (count > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
1635            count -= [fDisplayedTorrents count];
1636       
1637        totalTorrentsString = [NSString stringWithFormat: NSLocalizedString(@"%d of %@", "Status bar transfer count"),
1638                                count, totalTorrentsString];
1639    }
1640   
1641    [fTotalTorrentsField setStringValue: totalTorrentsString];
1642}
1643
1644- (void) updateSpeedFieldsToolTips
1645{
1646    NSString * uploadText, * downloadText;
1647   
1648    if ([fDefaults boolForKey: @"SpeedLimit"])
1649    {
1650        NSString * speedString = [NSString stringWithFormat: @"%@ (%@)", NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1651                                    NSLocalizedString(@"Speed Limit", "Status Bar -> speed tooltip")];
1652       
1653        uploadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]];
1654        downloadText = [NSString stringWithFormat: speedString, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]];
1655    }
1656    else
1657    {
1658        if ([fDefaults boolForKey: @"CheckUpload"])
1659            uploadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1660                            [fDefaults integerForKey: @"UploadLimit"]];
1661        else
1662            uploadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1663       
1664        if ([fDefaults boolForKey: @"CheckDownload"])
1665            downloadText = [NSString stringWithFormat: NSLocalizedString(@"%d KB/s", "Status Bar -> speed tooltip"),
1666                            [fDefaults integerForKey: @"DownloadLimit"]];
1667        else
1668            downloadText = NSLocalizedString(@"unlimited", "Status Bar -> speed tooltip");
1669    }
1670   
1671    uploadText = [NSLocalizedString(@"Total upload rate", "Status Bar -> speed tooltip")
1672                    stringByAppendingFormat: @": %@", uploadText];
1673    downloadText = [NSLocalizedString(@"Total download rate", "Status Bar -> speed tooltip")
1674                    stringByAppendingFormat: @": %@", downloadText];
1675   
1676    [fTotalULField setToolTip: uploadText];
1677    [fTotalDLField setToolTip: downloadText];
1678}
1679
1680- (void) updateTorrentsInQueue
1681{
1682    BOOL download = [fDefaults boolForKey: @"Queue"],
1683        seed = [fDefaults boolForKey: @"QueueSeed"];
1684   
1685    NSInteger desiredDownloadActive = [self numToStartFromQueue: YES],
1686        desiredSeedActive = [self numToStartFromQueue: NO];
1687   
1688    for (Torrent * torrent in fTorrents)
1689    {
1690        if (![torrent isActive] && ![torrent isChecking] && [torrent waitingToStart])
1691        {
1692            if (![torrent allDownloaded])
1693            {
1694                if (!download || desiredDownloadActive > 0)
1695                {
1696                    [torrent startTransfer];
1697                    if ([torrent isActive])
1698                        desiredDownloadActive--;
1699                    [torrent update];
1700                }
1701            }
1702            else
1703            {
1704                if (!seed || desiredSeedActive > 0)
1705                {
1706                    [torrent startTransfer];
1707                    if ([torrent isActive])
1708                        desiredSeedActive--;
1709                    [torrent update];
1710                }
1711            }
1712        }
1713    }
1714   
1715    [self updateUI];
1716    [self applyFilter: nil];
1717    [self updateTorrentHistory];
1718}
1719
1720- (NSInteger) numToStartFromQueue: (BOOL) downloadQueue
1721{
1722    if (![fDefaults boolForKey: downloadQueue ? @"Queue" : @"QueueSeed"])
1723        return 0;
1724   
1725    NSInteger desired = [fDefaults integerForKey: downloadQueue ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
1726       
1727    for (Torrent * torrent in fTorrents)
1728    {
1729        if ([torrent isChecking])
1730        {
1731            desired--;
1732            if (desired <= 0)
1733                return 0;
1734        }
1735        else if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
1736        {
1737            if ([torrent allDownloaded] != downloadQueue)
1738            {
1739                desired--;
1740                if (desired <= 0)
1741                    return 0;
1742            }
1743        }
1744        else;
1745    }
1746   
1747    return desired;
1748}
1749
1750- (void) torrentFinishedDownloading: (NSNotification *) notification
1751{
1752    Torrent * torrent = [notification object];
1753   
1754    if ([torrent isActive])
1755    {
1756        if (!fSoundPlaying && [fDefaults boolForKey: @"PlayDownloadSound"])
1757        {
1758            NSSound * sound;
1759            if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"DownloadSound"]]))
1760            {
1761                [sound setDelegate: self];
1762                fSoundPlaying = YES;
1763                [sound play];
1764            }
1765        }
1766       
1767        NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_DOWNLOAD_COMPLETE, @"Type",
1768                                        [torrent dataLocation] , @"Location", nil];
1769        [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Download Complete", "Growl notification title")
1770                                    description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE
1771                                    iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1772       
1773        if (![fWindow isMainWindow])
1774            [fBadger incrementCompleted];
1775       
1776        //bounce download stack
1777        [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"com.apple.DownloadFileFinished"
1778            object: [[torrent downloadFolder] stringByAppendingPathComponent: [torrent name]]];
1779       
1780        if ([fDefaults boolForKey: @"QueueSeed"] && [self numToStartFromQueue: NO] <= 0)
1781        {
1782            [torrent stopTransfer];
1783            [torrent setWaitToStart: YES];
1784        }
1785    }
1786   
1787    [self updateTorrentsInQueue];
1788}
1789
1790- (void) torrentRestartedDownloading: (NSNotification *) notification
1791{
1792    Torrent * torrent = [notification object];
1793    if ([torrent isActive])
1794    {
1795        if ([fDefaults boolForKey: @"Queue"] && [self numToStartFromQueue: YES] <= 0)
1796        {
1797            [torrent stopTransfer];
1798            [torrent setWaitToStart: YES];
1799        }
1800    }
1801   
1802    [self updateTorrentsInQueue];
1803}
1804
1805- (void) torrentStoppedForRatio: (NSNotification *) notification
1806{
1807    Torrent * torrent = [notification object];
1808   
1809    [self updateTorrentsInQueue];
1810   
1811    if ([[fTableView selectedTorrents] containsObject: torrent])
1812    {
1813        [fInfoController updateInfoStats];
1814        [fInfoController updateOptions];
1815    }
1816   
1817    if (!fSoundPlaying && [fDefaults boolForKey: @"PlaySeedingSound"])
1818    {
1819        NSSound * sound;
1820        if ((sound = [NSSound soundNamed: [fDefaults stringForKey: @"SeedingSound"]]))
1821        {
1822            [sound setDelegate: self];
1823            fSoundPlaying = YES;
1824            [sound play];
1825        }
1826    }
1827   
1828    NSDictionary * clickContext = [NSDictionary dictionaryWithObjectsAndKeys: GROWL_SEEDING_COMPLETE, @"Type",
1829                                    [torrent dataLocation], @"Location", nil];
1830    [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Seeding Complete", "Growl notification title")
1831                        description: [torrent name] notificationName: GROWL_SEEDING_COMPLETE
1832                        iconData: nil priority: 0 isSticky: NO clickContext: clickContext];
1833}
1834
1835- (void) updateTorrentHistory
1836{
1837    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
1838   
1839    for (Torrent * torrent in fTorrents)
1840        [history addObject: [torrent history]];
1841   
1842    [history writeToFile: [NSHomeDirectory() stringByAppendingPathComponent: TRANSFER_PLIST] atomically: YES];
1843}
1844
1845- (void) setSort: (id) sender
1846{
1847    NSString * sortType;
1848    switch ([sender tag])
1849    {
1850        case SORT_ORDER_TAG:
1851            sortType = SORT_ORDER;
1852            [fDefaults setBool: NO forKey: @"SortReverse"];
1853            break;
1854        case SORT_DATE_TAG:
1855            sortType = SORT_DATE;
1856            break;
1857        case SORT_NAME_TAG:
1858            sortType = SORT_NAME;
1859            break;
1860        case SORT_PROGRESS_TAG:
1861            sortType = SORT_PROGRESS;
1862            break;
1863        case SORT_STATE_TAG:
1864            sortType = SORT_STATE;
1865            break;
1866        case SORT_TRACKER_TAG:
1867            sortType = SORT_TRACKER;
1868            break;
1869        case SORT_ACTIVITY_TAG:
1870            sortType = SORT_ACTIVITY;
1871            break;
1872        default:
1873            return;
1874    }
1875   
1876    [fDefaults setObject: sortType forKey: @"Sort"];
1877    [self applyFilter: nil]; //better than calling sortTorrents because it will even apply to queue order
1878}
1879
1880- (void) setSortByGroup: (id) sender
1881{
1882    BOOL sortByGroup = ![fDefaults boolForKey: @"SortByGroup"];
1883    [fDefaults setBool: sortByGroup forKey: @"SortByGroup"];
1884   
1885    //expand all groups
1886    if (sortByGroup)
1887        [fTableView removeAllCollapsedGroups];
1888   
1889    [self applyFilter: nil];
1890}
1891
1892- (void) setSortReverse: (id) sender
1893{
1894    [fDefaults setBool: ![fDefaults boolForKey: @"SortReverse"] forKey: @"SortReverse"];
1895    [self sortTorrents];
1896}
1897
1898- (void) sortTorrents
1899{
1900    NSArray * selectedValues = [fTableView selectedValues];
1901   
1902    [self sortTorrentsIgnoreSelected]; //actually sort
1903   
1904    [fTableView selectValues: selectedValues];
1905}
1906
1907- (void) sortTorrentsIgnoreSelected
1908{
1909    NSString * sortType = [fDefaults stringForKey: @"Sort"];
1910   
1911    if (![sortType isEqualToString: SORT_ORDER])
1912    {
1913        const BOOL asc = ![fDefaults boolForKey: @"SortReverse"];
1914       
1915        NSArray * descriptors;
1916        NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: asc
1917                                                selector: @selector(compareFinder:)] autorelease];
1918       
1919        if ([sortType isEqualToString: SORT_STATE])
1920        {
1921            NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"stateSortKey" ascending: !asc] autorelease],
1922                            * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: !asc] autorelease],
1923                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: !asc] autorelease];
1924           
1925            descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor, ratioDescriptor,
1926                                                                nameDescriptor, nil];
1927        }
1928        else if ([sortType isEqualToString: SORT_PROGRESS])
1929        {
1930            NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progress" ascending: asc] autorelease],
1931                            * ratioProgressDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"progressStopRatio"
1932                                                            ascending: asc] autorelease],
1933                            * ratioDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"ratio" ascending: asc] autorelease];
1934           
1935            descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, ratioProgressDescriptor, ratioDescriptor,
1936                                                                nameDescriptor, nil];
1937        }
1938        #warning broken
1939        else if ([sortType isEqualToString: SORT_TRACKER])
1940        {
1941            NSSortDescriptor * trackerDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"trackerAddressAnnounce" ascending: asc
1942                                                    selector: @selector(localizedCaseInsensitiveCompare:)] autorelease];
1943           
1944            descriptors = [[NSArray alloc] initWithObjects: trackerDescriptor, nameDescriptor, nil];
1945        }
1946        else if ([sortType isEqualToString: SORT_ACTIVITY])
1947        {
1948            NSSortDescriptor * rateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"totalRate" ascending: !asc] autorelease];
1949            NSSortDescriptor * activityDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateActivityOrAdd" ascending: !asc]
1950                                                        autorelease];
1951           
1952            descriptors = [[NSArray alloc] initWithObjects: rateDescriptor, activityDescriptor, nameDescriptor, nil];
1953        }
1954        else if ([sortType isEqualToString: SORT_DATE])
1955        {
1956            NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"dateAdded" ascending: asc] autorelease];
1957       
1958            descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, nameDescriptor, nil];
1959        }
1960        else
1961            descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, nil];
1962       
1963        //actually sort
1964        if ([fDefaults boolForKey: @"SortByGroup"])
1965        {
1966            for (TorrentGroup * group in fDisplayedTorrents)
1967                [[group torrents] sortUsingDescriptors: descriptors];
1968        }
1969        else
1970            [fDisplayedTorrents sortUsingDescriptors: descriptors];
1971       
1972        [descriptors release];
1973    }
1974   
1975    [fTableView reloadData];
1976}
1977
1978- (void) applyFilter: (id) sender
1979{
1980    //get all the torrents in the table
1981    NSMutableArray * previousTorrents;
1982    if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
1983    {
1984        previousTorrents = [NSMutableArray array];
1985       
1986        for (TorrentGroup * group in fDisplayedTorrents)
1987            [previousTorrents addObjectsFromArray: [group torrents]];
1988    }
1989    else
1990        previousTorrents = fDisplayedTorrents;
1991   
1992    NSArray * selectedValues = [fTableView selectedValues];
1993   
1994    NSUInteger active = 0, downloading = 0, seeding = 0, paused = 0;
1995    NSString * filterType = [fDefaults stringForKey: @"Filter"];
1996    BOOL filterActive = NO, filterDownload = NO, filterSeed = NO, filterPause = NO, filterStatus = YES;
1997    if ([filterType isEqualToString: FILTER_ACTIVE])
1998        filterActive = YES;
1999    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2000        filterDownload = YES;
2001    else if ([filterType isEqualToString: FILTER_SEED])
2002        filterSeed = YES;
2003    else if ([filterType isEqualToString: FILTER_PAUSE])
2004        filterPause = YES;
2005    else
2006        filterStatus = NO;
2007   
2008    const NSInteger groupFilterValue = [fDefaults integerForKey: @"FilterGroup"];
2009    const BOOL filterGroup = groupFilterValue != GROUP_FILTER_ALL_TAG;
2010   
2011    NSString * searchString = [fSearchFilterField stringValue];
2012    const BOOL filterText = [searchString length] > 0,
2013            filterTracker = filterText && [[fDefaults stringForKey: @"FilterSearchType"] isEqualToString: FILTER_TYPE_TRACKER];
2014   
2015    NSMutableArray * allTorrents = [NSMutableArray arrayWithCapacity: [fTorrents count]];
2016   
2017    //get count of each type
2018    for (Torrent * torrent in fTorrents)
2019    {
2020        //check status
2021        if ([torrent isActive] && ![torrent isCheckingWaiting])
2022        {
2023            if ([torrent isSeeding])
2024            {
2025                seeding++;
2026                BOOL isActive = ![torrent isStalled];
2027                if (isActive)
2028                    active++;
2029               
2030                if (filterStatus && !((filterActive && isActive) || filterSeed))
2031                    continue;
2032            }
2033            else
2034            {
2035                downloading++;
2036                BOOL isActive = ![torrent isStalled];
2037                if (isActive)
2038                    active++;
2039               
2040                if (filterStatus && !((filterActive && isActive) || filterDownload))
2041                    continue;
2042            }
2043        }
2044        else
2045        {
2046            paused++;
2047            if (filterStatus && !filterPause)
2048                continue;
2049        }
2050       
2051        //checkGroup
2052        if (filterGroup)
2053            if ([torrent groupValue] != groupFilterValue)
2054                continue;
2055       
2056        //check text field
2057        if (filterText)
2058        {
2059            if (filterTracker)
2060            {
2061                BOOL removeTextField = YES;
2062                for (NSString * tracker in [torrent allTrackersFlat])
2063                {
2064                    if ([tracker rangeOfString: searchString options:
2065                            (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location != NSNotFound)
2066                    {
2067                        removeTextField = NO;
2068                        break;
2069                    }
2070                }
2071               
2072                if (removeTextField)
2073                    continue;
2074            }
2075            else
2076            {
2077                if ([[torrent name] rangeOfString: searchString options:
2078                        (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)].location == NSNotFound)
2079                    continue;
2080            }
2081        }
2082       
2083        [allTorrents addObject: torrent];
2084    }
2085   
2086    //set button tooltips
2087    [fNoFilterButton setCount: [fTorrents count]];
2088    [fActiveFilterButton setCount: active];
2089    [fDownloadFilterButton setCount: downloading];
2090    [fSeedFilterButton setCount: seeding];
2091    [fPauseFilterButton setCount: paused];
2092   
2093    //clear display cache for not-shown torrents
2094    [previousTorrents removeObjectsInArray: allTorrents];
2095    for (Torrent * torrent in previousTorrents)
2096        [torrent setPreviousFinishedPieces: nil];
2097   
2098    //place torrents into groups
2099    const BOOL groupRows = [fDefaults boolForKey: @"SortByGroup"];
2100    if (groupRows)
2101    {
2102        NSMutableArray * oldTorrentGroups = [NSMutableArray array];
2103        if ([fDisplayedTorrents count] > 0 && [[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [TorrentGroup class]])
2104            [oldTorrentGroups addObjectsFromArray: fDisplayedTorrents];
2105       
2106        [fDisplayedTorrents removeAllObjects];
2107       
2108        NSSortDescriptor * groupDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"groupOrderValue" ascending: YES] autorelease];
2109        [allTorrents sortUsingDescriptors: [NSArray arrayWithObject: groupDescriptor]];
2110       
2111        NSMutableArray * groupTorrents;
2112        NSInteger lastGroupValue = -2, currentOldGroupIndex = 0;
2113        for (Torrent * torrent in allTorrents)
2114        {
2115            NSInteger groupValue = [torrent groupValue];
2116            if (groupValue != lastGroupValue)
2117            {
2118                lastGroupValue = groupValue;
2119               
2120                TorrentGroup * group = nil;
2121               
2122                //try to see if the group already exists
2123                for (; currentOldGroupIndex < [oldTorrentGroups count]; currentOldGroupIndex++)
2124                {
2125                    TorrentGroup * currentGroup = [oldTorrentGroups objectAtIndex: currentOldGroupIndex];
2126                    const NSInteger currentGroupValue = [currentGroup groupIndex];
2127                    if (currentGroupValue == groupValue)
2128                    {
2129                        group = currentGroup;
2130                        [[currentGroup torrents] removeAllObjects];
2131                       
2132                        currentOldGroupIndex++;
2133                    }
2134                   
2135                    if (currentGroupValue >= groupValue)
2136                        break;
2137                }
2138               
2139                if (!group)
2140                    group = [[[TorrentGroup alloc] initWithGroup: groupValue] autorelease];
2141                [fDisplayedTorrents addObject: group];
2142               
2143                groupTorrents = [group torrents];
2144            }
2145           
2146            [groupTorrents addObject: torrent];
2147        }
2148    }
2149    else
2150        [fDisplayedTorrents setArray: allTorrents];
2151   
2152    //actually sort
2153    [self sortTorrentsIgnoreSelected];
2154   
2155    //reset expanded/collapsed rows
2156    if (groupRows)
2157    {
2158        for (TorrentGroup * group in fDisplayedTorrents)
2159        {
2160            if ([fTableView isGroupCollapsed: [group groupIndex]])
2161                [fTableView collapseItem: group];
2162            else
2163                [fTableView expandItem: group];
2164        }
2165    }
2166   
2167    [fTableView selectValues: selectedValues];
2168    [self resetInfo]; //if group is already selected, but the torrents in it change
2169   
2170    [self setBottomCountText: groupRows || filterStatus || filterGroup || filterText];
2171   
2172    [self setWindowSizeToFit];
2173}
2174
2175//resets filter and sorts torrents
2176- (void) setFilter: (id) sender
2177{
2178    NSString * oldFilterType = [fDefaults stringForKey: @"Filter"];
2179   
2180    NSButton * prevFilterButton;
2181    if ([oldFilterType isEqualToString: FILTER_PAUSE])
2182        prevFilterButton = fPauseFilterButton;
2183    else if ([oldFilterType isEqualToString: FILTER_ACTIVE])
2184        prevFilterButton = fActiveFilterButton;
2185    else if ([oldFilterType isEqualToString: FILTER_SEED])
2186        prevFilterButton = fSeedFilterButton;
2187    else if ([oldFilterType isEqualToString: FILTER_DOWNLOAD])
2188        prevFilterButton = fDownloadFilterButton;
2189    else
2190        prevFilterButton = fNoFilterButton;
2191   
2192    if (sender != prevFilterButton)
2193    {
2194        [prevFilterButton setState: NSOffState];
2195        [sender setState: NSOnState];
2196
2197        NSString * filterType;
2198        if (sender == fActiveFilterButton)
2199            filterType = FILTER_ACTIVE;
2200        else if (sender == fDownloadFilterButton)
2201            filterType = FILTER_DOWNLOAD;
2202        else if (sender == fPauseFilterButton)
2203            filterType = FILTER_PAUSE;
2204        else if (sender == fSeedFilterButton)
2205            filterType = FILTER_SEED;
2206        else
2207            filterType = FILTER_NONE;
2208
2209        [fDefaults setObject: filterType forKey: @"Filter"];
2210    }
2211    else
2212        [sender setState: NSOnState];
2213
2214    [self applyFilter: nil];
2215}
2216
2217- (void) setFilterSearchType: (id) sender
2218{
2219    NSString * oldFilterType = [fDefaults stringForKey: @"FilterSearchType"];
2220   
2221    NSInteger prevTag, currentTag = [sender tag];
2222    if ([oldFilterType isEqualToString: FILTER_TYPE_TRACKER])
2223        prevTag = FILTER_TYPE_TAG_TRACKER;
2224    else
2225        prevTag = FILTER_TYPE_TAG_NAME;
2226   
2227    if (currentTag != prevTag)
2228    {
2229        NSString * filterType;
2230        if (currentTag == FILTER_TYPE_TAG_TRACKER)
2231            filterType = FILTER_TYPE_TRACKER;
2232        else
2233            filterType = FILTER_TYPE_NAME;
2234       
2235        [fDefaults setObject: filterType forKey: @"FilterSearchType"];
2236       
2237        [[fSearchFilterField cell] setPlaceholderString: [sender title]];
2238    }
2239   
2240    [self applyFilter: nil];
2241}
2242
2243- (void) switchFilter: (id) sender
2244{
2245    NSString * filterType = [fDefaults stringForKey: @"Filter"];
2246   
2247    NSButton * button;
2248    if ([filterType isEqualToString: FILTER_NONE])
2249        button = sender == fNextFilterItem ? fActiveFilterButton : fPauseFilterButton;
2250    else if ([filterType isEqualToString: FILTER_ACTIVE])
2251        button = sender == fNextFilterItem ? fDownloadFilterButton : fNoFilterButton;
2252    else if ([filterType isEqualToString: FILTER_DOWNLOAD])
2253        button = sender == fNextFilterItem ? fSeedFilterButton : fActiveFilterButton;
2254    else if ([filterType isEqualToString: FILTER_SEED])
2255        button = sender == fNextFilterItem ? fPauseFilterButton : fDownloadFilterButton;
2256    else if ([filterType isEqualToString: FILTER_PAUSE])
2257        button = sender == fNextFilterItem ? fNoFilterButton : fSeedFilterButton;
2258    else
2259        button = fNoFilterButton;
2260   
2261    [self setFilter: button];
2262}
2263
2264- (void) setStatusLabel: (id) sender
2265{
2266    NSString * statusLabel;
2267    switch ([sender tag])
2268    {
2269        case STATUS_RATIO_TOTAL_TAG:
2270            statusLabel = STATUS_RATIO_TOTAL;
2271            break;
2272        case STATUS_RATIO_SESSION_TAG:
2273            statusLabel = STATUS_RATIO_SESSION;
2274            break;
2275        case STATUS_TRANSFER_TOTAL_TAG:
2276            statusLabel = STATUS_TRANSFER_TOTAL;
2277            break;
2278        case STATUS_TRANSFER_SESSION_TAG:
2279            statusLabel = STATUS_TRANSFER_SESSION;
2280            break;
2281        default:
2282            return;
2283    }
2284   
2285    [fDefaults setObject: statusLabel forKey: @"StatusLabel"];
2286    [self updateUI];
2287}
2288
2289- (void) menuNeedsUpdate: (NSMenu *) menu
2290{
2291    if (menu == fGroupsSetMenu || menu == fGroupsSetContextMenu || menu == fGroupFilterMenu)
2292    {
2293        const BOOL filter = menu == fGroupFilterMenu;
2294       
2295        const NSInteger remaining = filter ? 3 : 0;
2296        for (NSInteger i = [menu numberOfItems]-1; i >= remaining; i--)
2297            [menu removeItemAtIndex: i];
2298       
2299        NSMenu * groupMenu;
2300        if (!filter)
2301            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroup:) isSmall: NO];
2302        else
2303            groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(setGroupFilter:) isSmall: YES];
2304       
2305        const NSInteger groupMenuCount = [groupMenu numberOfItems];
2306        for (NSInteger i = 0; i < groupMenuCount; i++)
2307        {
2308            NSMenuItem * item = [[groupMenu itemAtIndex: 0] retain];
2309            [groupMenu removeItemAtIndex: 0];
2310            [menu addItem: item];
2311            [item release];
2312        }
2313    }
2314    else if (menu == fUploadMenu || menu == fDownloadMenu)
2315    {
2316        if ([menu numberOfItems] > 3)
2317            return;
2318       
2319        const NSInteger speedLimitActionValue[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750, 1000, 1500, 2000, -1 };
2320       
2321        NSMenuItem * item;
2322        for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
2323        {
2324            item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
2325                    "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimitGlobal:)
2326                    keyEquivalent: @""];
2327            [item setTarget: self];
2328            [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
2329            [menu addItem: item];
2330            [item release];
2331        }
2332    }
2333    else if (menu == fRatioStopMenu)
2334    {
2335        if ([menu numberOfItems] > 3)
2336            return;
2337       
2338        const float ratioLimitActionValue[] = { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, -1 };
2339       
2340        NSMenuItem * item;
2341        for (NSInteger i = 0; ratioLimitActionValue[i] != -1; i++)
2342        {
2343            item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
2344                    action: @selector(setQuickRatioGlobal:) keyEquivalent: @""];
2345            [item setTarget: self];
2346            [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
2347            [menu addItem: item];
2348            [item release];
2349        }
2350    }
2351    else;
2352}
2353
2354- (void) setGroup: (id) sender
2355{
2356    for (Torrent * torrent in [fTableView selectedTorrents])
2357    {
2358        [fTableView removeCollapsedGroup: [torrent groupValue]]; //remove old collapsed group
2359       
2360        [torrent setGroupValue: [sender tag]];
2361    }
2362   
2363    [self applyFilter: nil];
2364    [self updateUI];
2365    [self updateTorrentHistory];
2366}
2367
2368- (void) setGroupFilter: (id) sender
2369{
2370    [fDefaults setInteger: [sender tag] forKey: @"FilterGroup"];
2371    [self updateGroupsFilterButton];
2372    [self applyFilter: nil];
2373}
2374
2375- (void) updateGroupsFilterButton
2376{
2377    NSInteger groupIndex = [fDefaults integerForKey: @"FilterGroup"];
2378   
2379    NSImage * icon;
2380    NSString * toolTip;
2381    if (groupIndex == GROUP_FILTER_ALL_TAG)
2382    {
2383        icon = [NSImage imageNamed: @"PinTemplate.png"];
2384        toolTip = NSLocalizedString(@"All Groups", "Groups -> Button");
2385    }
2386    else
2387    {
2388        icon = [[GroupsController groups] imageForIndex: groupIndex];
2389        NSString * groupName = groupIndex != -1 ? [[GroupsController groups] nameForIndex: groupIndex]
2390                                                : NSLocalizedString(@"None", "Groups -> Button");
2391        toolTip = [NSLocalizedString(@"Group", "Groups -> Button") stringByAppendingFormat: @": %@", groupName];
2392    }
2393   
2394    [[fGroupFilterMenu itemAtIndex: 0] setImage: icon];
2395    [fGroupsButton setToolTip: toolTip];
2396}
2397
2398- (void) updateGroupsFilters: (NSNotification *) notification
2399{
2400    [self updateGroupsFilterButton];
2401    [self applyFilter: nil];
2402}
2403
2404- (void) toggleSpeedLimit: (id) sender
2405{
2406    [fDefaults setBool: ![fDefaults boolForKey: @"SpeedLimit"] forKey: @"SpeedLimit"];
2407    [self speedLimitChanged: sender];
2408}
2409
2410- (void) speedLimitChanged: (id) sender
2411{
2412    tr_sessionUseAltSpeed(fLib, [fDefaults boolForKey: @"SpeedLimit"]);
2413    [self updateSpeedFieldsToolTips];
2414}
2415
2416//dict has been retained
2417- (void) altSpeedToggledCallbackIsLimited: (NSDictionary *) dict
2418{
2419    const BOOL isLimited = [[dict objectForKey: @"Active"] boolValue];
2420
2421    [fDefaults setBool: isLimited forKey: @"SpeedLimit"];
2422    [self updateSpeedFieldsToolTips];
2423   
2424    if (![[dict objectForKey: @"ByUser"] boolValue])
2425        [GrowlApplicationBridge notifyWithTitle: isLimited
2426                ? NSLocalizedString(@"Speed Limit Auto Enabled", "Growl notification title")
2427                : NSLocalizedString(@"Speed Limit Auto Disabled", "Growl notification title")
2428            description: NSLocalizedString(@"Bandwidth settings changed", "Growl notification description")
2429            notificationName: GROWL_AUTO_SPEED_LIMIT iconData: nil priority: 0 isSticky: NO clickContext: nil];
2430   
2431    [dict release];
2432}
2433
2434- (void) setLimitGlobalEnabled: (id) sender
2435{
2436    BOOL upload = [sender menu] == fUploadMenu;
2437    [fDefaults setBool: sender == (upload ? fUploadLimitItem : fDownloadLimitItem) forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2438   
2439    [fPrefsController applySpeedSettings: nil];
2440}
2441
2442- (void) setQuickLimitGlobal: (id) sender
2443{
2444    BOOL upload = [sender menu] == fUploadMenu;
2445    [fDefaults setInteger: [[sender representedObject] intValue] forKey: upload ? @"UploadLimit" : @"DownloadLimit"];
2446    [fDefaults setBool: YES forKey: upload ? @"CheckUpload" : @"CheckDownload"];
2447   
2448    [fPrefsController updateLimitFields];
2449    [fPrefsController applySpeedSettings: nil];
2450}
2451
2452- (void) setRatioGlobalEnabled: (id) sender
2453{
2454    [fDefaults setBool: sender == fCheckRatioItem forKey: @"RatioCheck"];
2455   
2456    [fPrefsController applyRatioSetting: nil];
2457}
2458
2459- (void) setQuickRatioGlobal: (id) sender
2460{
2461    [fDefaults setBool: YES forKey: @"RatioCheck"];
2462    [fDefaults setFloat: [[sender representedObject] floatValue] forKey: @"RatioLimit"];
2463   
2464    [fPrefsController updateRatioStopField];
2465}
2466
2467- (void) sound: (NSSound *) sound didFinishPlaying: (BOOL) finishedPlaying
2468{
2469    fSoundPlaying = NO;
2470}
2471
2472- (void) watcher: (id<UKFileWatcher>) watcher receivedNotification: (NSString *) notification forPath: (NSString *) path
2473{
2474    if ([notification isEqualToString: UKFileWatcherWriteNotification])
2475    {
2476        if (![fDefaults boolForKey: @"AutoImport"] || ![fDefaults stringForKey: @"AutoImportDirectory"])
2477            return;
2478       
2479        if (fAutoImportTimer)
2480        {
2481            if ([fAutoImportTimer isValid])
2482                [fAutoImportTimer invalidate];
2483            [fAutoImportTimer release];
2484            fAutoImportTimer = nil;
2485        }
2486       
2487        //check again in 10 seconds in case torrent file wasn't complete
2488        fAutoImportTimer = [[NSTimer scheduledTimerWithTimeInterval: 10.0 target: self
2489            selector: @selector(checkAutoImportDirectory) userInfo: nil repeats: NO] retain];
2490       
2491        [self checkAutoImportDirectory];
2492    }
2493}
2494
2495- (void) changeAutoImport
2496{
2497    if (fAutoImportTimer)
2498    {
2499        if ([fAutoImportTimer isValid])
2500            [fAutoImportTimer invalidate];
2501        [fAutoImportTimer release];
2502        fAutoImportTimer = nil;
2503    }
2504   
2505    if (fAutoImportedNames)
2506    {
2507        [fAutoImportedNames release];
2508        fAutoImportedNames = nil;
2509    }
2510   
2511    [self checkAutoImportDirectory];
2512}
2513
2514- (void) checkAutoImportDirectory
2515{
2516    NSString * path;
2517    if (![fDefaults boolForKey: @"AutoImport"] || !(path = [fDefaults stringForKey: @"AutoImportDirectory"]))
2518        return;
2519   
2520    path = [path stringByExpandingTildeInPath];
2521   
2522    NSArray * importedNames;
2523    if (!(importedNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: path error: NULL]))
2524        return;
2525   
2526    //only check files that have not been checked yet
2527    NSMutableArray * newNames = [importedNames mutableCopy];
2528   
2529    if (fAutoImportedNames)
2530        [newNames removeObjectsInArray: fAutoImportedNames];
2531    else
2532        fAutoImportedNames = [[NSMutableArray alloc] init];
2533    [fAutoImportedNames setArray: importedNames];
2534   
2535    for (NSString * file in newNames)
2536    {
2537        if ([file hasPrefix: @"."])
2538            continue;
2539       
2540        NSString * fullFile = [path stringByAppendingPathComponent: file];
2541       
2542        if (!([[[NSWorkspace sharedWorkspace] typeOfFile: fullFile error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2543                || [[fullFile pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame))
2544            continue;
2545       
2546        tr_ctor * ctor = tr_ctorNew(fLib);
2547        tr_ctorSetMetainfoFromFile(ctor, [fullFile UTF8String]);
2548       
2549        switch (tr_torrentParse(ctor, NULL))
2550        {
2551            case TR_PARSE_OK:
2552                [self openFiles: [NSArray arrayWithObject: fullFile] addType: ADD_AUTO forcePath: nil];
2553               
2554                [GrowlApplicationBridge notifyWithTitle: NSLocalizedString(@"Torrent File Auto Added", "Growl notification title")
2555                    description: file notificationName: GROWL_AUTO_ADD iconData: nil priority: 0 isSticky: NO
2556                    clickContext: nil];
2557                break;
2558           
2559            case TR_PARSE_ERR:
2560                [fAutoImportedNames removeObject: file];
2561        }
2562       
2563        tr_ctorFree(ctor);
2564    }
2565   
2566    [newNames release];
2567}
2568
2569- (void) beginCreateFile: (NSNotification *) notification
2570{
2571    if (![fDefaults boolForKey: @"AutoImport"])
2572        return;
2573   
2574    NSString * location = [notification object],
2575            * path = [fDefaults stringForKey: @"AutoImportDirectory"];
2576   
2577    if (location && path && [[[location stringByDeletingLastPathComponent] stringByExpandingTildeInPath]
2578                                    isEqualToString: [path stringByExpandingTildeInPath]])
2579        [fAutoImportedNames addObject: [location lastPathComponent]];
2580}
2581
2582- (NSInteger) outlineView: (NSOutlineView *) outlineView numberOfChildrenOfItem: (id) item
2583{
2584    if (item)
2585        return [[item torrents] count];
2586    else
2587        return [fDisplayedTorrents count];
2588}
2589
2590- (id) outlineView: (NSOutlineView *) outlineView child: (NSInteger) index ofItem: (id) item
2591{
2592    if (item)
2593        return [[item torrents] objectAtIndex: index];
2594    else
2595        return [fDisplayedTorrents objectAtIndex: index];
2596}
2597
2598- (BOOL) outlineView: (NSOutlineView *) outlineView isItemExpandable: (id) item
2599{
2600    return ![item isKindOfClass: [Torrent class]];
2601}
2602
2603- (id) outlineView: (NSOutlineView *) outlineView objectValueForTableColumn: (NSTableColumn *) tableColumn byItem: (id) item
2604{
2605    if ([item isKindOfClass: [Torrent class]])
2606        return [item hashString];
2607    else
2608    {
2609        NSString * ident = [tableColumn identifier];
2610        if ([ident isEqualToString: @"Group"])
2611        {
2612            NSInteger group = [item groupIndex];
2613            return group != -1 ? [[GroupsController groups] nameForIndex: group]
2614                                : NSLocalizedString(@"No Group", "Group table row");
2615        }
2616        else if ([ident isEqualToString: @"Color"])
2617        {
2618            NSInteger group = [item groupIndex];
2619            return [[GroupsController groups] imageForIndex: group];
2620        }
2621        else if ([ident isEqualToString: @"DL Image"])
2622            return [NSImage imageNamed: @"DownArrowGroupTemplate.png"];
2623        else if ([ident isEqualToString: @"UL Image"])
2624            return [NSImage imageNamed: [fDefaults boolForKey: @"DisplayGroupRowRatio"]
2625                                        ? @"YingYangGroupTemplate.png" : @"UpArrowGroupTemplate.png"];
2626        else
2627        {
2628            TorrentGroup * group = (TorrentGroup *)item;
2629           
2630            if ([fDefaults boolForKey: @"DisplayGroupRowRatio"])
2631                return [NSString stringForRatio: [group ratio]];
2632            else
2633            {
2634                CGFloat rate = [ident isEqualToString: @"UL"] ? [group uploadRate] : [group downloadRate];
2635                return [NSString stringForSpeed: rate];
2636            }
2637        }
2638    }
2639}
2640
2641- (BOOL) outlineView: (NSOutlineView *) outlineView writeItems: (NSArray *) items toPasteboard: (NSPasteboard *) pasteboard
2642{
2643    //only allow reordering of rows if sorting by order
2644    if ([fDefaults boolForKey: @"SortByGroup"] || [[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2645    {
2646        NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
2647        for (id torrent in items)
2648        {
2649            if (![torrent isKindOfClass: [Torrent class]])
2650                return NO;
2651           
2652            [indexSet addIndex: [fTableView rowForItem: torrent]];
2653        }
2654       
2655        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
2656        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexSet] forType: TORRENT_TABLE_VIEW_DATA_TYPE];
2657        return YES;
2658    }
2659    return NO;
2660}
2661
2662- (NSDragOperation) outlineView: (NSOutlineView *) outlineView validateDrop: (id < NSDraggingInfo >) info proposedItem: (id) item
2663    proposedChildIndex: (NSInteger) index
2664{
2665    NSPasteboard * pasteboard = [info draggingPasteboard];
2666    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2667    {
2668        if ([fDefaults boolForKey: @"SortByGroup"])
2669        {
2670            if (!item)
2671                return NSDragOperationNone;
2672           
2673            if ([[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER])
2674            {
2675                if ([item isKindOfClass: [Torrent class]])
2676                {
2677                    TorrentGroup * group = [fTableView parentForItem: item];
2678                    index = [[group torrents] indexOfObject: item] + 1;
2679                    item = group;
2680                }
2681            }
2682            else
2683            {
2684                if ([item isKindOfClass: [Torrent class]])
2685                    item = [fTableView parentForItem: item];
2686                index = NSOutlineViewDropOnItemIndex;
2687            }
2688        }
2689        else
2690        {
2691            if (item)
2692            {
2693                index = [fTableView rowForItem: item] + 1;
2694                item = nil;
2695            }
2696        }
2697       
2698        [fTableView setDropItem: item dropChildIndex: index];
2699        return NSDragOperationGeneric;
2700    }
2701   
2702    return NSDragOperationNone;
2703}
2704
2705- (BOOL) outlineView: (NSOutlineView *) outlineView acceptDrop: (id < NSDraggingInfo >) info item: (id) item
2706    childIndex: (NSInteger) newRow
2707{
2708    NSPasteboard * pasteboard = [info draggingPasteboard];
2709    if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
2710    {
2711        //remember selected rows
2712        NSArray * selectedValues = [fTableView selectedValues];
2713   
2714        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData: [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
2715       
2716        //get the torrents to move
2717        NSMutableArray * movingTorrents = [NSMutableArray arrayWithCapacity: [indexes count]];
2718        for (NSUInteger i = [indexes firstIndex]; i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
2719            [movingTorrents addObject: [fTableView itemAtRow: i]];
2720       
2721        //reset groups
2722        if (item)
2723        {
2724            //change groups
2725            NSInteger groupValue = [item groupIndex];
2726            for (Torrent * torrent in movingTorrents)
2727            {
2728                //have to reset objects here to avoid weird crash
2729                [[[fTableView parentForItem: torrent] torrents] removeObject: torrent];
2730                [[item torrents] addObject: torrent];
2731               
2732                [torrent setGroupValue: groupValue];
2733            }
2734            //part 2 of avoiding weird crash
2735            [fTableView reloadItem: nil reloadChildren: YES];
2736        }
2737       
2738        //reorder queue order
2739        if (newRow != NSOutlineViewDropOnItemIndex)
2740        {
2741            //find torrent to place under
2742            NSArray * groupTorrents = item ? [item torrents] : fDisplayedTorrents;
2743            Torrent * topTorrent = nil;
2744            for (NSInteger i = newRow-1; i >= 0; i--)
2745            {
2746                Torrent * tempTorrent = [groupTorrents objectAtIndex: i];
2747                if (![movingTorrents containsObject: tempTorrent])
2748                {
2749                    topTorrent = tempTorrent;
2750                    break;
2751                }
2752            }
2753           
2754            //remove objects to reinsert
2755            [fTorrents removeObjectsInArray: movingTorrents];
2756           
2757            //insert objects at new location
2758            NSUInteger insertIndex = topTorrent ? [fTorrents indexOfObject: topTorrent] + 1 : 0;
2759            NSIndexSet * insertIndexes = [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(insertIndex, [movingTorrents count])];
2760            [fTorrents insertObjects: movingTorrents atIndexes: insertIndexes];
2761        }
2762       
2763        [self applyFilter: nil];
2764        [fTableView selectValues: selectedValues];
2765    }
2766   
2767    return YES;
2768}
2769
2770- (void) torrentTableViewSelectionDidChange: (NSNotification *) notification
2771{
2772    [self resetInfo];
2773}
2774
2775- (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) info
2776{
2777    NSPasteboard * pasteboard = [info draggingPasteboard];
2778    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2779    {
2780        //check if any torrent files can be added
2781        BOOL torrent = NO;
2782        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2783        for (NSString * file in files)
2784        {
2785            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2786                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2787            {
2788                torrent = YES;
2789                tr_ctor * ctor = tr_ctorNew(fLib);
2790                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2791                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2792                {
2793                    if (!fOverlayWindow)
2794                        fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2795                    [fOverlayWindow setTorrents: files];
2796                   
2797                    return NSDragOperationCopy;
2798                }
2799                tr_ctorFree(ctor);
2800            }
2801        }
2802       
2803        //create a torrent file if a single file
2804        if (!torrent && [files count] == 1)
2805        {
2806            if (!fOverlayWindow)
2807                fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2808            [fOverlayWindow setFile: [[files objectAtIndex: 0] lastPathComponent]];
2809           
2810            return NSDragOperationCopy;
2811        }
2812    }
2813    else if ([[pasteboard types] containsObject: NSURLPboardType])
2814    {
2815        if (!fOverlayWindow)
2816            fOverlayWindow = [[DragOverlayWindow alloc] initWithLib: fLib forWindow: fWindow];
2817        [fOverlayWindow setURL: [[NSURL URLFromPasteboard: pasteboard] relativeString]];
2818       
2819        return NSDragOperationCopy;
2820    }
2821    else;
2822   
2823    return NSDragOperationNone;
2824}
2825
2826- (void) draggingExited: (id <NSDraggingInfo>) info
2827{
2828    if (fOverlayWindow)
2829        [fOverlayWindow fadeOut];
2830}
2831
2832- (BOOL) performDragOperation: (id <NSDraggingInfo>) info
2833{
2834    if (fOverlayWindow)
2835        [fOverlayWindow fadeOut];
2836   
2837    NSPasteboard * pasteboard = [info draggingPasteboard];
2838    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
2839    {
2840        BOOL torrent = NO, accept = YES;
2841       
2842        //create an array of files that can be opened
2843        NSArray * files = [pasteboard propertyListForType: NSFilenamesPboardType];
2844        NSMutableArray * filesToOpen = [NSMutableArray arrayWithCapacity: [files count]];
2845        for (NSString * file in files)
2846        {
2847            if ([[[NSWorkspace sharedWorkspace] typeOfFile: file error: NULL] isEqualToString: @"org.bittorrent.torrent"]
2848                    || [[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
2849            {
2850                torrent = YES;
2851                tr_ctor * ctor = tr_ctorNew(fLib);
2852                tr_ctorSetMetainfoFromFile(ctor, [file UTF8String]);
2853                if (tr_torrentParse(ctor, NULL) == TR_PARSE_OK)
2854                    [filesToOpen addObject: file];
2855                tr_ctorFree(ctor);
2856            }
2857        }
2858       
2859        if ([filesToOpen count] > 0)
2860            [self application: NSApp openFiles: filesToOpen];
2861        else
2862        {
2863            if (!torrent && [files count] == 1)
2864                [CreatorWindowController createTorrentFile: fLib forFile: [files objectAtIndex: 0]];
2865            else
2866                accept = NO;
2867        }
2868       
2869        return accept;
2870    }
2871    else if ([[pasteboard types] containsObject: NSURLPboardType])
2872    {
2873        NSURL * url;
2874        if ((url = [NSURL URLFromPasteboard: pasteboard]))
2875        {
2876            [self openURL: url];
2877            return YES;
2878        }
2879    }
2880    else;
2881   
2882    return NO;
2883}
2884
2885- (void) toggleSmallView: (id) sender
2886{
2887    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
2888    [fDefaults setBool: makeSmall forKey: @"SmallView"];
2889   
2890    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
2891   
2892    [fTableView noteHeightOfRowsWithIndexesChanged: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTableView numberOfRows])]];
2893   
2894    //window min height
2895    NSSize contentMinSize = [fWindow contentMinSize],
2896            contentSize = [[fWindow contentView] frame].size;
2897    contentMinSize.height = contentSize.height - [[fTableView enclosingScrollView] frame].size.height
2898                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
2899    [fWindow setContentMinSize: contentMinSize];
2900   
2901    //resize for larger min height if not set to auto size
2902    if (![fDefaults boolForKey: @"AutoSize"])
2903    {
2904        if (!makeSmall && contentSize.height < contentMinSize.height)
2905        {
2906            NSRect frame = [fWindow frame];
2907            CGFloat heightChange = contentMinSize.height - contentSize.height;
2908            frame.size.height += heightChange;
2909            frame.origin.y -= heightChange;
2910           
2911            [fWindow setFrame: frame display: YES];
2912        }
2913    }
2914    else
2915        [self setWindowSizeToFit];
2916}
2917
2918- (void) togglePiecesBar: (id) sender
2919{
2920    [fDefaults setBool: ![fDefaults boolForKey: @"PiecesBar"] forKey: @"PiecesBar"];
2921    [fTableView togglePiecesBar];
2922}
2923
2924- (void) toggleAvailabilityBar: (id) sender
2925{
2926    [fDefaults setBool: ![fDefaults boolForKey: @"DisplayProgressBarAvailable"] forKey: @"DisplayProgressBarAvailable"];
2927    [fTableView display];
2928}
2929
2930- (void) toggleStatusString: (id) sender
2931{
2932    if ([fDefaults boolForKey: @"SmallView"])
2933        [fDefaults setBool: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] forKey: @"DisplaySmallStatusRegular"];
2934    else
2935        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayStatusProgressSelected"] forKey: @"DisplayStatusProgressSelected"];
2936   
2937    [fTableView reloadData];
2938}
2939
2940- (NSRect) windowFrameByAddingHeight: (CGFloat) height checkLimits: (BOOL) check
2941{
2942    NSScrollView * scrollView = [fTableView enclosingScrollView];
2943   
2944    //convert pixels to points
2945    NSRect windowFrame = [fWindow frame];
2946    NSSize windowSize = [scrollView convertSize: windowFrame.size fromView: nil];
2947    windowSize.height += height;
2948   
2949    if (check)
2950    {
2951        NSSize minSize = [scrollView convertSize: [fWindow minSize] fromView: nil];
2952       
2953        if (windowSize.height < minSize.height)
2954            windowSize.height = minSize.height;
2955        else
2956        {
2957            NSSize maxSize = [scrollView convertSize: [[fWindow screen] visibleFrame].size fromView: nil];
2958            if ([fStatusBar isHidden])
2959                maxSize.height -= [fStatusBar frame].size.height;
2960            if ([fFilterBar isHidden])
2961                maxSize.height -= [fFilterBar frame].size.height;
2962            if (windowSize.height > maxSize.height)
2963                windowSize.height = maxSize.height;
2964        }
2965    }
2966
2967    //convert points to pixels
2968    windowSize = [scrollView convertSize: windowSize toView: nil];
2969
2970    windowFrame.origin.y -= (windowSize.height - windowFrame.size.height);
2971    windowFrame.size.height = windowSize.height;
2972    return windowFrame;
2973}
2974
2975- (void) toggleStatusBar: (id) sender
2976{
2977    [self showStatusBar: [fStatusBar isHidden] animate: YES];
2978    [fDefaults setBool: ![fStatusBar isHidden] forKey: @"StatusBar"];
2979}
2980
2981//doesn't save shown state
2982- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
2983{
2984    if (show != [fStatusBar isHidden])
2985        return;
2986
2987    if (show)
2988        [fStatusBar setHidden: NO];
2989
2990    NSRect frame;
2991    CGFloat heightChange = [fStatusBar frame].size.height;
2992    if (!show)
2993        heightChange *= -1;
2994   
2995    //allow bar to show even if not enough room
2996    if (show && ![fDefaults boolForKey: @"AutoSize"])
2997    {
2998        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
2999        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3000        if (change < 0.0)
3001        {
3002            frame = [fWindow frame];
3003            frame.size.height += change;
3004            frame.origin.y -= change;
3005            [fWindow setFrame: frame display: NO animate: NO];
3006        }
3007    }
3008
3009    [self updateUI];
3010   
3011    NSScrollView * scrollView = [fTableView enclosingScrollView];
3012   
3013    //set views to not autoresize
3014    NSUInteger statsMask = [fStatusBar autoresizingMask];
3015    NSUInteger filterMask = [fFilterBar autoresizingMask];
3016    NSUInteger scrollMask = [scrollView autoresizingMask];
3017    [fStatusBar setAutoresizingMask: NSViewNotSizable];
3018    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3019    [scrollView setAutoresizingMask: NSViewNotSizable];
3020   
3021    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3022    [fWindow setFrame: frame display: YES animate: animate];
3023   
3024    //re-enable autoresize
3025    [fStatusBar setAutoresizingMask: statsMask];
3026    [fFilterBar setAutoresizingMask: filterMask];
3027    [scrollView setAutoresizingMask: scrollMask];
3028   
3029    //change min size
3030    NSSize minSize = [fWindow contentMinSize];
3031    minSize.height += heightChange;
3032    [fWindow setContentMinSize: minSize];
3033   
3034    if (!show)
3035        [fStatusBar setHidden: YES];
3036}
3037
3038- (void) toggleFilterBar: (id) sender
3039{
3040    //disable filtering when hiding
3041    if (![fFilterBar isHidden])
3042    {
3043        [fSearchFilterField setStringValue: @""];
3044        [self setFilter: fNoFilterButton];
3045        [self setGroupFilter: [fGroupFilterMenu itemWithTag: GROUP_FILTER_ALL_TAG]];
3046    }
3047
3048    [self showFilterBar: [fFilterBar isHidden] animate: YES];
3049    [fDefaults setBool: ![fFilterBar isHidden] forKey: @"FilterBar"];
3050}
3051
3052//doesn't save shown state
3053- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
3054{
3055    if (show != [fFilterBar isHidden])
3056        return;
3057
3058    if (show)
3059        [fFilterBar setHidden: NO];
3060
3061    NSRect frame;
3062    CGFloat heightChange = [fFilterBar frame].size.height;
3063    if (!show)
3064        heightChange *= -1;
3065   
3066    //allow bar to show even if not enough room
3067    if (show && ![fDefaults boolForKey: @"AutoSize"])
3068    {
3069        frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3070        CGFloat change = [[fWindow screen] visibleFrame].size.height - frame.size.height;
3071        if (change < 0.0)
3072        {
3073            frame = [fWindow frame];
3074            frame.size.height += change;
3075            frame.origin.y -= change;
3076            [fWindow setFrame: frame display: NO animate: NO];
3077        }
3078    }
3079   
3080    NSScrollView * scrollView = [fTableView enclosingScrollView];
3081
3082    //set views to not autoresize
3083    NSUInteger filterMask = [fFilterBar autoresizingMask];
3084    NSUInteger scrollMask = [scrollView autoresizingMask];
3085    [fFilterBar setAutoresizingMask: NSViewNotSizable];
3086    [scrollView setAutoresizingMask: NSViewNotSizable];
3087   
3088    frame = [self windowFrameByAddingHeight: heightChange checkLimits: NO];
3089    [fWindow setFrame: frame display: YES animate: animate];
3090   
3091    //re-enable autoresize
3092    [fFilterBar setAutoresizingMask: filterMask];
3093    [scrollView setAutoresizingMask: scrollMask];
3094   
3095    //change min size
3096    NSSize minSize = [fWindow contentMinSize];
3097    minSize.height += heightChange;
3098    [fWindow setContentMinSize: minSize];
3099   
3100    if (!show)
3101    {
3102        [fFilterBar setHidden: YES];
3103        [fWindow makeFirstResponder: fTableView];
3104    }
3105}
3106
3107- (void) focusFilterField
3108{
3109    [fWindow makeFirstResponder: fSearchFilterField];
3110    if ([fFilterBar isHidden])
3111        [self toggleFilterBar: self];
3112}
3113
3114- (ButtonToolbarItem *) standardToolbarButtonWithIdentifier: (NSString *) ident
3115{
3116    ButtonToolbarItem * item = [[ButtonToolbarItem alloc] initWithItemIdentifier: ident];
3117   
3118    NSButton * button = [[NSButton alloc] initWithFrame: NSZeroRect];
3119    [button setBezelStyle: NSTexturedRoundedBezelStyle];
3120    [button setStringValue: @""];
3121   
3122    [item setView: button];
3123    [button release];
3124   
3125    const NSSize buttonSize = NSMakeSize(36.0, 25.0);
3126    [item setMinSize: buttonSize];
3127    [item setMaxSize: buttonSize];
3128   
3129    return [item autorelease];
3130}
3131
3132- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
3133{
3134    if ([ident isEqualToString: TOOLBAR_CREATE])
3135    {
3136        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3137       
3138        [item setLabel: NSLocalizedString(@"Create", "Create toolbar item -> label")];
3139        [item setPaletteLabel: NSLocalizedString(@"Create Torrent File", "Create toolbar item -> palette label")];
3140        [item setToolTip: NSLocalizedString(@"Create torrent file", "Create toolbar item -> tooltip")];
3141        [item setImage: [NSImage imageNamed: @"ToolbarCreateTemplate.png"]];
3142        [item setTarget: self];
3143        [item setAction: @selector(createFile:)];
3144        [item setAutovalidates: NO];
3145       
3146        return item;
3147    }
3148    else if ([ident isEqualToString: TOOLBAR_OPEN_FILE])
3149    {
3150        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3151       
3152        [item setLabel: NSLocalizedString(@"Open", "Open toolbar item -> label")];
3153        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Files", "Open toolbar item -> palette label")];
3154        [item setToolTip: NSLocalizedString(@"Open torrent files", "Open toolbar item -> tooltip")];
3155        [item setImage: [NSImage imageNamed: @"ToolbarOpenTemplate.png"]];
3156        [item setTarget: self];
3157        [item setAction: @selector(openShowSheet:)];
3158        [item setAutovalidates: NO];
3159       
3160        return item;
3161    }
3162    else if ([ident isEqualToString: TOOLBAR_OPEN_WEB])
3163    {
3164        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3165       
3166        [item setLabel: NSLocalizedString(@"Open Address", "Open address toolbar item -> label")];
3167        [item setPaletteLabel: NSLocalizedString(@"Open Torrent Address", "Open address toolbar item -> palette label")];
3168        [item setToolTip: NSLocalizedString(@"Open torrent web address", "Open address toolbar item -> tooltip")];
3169        [item setImage: [NSImage imageNamed: @"ToolbarOpenWebTemplate.png"]];
3170        [item setTarget: self];
3171        [item setAction: @selector(openURLShowSheet:)];
3172        [item setAutovalidates: NO];
3173       
3174        return item;
3175    }
3176    else if ([ident isEqualToString: TOOLBAR_REMOVE])
3177    {
3178        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3179       
3180        [item setLabel: NSLocalizedString(@"Remove", "Remove toolbar item -> label")];
3181        [item setPaletteLabel: NSLocalizedString(@"Remove Selected", "Remove toolbar item -> palette label")];
3182        [item setToolTip: NSLocalizedString(@"Remove selected transfers", "Remove toolbar item -> tooltip")];
3183        [item setImage: [NSImage imageNamed: @"ToolbarRemoveTemplate.png"]];
3184        [item setTarget: self];
3185        [item setAction: @selector(removeNoDelete:)];
3186       
3187        return item;
3188    }
3189    else if ([ident isEqualToString: TOOLBAR_INFO])
3190    {
3191        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3192        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3193       
3194        [item setLabel: NSLocalizedString(@"Inspector", "Inspector toolbar item -> label")];
3195        [item setPaletteLabel: NSLocalizedString(@"Toggle Inspector", "Inspector toolbar item -> palette label")];
3196        [item setToolTip: NSLocalizedString(@"Toggle the torrent inspector", "Inspector toolbar item -> tooltip")];
3197        [item setImage: [NSImage imageNamed: @"ToolbarInfoTemplate.png"]];
3198        [item setTarget: self];
3199        [item setAction: @selector(showInfo:)];
3200       
3201        return item;
3202    }
3203    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_ALL])
3204    {
3205        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3206       
3207        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3208        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3209        [groupItem setView: segmentedControl];
3210        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3211       
3212        [segmentedControl setSegmentCount: 2];
3213        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3214       
3215        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3216        [groupItem setMinSize: groupSize];
3217        [groupItem setMaxSize: groupSize];
3218       
3219        [groupItem setLabel: NSLocalizedString(@"Apply All", "All toolbar item -> label")];
3220        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume All", "All toolbar item -> palette label")];
3221        [groupItem setTarget: self];
3222        [groupItem setAction: @selector(allToolbarClicked:)];
3223       
3224        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, nil]];
3225       
3226        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3227        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseAllTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3228        [segmentedCell setToolTip: NSLocalizedString(@"Pause all transfers",
3229                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3230       
3231        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3232        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeAllTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3233        [segmentedCell setToolTip: NSLocalizedString(@"Resume all transfers",
3234                                    "All toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3235       
3236        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause All", "All toolbar item -> label"),
3237                                        NSLocalizedString(@"Resume All", "All toolbar item -> label"), nil]];
3238       
3239        [segmentedControl release];
3240        return [groupItem autorelease];
3241    }
3242    else if ([ident isEqualToString: TOOLBAR_PAUSE_RESUME_SELECTED])
3243    {
3244        GroupToolbarItem * groupItem = [[GroupToolbarItem alloc] initWithItemIdentifier: ident];
3245       
3246        NSSegmentedControl * segmentedControl = [[NSSegmentedControl alloc] initWithFrame: NSZeroRect];
3247        [segmentedControl setCell: [[[ToolbarSegmentedCell alloc] init] autorelease]];
3248        [groupItem setView: segmentedControl];
3249        NSSegmentedCell * segmentedCell = (NSSegmentedCell *)[segmentedControl cell];
3250       
3251        [segmentedControl setSegmentCount: 2];
3252        [segmentedCell setTrackingMode: NSSegmentSwitchTrackingMomentary];
3253       
3254        const NSSize groupSize = NSMakeSize(72.0, 25.0);
3255        [groupItem setMinSize: groupSize];
3256        [groupItem setMaxSize: groupSize];
3257       
3258        [groupItem setLabel: NSLocalizedString(@"Apply Selected", "Selected toolbar item -> label")];
3259        [groupItem setPaletteLabel: NSLocalizedString(@"Pause / Resume Selected", "Selected toolbar item -> palette label")];
3260        [groupItem setTarget: self];
3261        [groupItem setAction: @selector(selectedToolbarClicked:)];
3262       
3263        [groupItem setIdentifiers: [NSArray arrayWithObjects: TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED, nil]];
3264       
3265        [segmentedCell setTag: TOOLBAR_PAUSE_TAG forSegment: TOOLBAR_PAUSE_TAG];
3266        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarPauseSelectedTemplate.png"] forSegment: TOOLBAR_PAUSE_TAG];
3267        [segmentedCell setToolTip: NSLocalizedString(@"Pause selected transfers",
3268                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_PAUSE_TAG];
3269       
3270        [segmentedCell setTag: TOOLBAR_RESUME_TAG forSegment: TOOLBAR_RESUME_TAG];
3271        [segmentedControl setImage: [NSImage imageNamed: @"ToolbarResumeSelectedTemplate.png"] forSegment: TOOLBAR_RESUME_TAG];
3272        [segmentedCell setToolTip: NSLocalizedString(@"Resume selected transfers",
3273                                    "Selected toolbar item -> tooltip") forSegment: TOOLBAR_RESUME_TAG];
3274       
3275        [groupItem createMenu: [NSArray arrayWithObjects: NSLocalizedString(@"Pause Selected", "Selected toolbar item -> label"),
3276                                        NSLocalizedString(@"Resume Selected", "Selected toolbar item -> label"), nil]];
3277       
3278        [segmentedControl release];
3279        return [groupItem autorelease];
3280    }
3281    else if ([ident isEqualToString: TOOLBAR_FILTER])
3282    {
3283        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3284        [[(NSButton *)[item view] cell] setShowsStateBy: NSContentsCellMask]; //blue when enabled
3285       
3286        [item setLabel: NSLocalizedString(@"Filter", "Filter toolbar item -> label")];
3287        [item setPaletteLabel: NSLocalizedString(@"Toggle Filter", "Filter toolbar item -> palette label")];
3288        [item setToolTip: NSLocalizedString(@"Toggle the filter bar", "Filter toolbar item -> tooltip")];
3289        [item setImage: [NSImage imageNamed: @"ToolbarFilterTemplate.png"]];
3290        [item setTarget: self];
3291        [item setAction: @selector(toggleFilterBar:)];
3292       
3293        return item;
3294    }
3295    else if ([ident isEqualToString: TOOLBAR_QUICKLOOK])
3296    {
3297        ButtonToolbarItem * item = [self standardToolbarButtonWithIdentifier: ident];
3298       
3299        [item setLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> label")];
3300        [item setPaletteLabel: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> palette label")];
3301        [item setToolTip: NSLocalizedString(@"Quick Look", "QuickLook toolbar item -> tooltip")];
3302        [item setImage: [NSImage imageNamed: NSImageNameQuickLookTemplate]];
3303        [item setTarget: self];
3304        [item setAction: @selector(toggleQuickLook:)];
3305        [item setAutovalidates: NO];
3306        [item setEnabled: [NSApp isOnSnowLeopardOrBetter]];
3307       
3308        return item;
3309    }
3310    else
3311        return nil;
3312}
3313
3314- (void) allToolbarClicked: (id) sender
3315{
3316    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3317                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3318    switch (tagValue)
3319    {
3320        case TOOLBAR_PAUSE_TAG:
3321            [self stopAllTorrents: sender];
3322            break;
3323        case TOOLBAR_RESUME_TAG:
3324            [self resumeAllTorrents: sender];
3325            break;
3326    }
3327}
3328
3329- (void) selectedToolbarClicked: (id) sender
3330{
3331    NSInteger tagValue = [sender isKindOfClass: [NSSegmentedControl class]]
3332                    ? [(NSSegmentedCell *)[sender cell] tagForSegment: [sender selectedSegment]] : [sender tag];
3333    switch (tagValue)
3334    {
3335        case TOOLBAR_PAUSE_TAG:
3336            [self stopSelectedTorrents: sender];
3337            break;
3338        case TOOLBAR_RESUME_TAG:
3339            [self resumeSelectedTorrents: sender];
3340            break;
3341    }
3342}
3343
3344- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
3345{
3346    return [NSArray arrayWithObjects:
3347            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_OPEN_WEB, TOOLBAR_REMOVE,
3348            TOOLBAR_PAUSE_RESUME_SELECTED, TOOLBAR_PAUSE_RESUME_ALL,
3349            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO,
3350            NSToolbarSeparatorItemIdentifier,
3351            NSToolbarSpaceItemIdentifier,
3352            NSToolbarFlexibleSpaceItemIdentifier,
3353            NSToolbarCustomizeToolbarItemIdentifier, nil];
3354}
3355
3356- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
3357{
3358    return [NSArray arrayWithObjects:
3359            TOOLBAR_CREATE, TOOLBAR_OPEN_FILE, TOOLBAR_REMOVE, NSToolbarSeparatorItemIdentifier,
3360            TOOLBAR_PAUSE_RESUME_ALL, NSToolbarFlexibleSpaceItemIdentifier,
3361            TOOLBAR_QUICKLOOK, TOOLBAR_FILTER, TOOLBAR_INFO, nil];
3362}
3363
3364- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
3365{
3366    NSString * ident = [toolbarItem itemIdentifier];
3367   
3368    //enable remove item
3369    if ([ident isEqualToString: TOOLBAR_REMOVE])
3370        return [fTableView numberOfSelectedRows] > 0;
3371
3372    //enable pause all item
3373    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
3374    {
3375        for (Torrent * torrent in fTorrents)
3376            if ([torrent isActive] || [torrent waitingToStart])
3377                return YES;
3378        return NO;
3379    }
3380
3381    //enable resume all item
3382    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
3383    {
3384        for (Torrent * torrent in fTorrents)
3385            if (![torrent isActive] && ![torrent waitingToStart])
3386                return YES;
3387        return NO;
3388    }
3389
3390    //enable pause item
3391    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
3392    {
3393        for (Torrent * torrent in [fTableView selectedTorrents])
3394            if ([torrent isActive] || [torrent waitingToStart])
3395                return YES;
3396        return NO;
3397    }
3398   
3399    //enable resume item
3400    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
3401    {
3402        for (Torrent * torrent in [fTableView selectedTorrents])
3403            if (![torrent isActive] && ![torrent waitingToStart])
3404                return YES;
3405        return NO;
3406    }
3407   
3408    //set info image
3409    if ([ident isEqualToString: TOOLBAR_INFO])
3410    {
3411        [(NSButton *)[toolbarItem view] setState: [[fInfoController window] isVisible]];
3412        return YES;
3413    }
3414   
3415    //set filter image
3416    if ([ident isEqualToString: TOOLBAR_FILTER])
3417    {
3418        [(NSButton *)[toolbarItem view] setState: ![fFilterBar isHidden]];
3419        return YES;
3420    }
3421
3422    return YES;
3423}
3424
3425- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
3426{
3427    SEL action = [menuItem action];
3428   
3429    if (action == @selector(toggleSpeedLimit:))
3430    {
3431        [menuItem setState: [fDefaults boolForKey: @"SpeedLimit"] ? NSOnState : NSOffState];
3432        return YES;
3433    }
3434   
3435    //only enable some items if it is in a context menu or the window is useable
3436    BOOL canUseTable = [fWindow isKeyWindow] || [[menuItem menu] supermenu] != [NSApp mainMenu];
3437
3438    //enable open items
3439    if (action == @selector(openShowSheet:) || action == @selector(openURLShowSheet:))
3440        return [fWindow attachedSheet] == nil;
3441   
3442    //enable sort options
3443    if (action == @selector(setSort:))
3444    {
3445        NSString * sortType;
3446        switch ([menuItem tag])
3447        {
3448            case SORT_ORDER_TAG:
3449                sortType = SORT_ORDER;
3450                break;
3451            case SORT_DATE_TAG:
3452                sortType = SORT_DATE;
3453                break;
3454            case SORT_NAME_TAG:
3455                sortType = SORT_NAME;
3456                break;
3457            case SORT_PROGRESS_TAG:
3458                sortType = SORT_PROGRESS;
3459                break;
3460            case SORT_STATE_TAG:
3461                sortType = SORT_STATE;
3462                break;
3463            case SORT_TRACKER_TAG:
3464                sortType = SORT_TRACKER;
3465                break;
3466            case SORT_ACTIVITY_TAG:
3467                sortType = SORT_ACTIVITY;
3468        }
3469       
3470        [menuItem setState: [sortType isEqualToString: [fDefaults stringForKey: @"Sort"]] ? NSOnState : NSOffState];
3471        return [fWindow isVisible];
3472    }
3473   
3474    //enable sort options
3475    if (action == @selector(setStatusLabel:))
3476    {
3477        NSString * statusLabel;
3478        switch ([menuItem tag])
3479        {
3480            case STATUS_RATIO_TOTAL_TAG:
3481                statusLabel = STATUS_RATIO_TOTAL;
3482                break;
3483            case STATUS_RATIO_SESSION_TAG:
3484                statusLabel = STATUS_RATIO_SESSION;
3485                break;
3486            case STATUS_TRANSFER_TOTAL_TAG:
3487                statusLabel = STATUS_TRANSFER_TOTAL;
3488                break;
3489            case STATUS_TRANSFER_SESSION_TAG:
3490                statusLabel = STATUS_TRANSFER_SESSION;
3491        }
3492       
3493        [menuItem setState: [statusLabel isEqualToString: [fDefaults stringForKey: @"StatusLabel"]] ? NSOnState : NSOffState];
3494        return YES;
3495    }
3496   
3497    if (action == @selector(setGroup:))
3498    {
3499        BOOL checked = NO;
3500       
3501        NSInteger index = [menuItem tag];
3502        for (Torrent * torrent in [fTableView selectedTorrents])
3503            if (index == [torrent groupValue])
3504            {
3505                checked = YES;
3506                break;
3507            }
3508       
3509        [menuItem setState: checked ? NSOnState : NSOffState];
3510        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3511    }
3512   
3513    if (action == @selector(setGroupFilter:))
3514    {
3515        [menuItem setState: [menuItem tag] == [fDefaults integerForKey: @"FilterGroup"] ? NSOnState : NSOffState];
3516        return YES;
3517    }
3518   
3519    if (action == @selector(toggleSmallView:))
3520    {
3521        [menuItem setState: [fDefaults boolForKey: @"SmallView"] ? NSOnState : NSOffState];
3522        return [fWindow isVisible];
3523    }
3524   
3525    if (action == @selector(togglePiecesBar:))
3526    {
3527        [menuItem setState: [fDefaults boolForKey: @"PiecesBar"] ? NSOnState : NSOffState];
3528        return [fWindow isVisible];
3529    }
3530   
3531    if (action == @selector(toggleStatusString:))
3532    {
3533        if ([fDefaults boolForKey: @"SmallView"])
3534        {
3535            [menuItem setTitle: NSLocalizedString(@"Remaining Time", "Action menu -> status string toggle")];
3536            [menuItem setState: ![fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? NSOnState : NSOffState];
3537        }
3538        else
3539        {
3540            [menuItem setTitle: NSLocalizedString(@"Status of Selected Files", "Action menu -> status string toggle")];
3541            [menuItem setState: [fDefaults boolForKey: @"DisplayStatusProgressSelected"] ? NSOnState : NSOffState];
3542        }
3543       
3544        return [fWindow isVisible];
3545    }
3546   
3547    if (action == @selector(toggleAvailabilityBar:))
3548    {
3549        [menuItem setState: [fDefaults boolForKey: @"DisplayProgressBarAvailable"] ? NSOnState : NSOffState];
3550        return [fWindow isVisible];
3551    }
3552   
3553    if (action == @selector(setLimitGlobalEnabled:))
3554    {
3555        BOOL upload = [menuItem menu] == fUploadMenu;
3556        BOOL limit = menuItem == (upload ? fUploadLimitItem : fDownloadLimitItem);
3557        if (limit)
3558            [menuItem setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
3559                                    "Action menu -> upload/download limit"),
3560                                    [fDefaults integerForKey: upload ? @"UploadLimit" : @"DownloadLimit"]]];
3561       
3562        [menuItem setState: [fDefaults boolForKey: upload ? @"CheckUpload" : @"CheckDownload"] ? limit : !limit];
3563        return YES;
3564    }
3565   
3566    if (action == @selector(setRatioGlobalEnabled:))
3567    {
3568        BOOL check = menuItem == fCheckRatioItem;
3569        if (check)
3570            [menuItem setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
3571                                    "Action menu -> ratio stop"), [fDefaults floatForKey: @"RatioLimit"]]];
3572       
3573        [menuItem setState: [fDefaults boolForKey: @"RatioCheck"] ? check : !check];
3574        return YES;
3575    }
3576
3577    //enable show info
3578    if (action == @selector(showInfo:))
3579    {
3580        NSString * title = [[fInfoController window] isVisible] ? NSLocalizedString(@"Hide Inspector", "View menu -> Inspector")
3581                            : NSLocalizedString(@"Show Inspector", "View menu -> Inspector");
3582        [menuItem setTitle: title];
3583
3584        return YES;
3585    }
3586   
3587    //enable prev/next inspector tab
3588    if (action == @selector(setInfoTab:))
3589        return [[fInfoController window] isVisible];
3590   
3591    //enable toggle status bar
3592    if (action == @selector(toggleStatusBar:))
3593    {
3594        NSString * title = [fStatusBar isHidden] ? NSLocalizedString(@"Show Status Bar", "View menu -> Status Bar")
3595                            : NSLocalizedString(@"Hide Status Bar", "View menu -> Status Bar");
3596        [menuItem setTitle: title];
3597
3598        return [fWindow isVisible];
3599    }
3600   
3601    //enable toggle filter bar
3602    if (action == @selector(toggleFilterBar:))
3603    {
3604        NSString * title = [fFilterBar isHidden] ? NSLocalizedString(@"Show Filter Bar", "View menu -> Filter Bar")
3605                            : NSLocalizedString(@"Hide Filter Bar", "View menu -> Filter Bar");
3606        [menuItem setTitle: title];
3607
3608        return [fWindow isVisible];
3609    }
3610   
3611    //enable prev/next filter button
3612    if (action == @selector(switchFilter:))
3613        return [fWindow isVisible] && ![fFilterBar isHidden];
3614   
3615    //enable reveal in finder
3616    if (action == @selector(revealFile:))
3617        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3618
3619    //enable remove items
3620    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:))
3621    {
3622        BOOL warning = NO;
3623       
3624        for (Torrent * torrent in [fTableView selectedTorrents])
3625        {
3626            if ([torrent isActive])
3627            {
3628                if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? ![torrent isSeeding] : YES)
3629                {
3630                    warning = YES;
3631                    break;
3632                }
3633            }
3634        }
3635   
3636        //append or remove ellipsis when needed
3637        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
3638        if (warning && [fDefaults boolForKey: @"CheckRemove"])
3639        {
3640            if (![title hasSuffix: ellipsis])
3641                [menuItem setTitle: [title stringByAppendingEllipsis]];
3642        }
3643        else
3644        {
3645            if ([title hasSuffix: ellipsis])
3646                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
3647        }
3648       
3649        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3650    }
3651
3652    //enable pause all item
3653    if (action == @selector(stopAllTorrents:))
3654    {
3655        for (Torrent * torrent in fTorrents)
3656            if ([torrent isActive] || [torrent waitingToStart])
3657                return YES;
3658        return NO;
3659    }
3660   
3661    //enable resume all item
3662    if (action == @selector(resumeAllTorrents:))
3663    {
3664        for (Torrent * torrent in fTorrents)
3665            if (![torrent isActive] && ![torrent waitingToStart])
3666                return YES;
3667        return NO;
3668    }
3669   
3670    //enable resume all waiting item
3671    if (action == @selector(resumeWaitingTorrents:))
3672    {
3673        if (![fDefaults boolForKey: @"Queue"] && ![fDefaults boolForKey: @"QueueSeed"])
3674            return NO;
3675   
3676        for (Torrent * torrent in fTorrents)
3677            if (![torrent isActive] && [torrent waitingToStart])
3678                return YES;
3679        return NO;
3680    }
3681   
3682    //enable resume selected waiting item
3683    if (action == @selector(resumeSelectedTorrentsNoWait:))
3684    {
3685        if (!canUseTable)
3686            return NO;
3687       
3688        for (Torrent * torrent in [fTableView selectedTorrents])
3689            if (![torrent isActive])
3690                return YES;
3691        return NO;
3692    }
3693
3694    //enable pause item
3695    if (action == @selector(stopSelectedTorrents:))
3696    {
3697        if (!canUseTable)
3698            return NO;
3699   
3700        for (Torrent * torrent in [fTableView selectedTorrents])
3701            if ([torrent isActive] || [torrent waitingToStart])
3702                return YES;
3703        return NO;
3704    }
3705   
3706    //enable resume item
3707    if (action == @selector(resumeSelectedTorrents:))
3708    {
3709        if (!canUseTable)
3710            return NO;
3711   
3712        for (Torrent * torrent in [fTableView selectedTorrents])
3713            if (![torrent isActive] && ![torrent waitingToStart])
3714                return YES;
3715        return NO;
3716    }
3717   
3718    //enable manual announce item
3719    if (action == @selector(announceSelectedTorrents:))
3720    {
3721        if (!canUseTable)
3722            return NO;
3723       
3724        for (Torrent * torrent in [fTableView selectedTorrents])
3725            if ([torrent canManualAnnounce])
3726                return YES;
3727        return NO;
3728    }
3729   
3730    //enable reset cache item
3731    if (action == @selector(verifySelectedTorrents:))
3732        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3733   
3734    //enable move torrent file item
3735    if (action == @selector(moveDataFilesSelected:))
3736        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3737   
3738    //enable copy torrent file item
3739    if (action == @selector(copyTorrentFiles:))
3740        return canUseTable && [fTableView numberOfSelectedRows] > 0;
3741   
3742    //enable reverse sort item
3743    if (action == @selector(setSortReverse:))
3744    {
3745        [menuItem setState: [fDefaults boolForKey: @"SortReverse"] ? NSOnState : NSOffState];
3746        return ![[fDefaults stringForKey: @"Sort"] isEqualToString: SORT_ORDER];
3747    }
3748   
3749    //enable group sort item
3750    if (action == @selector(setSortByGroup:))
3751    {
3752        [menuItem setState: [fDefaults boolForKey: @"SortByGroup"] ? NSOnState : NSOffState];
3753        return YES;
3754    }
3755   
3756    //check proper filter search item
3757    if (action == @selector(setFilterSearchType:))
3758    {
3759        NSString * filterType = [fDefaults stringForKey: @"FilterSearchType"];
3760       
3761        BOOL state;
3762        if ([menuItem tag] == FILTER_TYPE_TAG_TRACKER)
3763            state = [filterType isEqualToString: FILTER_TYPE_TRACKER];
3764        else
3765            state = [filterType isEqualToString: FILTER_TYPE_NAME];
3766       
3767        [menuItem setState: state ? NSOnState : NSOffState];
3768        return YES;
3769    }
3770   
3771    //quick look only works on 10.6
3772    if (action == @selector(toggleQuickLook:))
3773        return [NSApp isOnSnowLeopardOrBetter];
3774   
3775    return YES;
3776}
3777
3778- (void) sleepCallback: (natural_t) messageType argument: (void *) messageArgument
3779{
3780    switch (messageType)
3781    {
3782        case kIOMessageSystemWillSleep:
3783            //if there are any running transfers, wait 15 seconds for them to stop
3784            for (Torrent * torrent in fTorrents)
3785                if ([torrent isActive])
3786                {
3787                    //stop all transfers (since some are active) before going to sleep and remember to resume when we wake up
3788                    for (Torrent * torrent in fTorrents)
3789                        [torrent sleep];
3790                    sleep(15);
3791                    break;
3792                }
3793
3794            IOAllowPowerChange(fRootPort, (long) messageArgument);
3795            break;
3796
3797        case kIOMessageCanSystemSleep:
3798            if ([fDefaults boolForKey: @"SleepPrevent"])
3799            {
3800                //prevent idle sleep unless no torrents are active
3801                for (Torrent * torrent in fTorrents)
3802                    if ([torrent isActive] && ![torrent isStalled] && ![torrent isError])
3803                    {
3804                        IOCancelPowerChange(fRootPort, (long) messageArgument);
3805                        return;
3806                    }
3807            }
3808           
3809            IOAllowPowerChange(fRootPort, (long) messageArgument);
3810            break;
3811
3812        case kIOMessageSystemHasPoweredOn:
3813            //resume sleeping transfers after we wake up
3814            for (Torrent * torrent in fTorrents)
3815                [torrent wakeUp];
3816            #warning check speed limit timer?
3817            //[self autoSpeedLimitChange: nil];
3818            break;
3819    }
3820}
3821
3822- (NSMenu *) applicationDockMenu: (NSApplication *) sender
3823{
3824    NSInteger seeding = 0, downloading = 0;
3825    for (Torrent * torrent in fTorrents)
3826    {
3827        if ([torrent isSeeding])
3828            seeding++;
3829        else if ([torrent isActive])
3830            downloading++;
3831        else;
3832    }
3833   
3834    NSMenuItem * seedingItem = [fDockMenu itemWithTag: DOCK_SEEDING_TAG],
3835            * downloadingItem = [fDockMenu itemWithTag: DOCK_DOWNLOADING_TAG];
3836   
3837    BOOL hasSeparator = seedingItem || downloadingItem;
3838   
3839    if (seeding > 0)
3840    {
3841        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Seeding", "Dock item - Seeding"), seeding];
3842        if (!seedingItem)
3843        {
3844            seedingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3845            [seedingItem setTag: DOCK_SEEDING_TAG];
3846            [fDockMenu insertItem: seedingItem atIndex: 0];
3847        }
3848        else
3849            [seedingItem setTitle: title];
3850    }
3851    else
3852    {
3853        if (seedingItem)
3854            [fDockMenu removeItem: seedingItem];
3855    }
3856   
3857    if (downloading > 0)
3858    {
3859        NSString * title = [NSString stringWithFormat: NSLocalizedString(@"%d Downloading", "Dock item - Downloading"), downloading];
3860        if (!downloadingItem)
3861        {
3862            downloadingItem = [[[NSMenuItem alloc] initWithTitle: title action: nil keyEquivalent: @""] autorelease];
3863            [downloadingItem setTag: DOCK_DOWNLOADING_TAG];
3864            [fDockMenu insertItem: downloadingItem atIndex: seeding > 0 ? 1 : 0];
3865        }
3866        else
3867            [downloadingItem setTitle: title];
3868    }
3869    else
3870    {
3871        if (downloadingItem)
3872            [fDockMenu removeItem: downloadingItem];
3873    }
3874   
3875    if (seeding > 0 || downloading > 0)
3876    {
3877        if (!hasSeparator)
3878            [fDockMenu insertItem: [NSMenuItem separatorItem] atIndex: seeding > 0 && downloading > 0 ? 2 : 1];
3879    }
3880    else
3881    {
3882        if (hasSeparator)
3883            [fDockMenu removeItemAtIndex: 0];
3884    }
3885   
3886    return fDockMenu;
3887}
3888
3889- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
3890{
3891    //if auto size is enabled, the current frame shouldn't need to change
3892    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame] : [self sizedWindowFrame];
3893   
3894    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
3895    return frame;
3896}
3897
3898- (void) setWindowSizeToFit
3899{
3900    if ([fDefaults boolForKey: @"AutoSize"])
3901    {
3902        NSScrollView * scrollView = [fTableView enclosingScrollView];
3903       
3904        [scrollView setHasVerticalScroller: NO];
3905        [fWindow setFrame: [self sizedWindowFrame] display: YES animate: YES];
3906        [scrollView setHasVerticalScroller: YES];
3907       
3908        //hack to ensure scrollbars don't disappear after resizing
3909        [scrollView setAutohidesScrollers: NO];
3910        [scrollView setAutohidesScrollers: YES];
3911    }
3912}
3913
3914- (NSRect) sizedWindowFrame
3915{
3916    NSInteger groups = ([fDisplayedTorrents count] > 0 && ![[fDisplayedTorrents objectAtIndex: 0] isKindOfClass: [Torrent class]])
3917                    ? [fDisplayedTorrents count] : 0;
3918   
3919    CGFloat heightChange = (GROUP_SEPARATOR_HEIGHT + [fTableView intercellSpacing].height) * groups
3920                        + ([fTableView rowHeight] + [fTableView intercellSpacing].height) * ([fTableView numberOfRows] - groups)
3921                        - [[fTableView enclosingScrollView] frame].size.height;
3922   
3923    return [self windowFrameByAddingHeight: heightChange checkLimits: YES];
3924}
3925
3926- (void) updateForExpandCollape
3927{
3928    [self setWindowSizeToFit];
3929    [self setBottomCountText: YES];
3930}
3931
3932- (void) showMainWindow: (id) sender
3933{
3934    [fWindow makeKeyAndOrderFront: nil];
3935}
3936
3937- (void) windowDidBecomeMain: (NSNotification *) notification
3938{
3939    [fBadger clearCompleted];
3940    [self updateUI];
3941}
3942
3943- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
3944{
3945    //only resize horizontally if autosize is enabled
3946    if ([fDefaults boolForKey: @"AutoSize"])
3947        proposedFrameSize.height = [fWindow frame].size.height;
3948    return proposedFrameSize;
3949}
3950
3951- (void) windowDidResize: (NSNotification *) notification
3952{
3953    if (![fStatusBar isHidden])
3954        [self resizeStatusButton];
3955   
3956    if ([fFilterBar isHidden])
3957        return;
3958   
3959    //replace all buttons
3960    [fNoFilterButton sizeToFit];
3961    [fActiveFilterButton sizeToFit];
3962    [fDownloadFilterButton sizeToFit];
3963    [fSeedFilterButton sizeToFit];
3964    [fPauseFilterButton sizeToFit];
3965   
3966    NSRect allRect = [fNoFilterButton frame];
3967    NSRect activeRect = [fActiveFilterButton frame];
3968    NSRect downloadRect = [fDownloadFilterButton frame];
3969    NSRect seedRect = [fSeedFilterButton frame];
3970    NSRect pauseRect = [fPauseFilterButton frame];
3971   
3972    //size search filter to not overlap buttons
3973    NSRect searchFrame = [fSearchFilterField frame];
3974    searchFrame.origin.x = NSMaxX(pauseRect) + 5.0;
3975    searchFrame.size.width = [fStatusBar frame].size.width - searchFrame.origin.x - 5.0;
3976   
3977    //make sure it is not too long
3978    if (searchFrame.size.width > SEARCH_FILTER_MAX_WIDTH)
3979    {
3980        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MAX_WIDTH;
3981        searchFrame.size.width = SEARCH_FILTER_MAX_WIDTH;
3982    }
3983    else if (searchFrame.size.width < SEARCH_FILTER_MIN_WIDTH)
3984    {
3985        searchFrame.origin.x += searchFrame.size.width - SEARCH_FILTER_MIN_WIDTH;
3986        searchFrame.size.width = SEARCH_FILTER_MIN_WIDTH;
3987       
3988        //calculate width the buttons can take up
3989        const CGFloat allowedWidth = (searchFrame.origin.x - 5.0) - allRect.origin.x;
3990        const CGFloat currentWidth = NSWidth(allRect) + NSWidth(activeRect) + NSWidth(downloadRect) + NSWidth(seedRect)
3991                                        + NSWidth(pauseRect) + 4.0; //add 4 for space between buttons
3992        const CGFloat ratio = allowedWidth / currentWidth;
3993       
3994        //decrease button widths proportionally
3995        allRect.size.width  = NSWidth(allRect) * ratio;
3996        activeRect.size.width = NSWidth(activeRect) * ratio;
3997        downloadRect.size.width = NSWidth(downloadRect) * ratio;
3998        seedRect.size.width = NSWidth(seedRect) * ratio;
3999        pauseRect.size.width = NSWidth(pauseRect) * ratio;
4000    }
4001    else;
4002   
4003    activeRect.origin.x = NSMaxX(allRect) + 1.0;
4004    downloadRect.origin.x = NSMaxX(activeRect) + 1.0;
4005    seedRect.origin.x = NSMaxX(downloadRect) + 1.0;
4006    pauseRect.origin.x = NSMaxX(seedRect) + 1.0;
4007   
4008    [fNoFilterButton setFrame: allRect];
4009    [fActiveFilterButton setFrame: activeRect];
4010    [fDownloadFilterButton setFrame: downloadRect];
4011    [fSeedFilterButton setFrame: seedRect];
4012    [fPauseFilterButton setFrame: pauseRect];
4013   
4014    [fSearchFilterField setFrame: searchFrame];
4015}
4016
4017- (void) applicationWillUnhide: (NSNotification *) notification
4018{
4019    [self updateUI];
4020}
4021
4022- (void) toggleQuickLook: (id) sender
4023{
4024    if (![NSApp isOnSnowLeopardOrBetter])
4025        return;
4026   
4027    if ([[QLPreviewPanelSL sharedPreviewPanel] isVisible])
4028        [[QLPreviewPanelSL sharedPreviewPanel] orderOut: nil];
4029    else
4030        [[QLPreviewPanelSL sharedPreviewPanel] makeKeyAndOrderFront: nil];
4031}
4032
4033- (void) linkHomepage: (id) sender
4034{
4035    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
4036}
4037
4038- (void) linkForums: (id) sender
4039{
4040    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
4041}
4042
4043- (void) linkTrac: (id) sender
4044{
4045    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: TRAC_URL]];
4046}
4047
4048- (void) linkDonate: (id) sender
4049{
4050    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: DONATE_URL]];
4051}
4052
4053- (void) updaterWillRelaunchApplication: (SUUpdater *) updater
4054{
4055    fUpdateInProgress = YES;
4056}
4057
4058- (NSDictionary *) registrationDictionaryForGrowl
4059{
4060    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE, GROWL_SEEDING_COMPLETE,
4061                                                            GROWL_AUTO_ADD, GROWL_AUTO_SPEED_LIMIT, nil];
4062    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
4063                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
4064}
4065
4066- (void) growlNotificationWasClicked: (id) clickContext
4067{
4068    if (!clickContext || ![clickContext isKindOfClass: [NSDictionary class]])
4069        return;
4070   
4071    NSString * type = [clickContext objectForKey: @"Type"], * location;
4072    if (([type isEqualToString: GROWL_DOWNLOAD_COMPLETE] || [type isEqualToString: GROWL_SEEDING_COMPLETE])
4073            && (location = [clickContext objectForKey: @"Location"]))
4074    {
4075        if ([NSApp isOnSnowLeopardOrBetter])
4076        {
4077            NSURL * file = [NSURL fileURLWithPath: location];
4078            [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
4079        }
4080        else
4081            [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
4082    }
4083}
4084
4085- (void) rpcCallback: (tr_rpc_callback_type) type forTorrentStruct: (struct tr_torrent *) torrentStruct
4086{
4087    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
4088   
4089    //get the torrent
4090    Torrent * torrent = nil;
4091    if (torrentStruct != NULL && (type != TR_RPC_TORRENT_ADDED && type != TR_RPC_SESSION_CHANGED))
4092    {
4093        for (torrent in fTorrents)
4094            if (torrentStruct == [torrent torrentStruct])
4095            {
4096                [torrent retain];
4097                break;
4098            }
4099       
4100        if (!torrent)
4101        {
4102            [pool release];
4103           
4104            NSLog(@"No torrent found matching the given torrent struct from the RPC callback!");
4105            return;
4106        }
4107    }
4108   
4109    switch (type)
4110    {
4111        case TR_RPC_TORRENT_ADDED:
4112            [self performSelectorOnMainThread: @selector(rpcAddTorrentStruct:) withObject:
4113                [[NSValue valueWithPointer: torrentStruct] retain] waitUntilDone: NO];
4114            break;
4115       
4116        case TR_RPC_TORRENT_STARTED:
4117        case TR_RPC_TORRENT_STOPPED:
4118            [self performSelectorOnMainThread: @selector(rpcStartedStoppedTorrent:) withObject: torrent waitUntilDone: NO];
4119            break;
4120       
4121        case TR_RPC_TORRENT_REMOVING:
4122            [self performSelectorOnMainThread: @selector(rpcRemoveTorrent:) withObject: torrent waitUntilDone: NO];
4123            break;
4124       
4125        case TR_RPC_TORRENT_CHANGED:
4126            [self performSelectorOnMainThread: @selector(rpcChangedTorrent:) withObject: torrent waitUntilDone: NO];
4127            break;
4128       
4129        case TR_RPC_SESSION_CHANGED:
4130            [fPrefsController performSelectorOnMainThread: @selector(rpcUpdatePrefs) withObject: nil waitUntilDone: NO];
4131            break;
4132       
4133        default:
4134            NSLog(@"Unknown RPC command received (%d)", type);
4135            [torrent release];
4136    }
4137   
4138    [pool drain];
4139}
4140
4141- (void) rpcAddTorrentStruct: (NSValue *) torrentStructPtr
4142{
4143    tr_torrent * torrentStruct = (tr_torrent *)[torrentStructPtr pointerValue];
4144    [torrentStructPtr release];
4145   
4146    NSString * location = nil;
4147    if (tr_torrentGetDownloadDir(torrentStruct) != NULL)
4148        location = [NSString stringWithUTF8String: tr_torrentGetDownloadDir(torrentStruct)];
4149   
4150    Torrent * torrent = [[Torrent alloc] initWithTorrentStruct: torrentStruct location: location lib: fLib];
4151   
4152    [torrent update];
4153    [fTorrents addObject: torrent];
4154    [torrent release];
4155   
4156    [self updateTorrentsInQueue];
4157}
4158
4159- (void) rpcRemoveTorrent: (Torrent *) torrent
4160{
4161    [self confirmRemoveTorrents: [[NSArray arrayWithObject: torrent] retain] deleteData: NO];
4162    [torrent release];
4163}
4164
4165- (void) rpcStartedStoppedTorrent: (Torrent *) torrent
4166{
4167    [torrent update];
4168    [torrent release];
4169   
4170    [self updateUI];
4171    [self applyFilter: nil];
4172    [self updateTorrentHistory];
4173}
4174
4175- (void) rpcChangedTorrent: (Torrent *) torrent
4176{
4177    [torrent update];
4178   
4179    if ([[fTableView selectedTorrents] containsObject: torrent])
4180    {
4181        [fInfoController updateInfoStats]; //this will reload the file table
4182        [fInfoController updateOptions];
4183    }
4184   
4185    [torrent release];
4186}
4187
4188@end
Note: See TracBrowser for help on using the repository browser.