source: trunk/macosx/Controller.m @ 10480

Last change on this file since 10480 was 10480, checked in by charles, 12 years ago

(trunk) #1869 "new status for torrents that reached the seed ratio" -- add temporary debug messages to help track down the issue leena's reporting in that ticket

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