source: trunk/macosx/PrefsController.m @ 8153

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

warnings--

  • Property svn:keywords set to Date Rev Author Id
File size: 48.0 KB
Line 
1/******************************************************************************
2 * $Id: PrefsController.m 8153 2009-04-05 17:48:03Z livings124 $
3 *
4 * Copyright (c) 2005-2009 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import "PrefsController.h"
26#import "BlocklistDownloaderViewController.h"
27#import "BlocklistScheduler.h"
28#import "PortChecker.h"
29#import "BonjourController.h"
30#import "NSStringAdditions.h"
31#import "UKKQueue.h"
32#import "utils.h"
33
34#import <Sparkle/Sparkle.h>
35
36#define DOWNLOAD_FOLDER     0
37#define DOWNLOAD_TORRENT    2
38
39#define SCHED_ALL_TAG       0
40#define SCHED_WEEKDAY_TAG   1
41#define SCHED_WEEKEND_TAG   2
42#define SCHED_MON_TAG       3
43#define SCHED_TUES_TAG      4
44#define SCHED_WED_TAG       5
45#define SCHED_THURS_TAG     6
46#define SCHED_FRI_TAG       7
47#define SCHED_SAT_TAG       8
48#define SCHED_SUN_TAG       9
49
50#define PROXY_HTTP      0
51#define PROXY_SOCKS4    1
52#define PROXY_SOCKS5    2
53
54#define RPC_IP_ADD_TAG      0
55#define RPC_IP_REMOVE_TAG   1
56
57#define TOOLBAR_GENERAL     @"TOOLBAR_GENERAL"
58#define TOOLBAR_TRANSFERS   @"TOOLBAR_TRANSFERS"
59#define TOOLBAR_GROUPS      @"TOOLBAR_GROUPS"
60#define TOOLBAR_BANDWIDTH   @"TOOLBAR_BANDWIDTH"
61#define TOOLBAR_PEERS       @"TOOLBAR_PEERS"
62#define TOOLBAR_NETWORK     @"TOOLBAR_NETWORK"
63#define TOOLBAR_REMOTE      @"TOOLBAR_REMOTE"
64
65#define PROXY_KEYCHAIN_SERVICE  "Transmission:Proxy"
66#define PROXY_KEYCHAIN_NAME     "Proxy"
67
68#define RPC_KEYCHAIN_SERVICE    "Transmission:Remote"
69#define RPC_KEYCHAIN_NAME       "Remote"
70
71#define WEBUI_URL   @"http://localhost:%d/transmission/web/"
72
73@interface PrefsController (Private)
74
75- (void) setPrefView: (id) sender;
76
77- (void) folderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info;
78- (void) incompleteFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info;
79- (void) importFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info;
80
81- (void) setKeychainPassword: (const char *) password forService: (const char *) service username: (const char *) username;
82
83@end
84
85@implementation PrefsController
86
87tr_session * fHandle;
88+ (void) setHandle: (tr_session *) handle
89{
90    fHandle = handle;
91}
92
93+ (tr_session *) handle
94{
95    return fHandle;
96}
97
98- (id) init
99{
100    if ((self = [super initWithWindowNibName: @"PrefsWindow"]))
101    {
102        fDefaults = [NSUserDefaults standardUserDefaults];
103       
104        //check for old version download location (before 1.1)
105        NSString * choice;
106        if ((choice = [fDefaults stringForKey: @"DownloadChoice"]))
107        {
108            [fDefaults setBool: [choice isEqualToString: @"Constant"] forKey: @"DownloadLocationConstant"];
109            [fDefaults setBool: YES forKey: @"DownloadAsk"];
110           
111            [fDefaults removeObjectForKey: @"DownloadChoice"];
112        }
113       
114        //set auto speed limit day
115        [self updateAutoSpeedLimitDay];
116       
117        //save a new random port
118        if ([fDefaults boolForKey: @"RandomPort"])
119            [fDefaults setInteger: tr_sessionGetPeerPort(fHandle) forKey: @"BindPort"];
120       
121        //set auto import
122        NSString * autoPath;
123        if ([fDefaults boolForKey: @"AutoImport"] && (autoPath = [fDefaults stringForKey: @"AutoImportDirectory"]))
124            [[UKKQueue sharedFileWatcher] addPath: [autoPath stringByExpandingTildeInPath]];
125       
126        //set blocklist scheduler
127        [[BlocklistScheduler scheduler] updateSchedule];
128       
129        //set encryption
130        [self setEncryptionMode: nil];
131       
132        //set proxy type
133        [self updateProxyType];
134        [self updateProxyPassword];
135       
136        //update rpc whitelist
137        [self updateRPCPassword];
138       
139        fRPCWhitelistArray = [[fDefaults arrayForKey: @"RPCWhitelist"] mutableCopy];
140        if (!fRPCWhitelistArray)
141            fRPCWhitelistArray = [[NSMutableArray arrayWithObject: @"127.0.0.1"] retain];
142        [self updateRPCWhitelist];
143       
144        //reset old Sparkle settings from previous versions
145        [fDefaults removeObjectForKey: @"SUScheduledCheckInterval"];
146        if ([fDefaults objectForKey: @"CheckForUpdates"])
147        {
148            [[SUUpdater sharedUpdater] setAutomaticallyChecksForUpdates: [fDefaults boolForKey: @"CheckForUpdates"]];
149            [fDefaults removeObjectForKey: @"CheckForUpdates"];
150        }
151       
152        [self setAutoUpdateToBeta: nil];
153    }
154   
155    return self;
156}
157
158- (void) dealloc
159{
160    [[NSNotificationCenter defaultCenter] removeObserver: self];
161   
162    [fPortStatusTimer invalidate];
163    if (fPortChecker)
164    {
165        [fPortChecker cancelProbe];
166        [fPortChecker release];
167    }
168   
169    [fRPCWhitelistArray release];
170   
171    [fRPCPassword release];
172   
173    [super dealloc];
174}
175
176- (void) awakeFromNib
177{
178    fHasLoaded = YES;
179   
180    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"Preferences Toolbar"];
181    [toolbar setDelegate: self];
182    [toolbar setAllowsUserCustomization: NO];
183    [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
184    [toolbar setSizeMode: NSToolbarSizeModeRegular];
185    [toolbar setSelectedItemIdentifier: TOOLBAR_GENERAL];
186    [[self window] setToolbar: toolbar];
187    [toolbar release];
188   
189    [self setPrefView: nil];
190   
191    //set download folder
192    [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT];
193   
194    //set stop ratio
195    [fRatioStopField setFloatValue: [fDefaults floatForKey: @"RatioLimit"]];
196   
197    //set limits
198    [self updateLimitFields];
199   
200    //set speed limit
201    [fSpeedLimitUploadField setIntValue: [fDefaults integerForKey: @"SpeedLimitUploadLimit"]];
202    [fSpeedLimitDownloadField setIntValue: [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]];
203   
204    int schedDay;
205    switch (tr_sessionGetAltSpeedDay(fHandle))
206    {
207        case TR_SCHED_ALL:
208            schedDay = SCHED_ALL_TAG;
209            break;
210        case TR_SCHED_WEEKDAY:
211            schedDay = SCHED_WEEKDAY_TAG;
212            break;
213        case TR_SCHED_WEEKEND:
214            schedDay = SCHED_WEEKEND_TAG;
215            break;
216        case TR_SCHED_MON:
217            schedDay = SCHED_MON_TAG;
218            break;
219        case TR_SCHED_TUES:
220            schedDay = SCHED_TUES_TAG;
221            break;
222        case TR_SCHED_WED:
223            schedDay = SCHED_WED_TAG;
224            break;
225        case TR_SCHED_THURS:
226            schedDay = SCHED_THURS_TAG;
227            break;
228        case TR_SCHED_FRI:
229            schedDay = SCHED_FRI_TAG;
230            break;
231        case TR_SCHED_SAT:
232            schedDay = SCHED_SAT_TAG;
233            break;
234        case TR_SCHED_SUN:
235            schedDay = SCHED_SUN_TAG;
236            break;
237    }
238    [fAutoSpeedDayTypePopUp selectItemWithTag: schedDay];
239   
240    //set port
241    [fPortField setIntValue: [fDefaults integerForKey: @"BindPort"]];
242    fNatStatus = -1;
243   
244    [self updatePortStatus];
245    fPortStatusTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target: self
246                        selector: @selector(updatePortStatus) userInfo: nil repeats: YES];
247   
248    //set peer connections
249    [fPeersGlobalField setIntValue: [fDefaults integerForKey: @"PeersTotal"]];
250    [fPeersTorrentField setIntValue: [fDefaults integerForKey: @"PeersTorrent"]];
251   
252    //set queue values
253    [fQueueDownloadField setIntValue: [fDefaults integerForKey: @"QueueDownloadNumber"]];
254    [fQueueSeedField setIntValue: [fDefaults integerForKey: @"QueueSeedNumber"]];
255    [fStalledField setIntValue: [fDefaults integerForKey: @"StalledMinutes"]];
256   
257    //set proxy type
258    [fProxyAddressField setStringValue: [fDefaults stringForKey: @"ProxyAddress"]];
259    int proxyType;
260    switch (tr_sessionGetProxyType(fHandle))
261    {
262        case TR_PROXY_SOCKS4:
263            proxyType = PROXY_SOCKS4;
264            break;
265        case TR_PROXY_SOCKS5:
266            proxyType = PROXY_SOCKS5;
267            break;
268        case TR_PROXY_HTTP:
269            proxyType = PROXY_HTTP;
270    }
271    [fProxyTypePopUp selectItemAtIndex: proxyType];
272   
273    //set proxy password - does NOT need to be released
274    [fProxyPasswordField setStringValue: [NSString stringWithUTF8String: tr_sessionGetProxyPassword(fHandle)]];
275   
276    //set proxy port
277    [fProxyPortField setIntValue: [fDefaults integerForKey: @"ProxyPort"]];
278   
279    //set blocklist
280    [self updateBlocklistFields];
281    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateBlocklistFields)
282        name: @"BlocklistUpdated" object: nil];
283   
284    //set rpc port
285    [fRPCPortField setIntValue: [fDefaults integerForKey: @"RPCPort"]];
286   
287    //set rpc password
288    if (fRPCPassword)
289        [fRPCPasswordField setStringValue: fRPCPassword];
290}
291
292- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
293{
294    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
295
296    if ([ident isEqualToString: TOOLBAR_GENERAL])
297    {
298        [item setLabel: NSLocalizedString(@"General", "Preferences -> toolbar item title")];
299        [item setImage: [NSImage imageNamed: NSImageNamePreferencesGeneral]];
300        [item setTarget: self];
301        [item setAction: @selector(setPrefView:)];
302        [item setAutovalidates: NO];
303    }
304    else if ([ident isEqualToString: TOOLBAR_TRANSFERS])
305    {
306        [item setLabel: NSLocalizedString(@"Transfers", "Preferences -> toolbar item title")];
307        [item setImage: [NSImage imageNamed: @"Transfers.png"]];
308        [item setTarget: self];
309        [item setAction: @selector(setPrefView:)];
310        [item setAutovalidates: NO];
311    }
312    else if ([ident isEqualToString: TOOLBAR_GROUPS])
313    {
314        [item setLabel: NSLocalizedString(@"Groups", "Preferences -> toolbar item title")];
315        [item setImage: [NSImage imageNamed: @"Groups.png"]];
316        [item setTarget: self];
317        [item setAction: @selector(setPrefView:)];
318        [item setAutovalidates: NO];
319    }
320    else if ([ident isEqualToString: TOOLBAR_BANDWIDTH])
321    {
322        [item setLabel: NSLocalizedString(@"Bandwidth", "Preferences -> toolbar item title")];
323        [item setImage: [NSImage imageNamed: @"Bandwidth.png"]];
324        [item setTarget: self];
325        [item setAction: @selector(setPrefView:)];
326        [item setAutovalidates: NO];
327    }
328    else if ([ident isEqualToString: TOOLBAR_PEERS])
329    {
330        [item setLabel: NSLocalizedString(@"Peers", "Preferences -> toolbar item title")];
331        [item setImage: [NSImage imageNamed: NSImageNameUserGroup]];
332        [item setTarget: self];
333        [item setAction: @selector(setPrefView:)];
334        [item setAutovalidates: NO];
335    }
336    else if ([ident isEqualToString: TOOLBAR_NETWORK])
337    {
338        [item setLabel: NSLocalizedString(@"Network", "Preferences -> toolbar item title")];
339        [item setImage: [NSImage imageNamed: NSImageNameNetwork]];
340        [item setTarget: self];
341        [item setAction: @selector(setPrefView:)];
342        [item setAutovalidates: NO];
343    }
344    else if ([ident isEqualToString: TOOLBAR_REMOTE])
345    {
346        [item setLabel: NSLocalizedString(@"Remote", "Preferences -> toolbar item title")];
347        [item setImage: [NSImage imageNamed: @"Remote.png"]];
348        [item setTarget: self];
349        [item setAction: @selector(setPrefView:)];
350        [item setAutovalidates: NO];
351    }
352    else
353    {
354        [item release];
355        return nil;
356    }
357
358    return [item autorelease];
359}
360
361- (NSArray *) toolbarSelectableItemIdentifiers: (NSToolbar *) toolbar
362{
363    return [self toolbarDefaultItemIdentifiers: toolbar];
364}
365
366- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
367{
368    return [self toolbarAllowedItemIdentifiers: toolbar];
369}
370
371- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
372{
373    return [NSArray arrayWithObjects: TOOLBAR_GENERAL, TOOLBAR_TRANSFERS, TOOLBAR_GROUPS, TOOLBAR_BANDWIDTH,
374                                        TOOLBAR_PEERS, TOOLBAR_NETWORK, TOOLBAR_REMOTE, nil];
375}
376
377//for a beta release, always use the beta appcast
378#if defined(TR_BETA_RELEASE)
379#define SPARKLE_TAG YES
380#else
381#define SPARKLE_TAG [fDefaults boolForKey: @"AutoUpdateBeta"]
382#endif
383- (void) setAutoUpdateToBeta: (id) sender
384{
385    [[SUUpdater sharedUpdater] setAllowedTags: SPARKLE_TAG ? [NSSet setWithObject: @"beta"] : nil];
386}
387
388- (void) setPort: (id) sender
389{
390    const int port = [sender intValue];
391    [fDefaults setInteger: port forKey: @"BindPort"];
392    tr_sessionSetPeerPort(fHandle, port);
393   
394    fPeerPort = -1;
395    [self updatePortStatus];
396}
397
398- (void) randomPort: (id) sender
399{
400    const tr_port port = tr_sessionSetPeerPortRandom(fHandle);
401   
402    [fPortField setIntValue: port];
403    [self setPort: fPortField];
404}
405
406- (void) setRandomPortOnStart: (id) sender
407{
408    tr_sessionSetPeerPortRandomOnStart(fHandle, [sender state] == NSOnState);
409}
410
411- (void) setNat: (id) sender
412{
413    tr_sessionSetPortForwardingEnabled(fHandle, [fDefaults boolForKey: @"NatTraversal"]);
414   
415    fNatStatus = -1;
416    [self updatePortStatus];
417}
418
419- (void) updatePortStatus
420{
421    const tr_port_forwarding fwd = tr_sessionGetPortForwarding(fHandle);
422    const int port = tr_sessionGetPeerPort(fHandle);
423    BOOL natStatusChanged = (fNatStatus != fwd);
424    BOOL peerPortChanged = (fPeerPort != port);
425
426    if (natStatusChanged || peerPortChanged)
427    {
428        fNatStatus = fwd;
429        fPeerPort = port;
430       
431        [fPortStatusField setStringValue: @""];
432        [fPortStatusImage setImage: nil];
433        [fPortStatusProgress startAnimation: self];
434       
435        if (fPortChecker)
436        {
437            [fPortChecker cancelProbe];
438            [fPortChecker release];
439        }
440        BOOL delay = natStatusChanged || tr_sessionIsPortForwardingEnabled(fHandle);
441        fPortChecker = [[PortChecker alloc] initForPort: fPeerPort delay: delay withDelegate: self];
442    }
443}
444
445- (void) portCheckerDidFinishProbing: (PortChecker *) portChecker
446{
447    [fPortStatusProgress stopAnimation: self];
448    switch ([fPortChecker status])
449    {
450        case PORT_STATUS_OPEN:
451            [fPortStatusField setStringValue: NSLocalizedString(@"Port is open", "Preferences -> Network -> port status")];
452            [fPortStatusImage setImage: [NSImage imageNamed: @"GreenDot.png"]];
453            break;
454        case PORT_STATUS_CLOSED:
455            [fPortStatusField setStringValue: NSLocalizedString(@"Port is closed", "Preferences -> Network -> port status")];
456            [fPortStatusImage setImage: [NSImage imageNamed: @"RedDot.png"]];
457            break;
458        case PORT_STATUS_ERROR:
459            [fPortStatusField setStringValue: NSLocalizedString(@"Port check site is down", "Preferences -> Network -> port status")];
460            [fPortStatusImage setImage: [NSImage imageNamed: @"YellowDot.png"]];
461            break;
462    }
463    [fPortChecker release];
464    fPortChecker = nil;
465}
466
467- (NSArray *) sounds
468{
469    NSMutableArray * sounds = [NSMutableArray array];
470   
471    NSArray * directories = [NSArray arrayWithObjects: @"/System/Library/Sounds", @"/Library/Sounds", @"Library/Sounds", nil];
472   
473    for (NSString * directory in directories)
474    {
475        BOOL isDirectory;
476        if ([[NSFileManager defaultManager] fileExistsAtPath: directory isDirectory: &isDirectory] && isDirectory)
477        {
478            NSArray * directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: directory];
479            for (NSString * sound in directoryContents)
480            {
481                sound = [sound stringByDeletingPathExtension];
482                if ([NSSound soundNamed: sound])
483                    [sounds addObject: sound];
484            }
485        }
486    }
487   
488    return sounds;
489}
490
491- (void) setSound: (id) sender
492{
493    //play sound when selecting
494    NSSound * sound;
495    if ((sound = [NSSound soundNamed: [sender titleOfSelectedItem]]))
496        [sound play];
497}
498
499- (void) setPeersGlobal: (id) sender
500{
501    const int count = [sender intValue];
502    [fDefaults setInteger: count forKey: @"PeersTotal"];
503    tr_sessionSetPeerLimit(fHandle, count);
504}
505
506- (void) setPeersTorrent: (id) sender
507{
508    const int count = [sender intValue];
509    [fDefaults setInteger: count forKey: @"PeersTorrent"];
510}
511
512- (void) setPEX: (id) sender
513{
514    tr_sessionSetPexEnabled(fHandle, [fDefaults boolForKey: @"PEXGlobal"]);
515}
516
517- (void) setEncryptionMode: (id) sender
518{
519    const tr_encryption_mode mode = [fDefaults boolForKey: @"EncryptionPrefer"] ?
520        ([fDefaults boolForKey: @"EncryptionRequire"] ? TR_ENCRYPTION_REQUIRED : TR_ENCRYPTION_PREFERRED) : TR_CLEAR_PREFERRED;
521    tr_sessionSetEncryption(fHandle, mode);
522}
523
524- (void) setBlocklistEnabled: (id) sender
525{
526    const BOOL enable = [sender state] == NSOnState;
527    [fDefaults setBool: enable forKey: @"Blocklist"];
528    tr_blocklistSetEnabled(fHandle, enable);
529   
530    [[BlocklistScheduler scheduler] updateSchedule];
531}
532
533- (void) updateBlocklist: (id) sender
534{
535    [BlocklistDownloaderViewController downloadWithPrefsController: self];
536}
537
538- (void) setBlocklistAutoUpdate: (id) sender
539{
540    [[BlocklistScheduler scheduler] updateSchedule];
541}
542
543- (void) updateBlocklistFields
544{
545    const BOOL exists = tr_blocklistExists(fHandle);
546   
547    if (exists)
548    {
549        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
550        [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
551        [numberFormatter setMaximumFractionDigits: 0];
552        NSString * countString = [numberFormatter stringFromNumber: [NSNumber numberWithInt: tr_blocklistGetRuleCount(fHandle)]];
553        [numberFormatter release];
554       
555        [fBlocklistMessageField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ IP address rules in list",
556            "Prefs -> blocklist -> message"), countString]];
557    }
558    else
559        [fBlocklistMessageField setStringValue: NSLocalizedString(@"A blocklist must first be downloaded",
560            "Prefs -> blocklist -> message")];
561   
562    [fBlocklistEnableCheck setEnabled: exists];
563    [fBlocklistEnableCheck setState: exists && [fDefaults boolForKey: @"Blocklist"]];
564   
565    NSString * updatedDateString;
566    if (exists)
567    {
568        NSDate * updatedDate = [fDefaults objectForKey: @"BlocklistLastUpdate"];
569        if (updatedDate)
570        {
571            NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
572            [dateFormatter setDateStyle: NSDateFormatterFullStyle];
573            [dateFormatter setTimeStyle: NSDateFormatterShortStyle];
574           
575            updatedDateString = [dateFormatter stringFromDate: updatedDate];
576            [dateFormatter release];
577        }
578        else
579            updatedDateString = NSLocalizedString(@"N/A", "Prefs -> blocklist -> message");
580    }
581    else
582        updatedDateString = NSLocalizedString(@"Never", "Prefs -> blocklist -> message");
583   
584    [fBlocklistDateField setStringValue: [NSString stringWithFormat: @"%@: %@",
585        NSLocalizedString(@"Last updated", "Prefs -> blocklist -> message"), updatedDateString]];
586}
587
588- (void) applySpeedSettings: (id) sender
589{
590    tr_sessionLimitSpeed(fHandle, TR_UP, [fDefaults boolForKey: @"CheckUpload"]);
591    tr_sessionSetSpeedLimit(fHandle, TR_UP, [fDefaults integerForKey: @"UploadLimit"]);
592   
593    tr_sessionLimitSpeed(fHandle, TR_DOWN, [fDefaults boolForKey: @"CheckDownload"]);
594    tr_sessionSetSpeedLimit(fHandle, TR_DOWN, [fDefaults integerForKey: @"DownloadLimit"]);
595   
596    [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil];
597}
598
599- (void) applyAltSpeedSettings
600{
601    tr_sessionSetAltSpeed(fHandle, TR_UP, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]);
602    tr_sessionSetAltSpeed(fHandle, TR_DOWN, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]);
603       
604    [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil];
605}
606
607- (void) applyRatioSetting: (id) sender
608{
609    //[[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUI" object: nil];
610    tr_sessionSetRatioLimited(fHandle, [fDefaults boolForKey: @"RatioCheck"]);
611    tr_sessionSetRatioLimit(fHandle, [fDefaults floatForKey: @"RatioLimit"]);
612}
613
614- (void) updateRatioStopField
615{
616    if (fHasLoaded)
617        [fRatioStopField setFloatValue: [fDefaults floatForKey: @"RatioLimit"]];
618   
619    [self applyRatioSetting: nil];
620}
621
622- (void) setRatioStop: (id) sender
623{
624    [fDefaults setFloat: [sender floatValue] forKey: @"RatioLimit"];
625   
626    [self applyRatioSetting: nil];
627}
628
629- (void) updateLimitFields
630{
631    if (!fHasLoaded)
632        return;
633   
634    [fUploadField setIntValue: [fDefaults integerForKey: @"UploadLimit"]];
635    [fDownloadField setIntValue: [fDefaults integerForKey: @"DownloadLimit"]];
636}
637
638- (void) setGlobalLimit: (id) sender
639{
640    [fDefaults setInteger: [sender intValue] forKey: sender == fUploadField ? @"UploadLimit" : @"DownloadLimit"];
641    [self applySpeedSettings: self];
642}
643
644- (void) setSpeedLimit: (id) sender
645{
646    [fDefaults setInteger: [sender intValue] forKey: sender == fSpeedLimitUploadField
647                                                        ? @"SpeedLimitUploadLimit" : @"SpeedLimitDownloadLimit"];
648    [self applyAltSpeedSettings];
649}
650
651- (void) setAutoSpeedLimit: (id) sender
652{
653    tr_sessionUseAltSpeedTime(fHandle, [fDefaults boolForKey: @"SpeedLimitAuto"]);
654}
655
656- (void) setAutoSpeedLimitTime: (id) sender
657{
658    tr_sessionSetAltSpeedBegin(fHandle, [PrefsController dateToTimeSum: [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]]);
659    tr_sessionSetAltSpeedEnd(fHandle, [PrefsController dateToTimeSum: [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]]);
660}
661
662- (void) setAutoSpeedLimitDay: (id) sender
663{
664    NSString * day;
665    switch ([[sender selectedItem] tag])
666    {
667        case SCHED_ALL_TAG:
668            day = @"ALL";
669            break;
670        case SCHED_WEEKDAY_TAG:
671            day = @"WEEKDAY";
672            break;
673        case SCHED_WEEKEND_TAG:
674            day = @"WEEKEND";
675            break;
676        case SCHED_MON_TAG:
677            day = @"MON";
678            break;
679        case SCHED_TUES_TAG:
680            day = @"TUES";
681            break;
682        case SCHED_WED_TAG:
683            day = @"WED";
684            break;
685        case SCHED_THURS_TAG:
686            day = @"THURS";
687            break;
688        case SCHED_FRI_TAG:
689            day = @"FRI";
690            break;
691        case SCHED_SAT_TAG:
692            day = @"SAT";
693            break;
694        case SCHED_SUN_TAG:
695            day = @"SUN";
696            break;
697    }
698   
699    [fDefaults setObject: day forKey: @"SpeedLimitAutoDay"];
700    [self updateAutoSpeedLimitDay];
701}
702
703- (void) updateAutoSpeedLimitDay
704{
705    NSString * dayString = [fDefaults stringForKey: @"SpeedLimitAutoDay"];
706    tr_sched_day day;
707    if ([dayString isEqualToString: @"WEEKDAY"])
708        day = TR_SCHED_WEEKDAY;
709    else if ([dayString isEqualToString: @"WEEKEND"])
710        day = TR_SCHED_WEEKEND;
711    else if ([dayString isEqualToString: @"MON"])
712        day = TR_SCHED_MON;
713    else if ([dayString isEqualToString: @"TUES"])
714        day = TR_SCHED_TUES;
715    else if ([dayString isEqualToString: @"WED"])
716        day = TR_SCHED_WED;
717    else if ([dayString isEqualToString: @"THURS"])
718        day = TR_SCHED_THURS;
719    else if ([dayString isEqualToString: @"FRI"])
720        day = TR_SCHED_FRI;
721    else if ([dayString isEqualToString: @"SAT"])
722        day = TR_SCHED_SAT;
723    else if ([dayString isEqualToString: @"SUN"])
724        day = TR_SCHED_SUN;
725    else
726    {
727        //safety
728        if (![dayString isEqualToString: @"ALL"])
729        {
730            dayString = @"ALL";
731            [fDefaults setObject: dayString forKey: @"SpeedLimitAutoDay"];
732        }
733        day = TR_SCHED_ALL;
734    }
735   
736    tr_sessionSetAltSpeedDay(fHandle, day);
737}
738
739+ (NSInteger) dateToTimeSum: (NSDate *) date
740{
741    NSCalendar * calendar = [NSCalendar currentCalendar];
742    NSDateComponents * components = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: date];
743    return [components hour] * 60 + [components minute];
744}
745
746+ (NSDate *) timeSumToDate: (NSInteger) sum
747{
748    NSDateComponents * comps = [[[NSDateComponents alloc] init] autorelease];
749    [comps setHour: sum / 60];
750    [comps setMinute: sum % 60];
751   
752    return [[NSCalendar currentCalendar] dateFromComponents: comps];
753}
754
755- (BOOL) control: (NSControl *) control textShouldBeginEditing: (NSText *) fieldEditor
756{
757    [fInitialString release];
758    fInitialString = [[control stringValue] retain];
759   
760    return YES;
761}
762
763- (BOOL) control: (NSControl *) control didFailToFormatString: (NSString *) string errorDescription: (NSString *) error
764{
765    NSBeep();
766    if (fInitialString)
767    {
768        [control setStringValue: fInitialString];
769        [fInitialString release];
770        fInitialString = nil;
771    }
772    return NO;
773}
774
775- (void) setBadge: (id) sender
776{
777    [[NSNotificationCenter defaultCenter] postNotificationName: @"DockBadgeChange" object: self];
778}
779
780- (void) resetWarnings: (id) sender
781{
782    [fDefaults removeObjectForKey: @"WarningDuplicate"];
783    [fDefaults removeObjectForKey: @"WarningRemainingSpace"];
784    [fDefaults removeObjectForKey: @"WarningFolderDataSameName"];
785    [fDefaults removeObjectForKey: @"WarningResetStats"];
786    [fDefaults removeObjectForKey: @"WarningCreatorBlankAddress"];
787    [fDefaults removeObjectForKey: @"WarningRemoveBuiltInTracker"];
788    [fDefaults removeObjectForKey: @"WarningInvalidOpen"];
789}
790
791- (void) setQueue: (id) sender
792{
793    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
794}
795
796- (void) setQueueNumber: (id) sender
797{
798    [fDefaults setInteger: [sender intValue] forKey: sender == fQueueDownloadField ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
799    [self setQueue: nil];
800}
801
802- (void) setStalled: (id) sender
803{
804    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
805}
806
807- (void) setStalledMinutes: (id) sender
808{
809    [fDefaults setInteger: [sender intValue] forKey: @"StalledMinutes"];
810    [self setStalled: nil];
811}
812
813- (void) setDownloadLocation: (id) sender
814{
815    [fDefaults setBool: [fFolderPopUp indexOfSelectedItem] == DOWNLOAD_FOLDER forKey: @"DownloadLocationConstant"];
816}
817
818- (void) folderSheetShow: (id) sender
819{
820    NSOpenPanel * panel = [NSOpenPanel openPanel];
821
822    [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")];
823    [panel setAllowsMultipleSelection: NO];
824    [panel setCanChooseFiles: NO];
825    [panel setCanChooseDirectories: YES];
826    [panel setCanCreateDirectories: YES];
827
828    [panel beginSheetForDirectory: nil file: nil types: nil
829        modalForWindow: [self window] modalDelegate: self didEndSelector:
830        @selector(folderSheetClosed:returnCode:contextInfo:) contextInfo: nil];
831}
832
833- (void) incompleteFolderSheetShow: (id) sender
834{
835    NSOpenPanel * panel = [NSOpenPanel openPanel];
836
837    [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")];
838    [panel setAllowsMultipleSelection: NO];
839    [panel setCanChooseFiles: NO];
840    [panel setCanChooseDirectories: YES];
841    [panel setCanCreateDirectories: YES];
842
843    [panel beginSheetForDirectory: nil file: nil types: nil
844        modalForWindow: [self window] modalDelegate: self didEndSelector:
845        @selector(incompleteFolderSheetClosed:returnCode:contextInfo:) contextInfo: nil];
846}
847
848- (void) setAutoImport: (id) sender
849{
850    NSString * path;
851    if ((path = [fDefaults stringForKey: @"AutoImportDirectory"]))
852    {
853        path = [path stringByExpandingTildeInPath];
854        if ([fDefaults boolForKey: @"AutoImport"])
855            [[UKKQueue sharedFileWatcher] addPath: path];
856        else
857            [[UKKQueue sharedFileWatcher] removePathFromQueue: path];
858       
859        [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoImportSettingChange" object: self];
860    }
861    else
862        [self importFolderSheetShow: nil];
863}
864
865- (void) importFolderSheetShow: (id) sender
866{
867    NSOpenPanel * panel = [NSOpenPanel openPanel];
868
869    [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")];
870    [panel setAllowsMultipleSelection: NO];
871    [panel setCanChooseFiles: NO];
872    [panel setCanChooseDirectories: YES];
873    [panel setCanCreateDirectories: YES];
874
875    [panel beginSheetForDirectory: nil file: nil types: nil
876        modalForWindow: [self window] modalDelegate: self didEndSelector:
877        @selector(importFolderSheetClosed:returnCode:contextInfo:) contextInfo: nil];
878}
879
880- (void) setAutoSize: (id) sender
881{
882    [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoSizeSettingChange" object: self];
883}
884
885- (void) setProxyEnabled: (id) sender
886{
887    tr_sessionSetProxyEnabled(fHandle, [fDefaults boolForKey: @"Proxy"]);
888}
889
890- (void) setProxyAddress: (id) sender
891{
892    NSString * address = [sender stringValue];
893    tr_sessionSetProxy(fHandle, [address UTF8String]);
894    [fDefaults setObject: address forKey: @"ProxyAddress"];
895}
896
897- (void) setProxyPort: (id) sender
898{
899    int port = [sender intValue];
900    [fDefaults setInteger: port forKey: @"ProxyPort"];
901    tr_sessionSetProxyPort(fHandle, port);
902}
903
904- (void) setProxyType: (id) sender
905{
906    NSString * type;
907    switch ([sender indexOfSelectedItem])
908    {
909        case PROXY_HTTP:
910            type = @"HTTP";
911            break;
912        case PROXY_SOCKS4:
913            type = @"SOCKS4";
914            break;
915        case PROXY_SOCKS5:
916            type = @"SOCKS5";
917    }
918   
919    [fDefaults setObject: type forKey: @"ProxyType"];
920    [self updateProxyType];
921}
922
923- (void) updateProxyType
924{
925    NSString * typeString = [fDefaults stringForKey: @"ProxyType"];
926    tr_proxy_type type;
927    if ([typeString isEqualToString: @"SOCKS4"])
928        type = TR_PROXY_SOCKS4;
929    else if ([typeString isEqualToString: @"SOCKS5"])
930        type = TR_PROXY_SOCKS5;
931    else
932    {
933        //safety
934        if (![typeString isEqualToString: @"HTTP"])
935        {
936            typeString = @"HTTP";
937            [fDefaults setObject: typeString forKey: @"ProxyType"];
938        }
939        type = TR_PROXY_HTTP;
940    }
941   
942    tr_sessionSetProxyType(fHandle, type);
943}
944
945- (void) setProxyAuthorize: (id) sender
946{
947    BOOL enable = [fDefaults boolForKey: @"ProxyAuthorize"];
948    tr_sessionSetProxyAuthEnabled(fHandle, enable);
949}
950
951- (void) setProxyUsername: (id) sender
952{
953    tr_sessionSetProxyUsername(fHandle, [[fDefaults stringForKey: @"ProxyUsername"] UTF8String]);
954}
955
956- (void) setProxyPassword: (id) sender
957{
958    const char * password = [[sender stringValue] UTF8String];
959    [self setKeychainPassword: password forService: PROXY_KEYCHAIN_SERVICE username: PROXY_KEYCHAIN_NAME];
960   
961    tr_sessionSetProxyPassword(fHandle, password);
962}
963
964- (void) updateProxyPassword
965{
966    UInt32 passwordLength;
967    const char * password = nil;
968    SecKeychainFindGenericPassword(NULL, strlen(PROXY_KEYCHAIN_SERVICE), PROXY_KEYCHAIN_SERVICE,
969        strlen(PROXY_KEYCHAIN_NAME), PROXY_KEYCHAIN_NAME, &passwordLength, (void **)&password, NULL);
970   
971    if (password != NULL)
972    {
973        char fullPassword[passwordLength+1];
974        strncpy(fullPassword, password, passwordLength);
975        fullPassword[passwordLength] = '\0';
976        SecKeychainItemFreeContent(NULL, (void *)password);
977       
978        tr_sessionSetProxyPassword(fHandle, fullPassword);
979        [fProxyPasswordField setStringValue: [NSString stringWithUTF8String: fullPassword]];
980    }
981}
982
983- (void) setRPCEnabled: (id) sender
984{
985    BOOL enable = [fDefaults boolForKey: @"RPC"];
986    tr_sessionSetRPCEnabled(fHandle, enable);
987   
988    [self setRPCWebUIDiscovery: nil];
989}
990
991- (void) linkWebUI: (id) sender
992{
993    NSString * urlString = [NSString stringWithFormat: WEBUI_URL, [fDefaults integerForKey: @"RPCPort"]];
994    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: urlString]];
995}
996
997- (void) setRPCAuthorize: (id) sender
998{
999    tr_sessionSetRPCPasswordEnabled(fHandle, [fDefaults boolForKey: @"RPCAuthorize"]);
1000}
1001
1002- (void) setRPCUsername: (id) sender
1003{
1004    tr_sessionSetRPCUsername(fHandle, [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
1005}
1006
1007- (void) setRPCPassword: (id) sender
1008{
1009    [fRPCPassword release];
1010    fRPCPassword = [[sender stringValue] copy];
1011   
1012    const char * password = [[sender stringValue] UTF8String];
1013    [self setKeychainPassword: password forService: RPC_KEYCHAIN_SERVICE username: RPC_KEYCHAIN_NAME];
1014   
1015    tr_sessionSetRPCPassword(fHandle, password);
1016}
1017
1018- (void) updateRPCPassword
1019{
1020    UInt32 passwordLength;
1021    const char * password = nil;
1022    SecKeychainFindGenericPassword(NULL, strlen(RPC_KEYCHAIN_SERVICE), RPC_KEYCHAIN_SERVICE,
1023        strlen(RPC_KEYCHAIN_NAME), RPC_KEYCHAIN_NAME, &passwordLength, (void **)&password, NULL);
1024   
1025    [fRPCPassword release];
1026    if (password != NULL)
1027    {
1028        char fullPassword[passwordLength+1];
1029        strncpy(fullPassword, password, passwordLength);
1030        fullPassword[passwordLength] = '\0';
1031        SecKeychainItemFreeContent(NULL, (void *)password);
1032       
1033        tr_sessionSetRPCPassword(fHandle, fullPassword);
1034       
1035        fRPCPassword = [[NSString alloc] initWithUTF8String: fullPassword];
1036        [fRPCPasswordField setStringValue: fRPCPassword];
1037    }
1038    else
1039        fRPCPassword = nil;
1040}
1041
1042- (void) setRPCPort: (id) sender
1043{
1044    int port = [sender intValue];
1045    [fDefaults setInteger: port forKey: @"RPCPort"];
1046    tr_sessionSetRPCPort(fHandle, port);
1047   
1048    [self setRPCWebUIDiscovery: nil];
1049}
1050
1051- (void) setRPCUseWhitelist: (id) sender
1052{
1053    tr_sessionSetRPCWhitelistEnabled(fHandle, [fDefaults boolForKey: @"RPCUseWhitelist"]);
1054}
1055
1056- (void) setRPCWebUIDiscovery: (id) sender
1057{
1058    if ([fDefaults boolForKey:@"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"])
1059        [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]];
1060    else
1061        [[BonjourController defaultController] stop];
1062}
1063
1064- (void) updateRPCWhitelist
1065{
1066    NSString * string = [fRPCWhitelistArray componentsJoinedByString: @","];
1067    tr_sessionSetRPCWhitelist(fHandle, [string UTF8String]);
1068}
1069
1070- (void) addRemoveRPCIP: (id) sender
1071{
1072    //don't allow add/remove when currently adding - it leads to weird results
1073    if ([fRPCWhitelistTable editedRow] != -1)
1074        return;
1075   
1076    if ([[sender cell] tagForSegment: [sender selectedSegment]] == RPC_IP_REMOVE_TAG)
1077    {
1078        [fRPCWhitelistArray removeObjectsAtIndexes: [fRPCWhitelistTable selectedRowIndexes]];
1079        [fRPCWhitelistTable deselectAll: self];
1080        [fRPCWhitelistTable reloadData];
1081       
1082        [fDefaults setObject: fRPCWhitelistArray forKey: @"RPCWhitelist"];
1083        [self updateRPCWhitelist];
1084    }
1085    else
1086    {
1087        [fRPCWhitelistArray addObject: @""];
1088        [fRPCWhitelistTable reloadData];
1089       
1090        int row = [fRPCWhitelistArray count] - 1;
1091        [fRPCWhitelistTable selectRow: row byExtendingSelection: NO];
1092        [fRPCWhitelistTable editColumn: 0 row: row withEvent: nil select: YES];
1093    }
1094}
1095
1096- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
1097{
1098    return [fRPCWhitelistArray count];
1099}
1100
1101- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row
1102{
1103    return [fRPCWhitelistArray objectAtIndex: row];
1104}
1105
1106- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn
1107    row: (NSInteger) row
1108{
1109    NSArray * components = [object componentsSeparatedByString: @"."];
1110    NSMutableArray * newComponents = [NSMutableArray arrayWithCapacity: 4];
1111       
1112    //create better-formatted ip string
1113    BOOL valid = false;
1114    if ([components count] == 4)
1115    {
1116        valid = true;
1117        for (NSString * component in components)
1118        {
1119            if ([component isEqualToString: @"*"])
1120                [newComponents addObject: component];
1121            else
1122            {
1123                int num = [component intValue];
1124                if (num >= 0 && num < 256)
1125                    [newComponents addObject: [[NSNumber numberWithInt: num] stringValue]];
1126                else
1127                {
1128                    valid = false;
1129                    break;
1130                }
1131            }
1132        }
1133    }
1134   
1135    NSString * newIP;
1136    if (valid)
1137    {
1138        newIP = [newComponents componentsJoinedByString: @"."];
1139       
1140        //don't allow the same ip address
1141        if ([fRPCWhitelistArray containsObject: newIP] && ![[fRPCWhitelistArray objectAtIndex: row] isEqualToString: newIP])
1142            valid = false;
1143    }
1144   
1145    if (valid)
1146    {
1147        [fRPCWhitelistArray replaceObjectAtIndex: row withObject: newIP];
1148        [fRPCWhitelistArray sortUsingSelector: @selector(compareNumeric:)];
1149    }
1150    else
1151    {
1152        NSBeep();
1153        if ([[fRPCWhitelistArray objectAtIndex: row] isEqualToString: @""])
1154            [fRPCWhitelistArray removeObjectAtIndex: row];
1155    }
1156       
1157    [fRPCWhitelistTable deselectAll: self];
1158    [fRPCWhitelistTable reloadData];
1159   
1160    [fDefaults setObject: fRPCWhitelistArray forKey: @"RPCWhitelist"];
1161    [self updateRPCWhitelist];
1162}
1163
1164- (void) tableViewSelectionDidChange: (NSNotification *) notification
1165{
1166    [fRPCAddRemoveControl setEnabled: [fRPCWhitelistTable numberOfSelectedRows] > 0 forSegment: RPC_IP_REMOVE_TAG];
1167}
1168
1169- (void) helpForPeers: (id) sender
1170{
1171    [[NSHelpManager sharedHelpManager] openHelpAnchor: @"PeersPrefs"
1172        inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]];
1173}
1174
1175- (void) helpForNetwork: (id) sender
1176{
1177    [[NSHelpManager sharedHelpManager] openHelpAnchor: @"NetworkPrefs"
1178        inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]];
1179}
1180
1181- (void) helpForRemote: (id) sender
1182{
1183    [[NSHelpManager sharedHelpManager] openHelpAnchor: @"RemotePrefs"
1184        inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]];
1185}
1186
1187#warning probably needs to be updated
1188- (void) rpcUpdatePrefs
1189{
1190    //encryption
1191    const tr_encryption_mode encryptionMode = tr_sessionGetEncryption(fHandle);
1192    [fDefaults setBool: encryptionMode != TR_CLEAR_PREFERRED forKey: @"EncryptionPrefer"];
1193    [fDefaults setBool: encryptionMode == TR_ENCRYPTION_REQUIRED forKey: @"EncryptionRequire"];
1194   
1195    //download directory
1196    NSString * downloadLocation = [[NSString stringWithUTF8String: tr_sessionGetDownloadDir(fHandle)] stringByStandardizingPath];
1197    [fDefaults setObject: downloadLocation forKey: @"DownloadFolder"];
1198   
1199    //peers
1200    const uint16_t peersTotal = tr_sessionGetPeerLimit(fHandle);
1201    [fDefaults setInteger: peersTotal forKey: @"PeersTotal"];
1202   
1203    const uint16_t peersTorrent = tr_sessionGetPeerLimitPerTorrent(fHandle);
1204    [fDefaults setInteger: peersTotal forKey: @"PeersTorrent"];
1205   
1206    //pex
1207    const BOOL pex = tr_sessionIsPexEnabled(fHandle);
1208    [fDefaults setBool: pex forKey: @"PEXGlobal"];
1209   
1210    //port
1211    const tr_port port = tr_sessionGetPeerPort(fHandle);
1212    [fDefaults setInteger: port forKey: @"BindPort"];
1213   
1214    const BOOL nat = tr_sessionIsPortForwardingEnabled(fHandle);
1215    [fDefaults setBool: nat forKey: @"NatTraversal"];
1216   
1217    fPeerPort = -1;
1218    fNatStatus = -1;
1219    [self updatePortStatus];
1220   
1221    const BOOL randomPort = tr_sessionGetPeerPortRandomOnStart(fHandle);
1222    [fDefaults setBool: randomPort forKey: @"RandomPort"];
1223   
1224    //speed limit - down
1225    const BOOL downLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_DOWN);
1226    [fDefaults setBool: downLimitEnabled forKey: @"CheckDownload"];
1227   
1228    const int downLimit = tr_sessionGetSpeedLimit(fHandle, TR_DOWN);
1229    [fDefaults setInteger: downLimit forKey: @"DownloadLimit"];
1230   
1231    //speed limit - up
1232    const BOOL upLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_UP);
1233    [fDefaults setBool: upLimitEnabled forKey: @"CheckUpload"];
1234   
1235    const int upLimit = tr_sessionGetSpeedLimit(fHandle, TR_UP);
1236    [fDefaults setInteger: upLimit forKey: @"UploadLimit"];
1237   
1238    //alt speed limit enabled
1239    const BOOL useAltSpeed = tr_sessionUsesAltSpeed(fHandle);
1240    [fDefaults setBool: useAltSpeed forKey: @"SpeedLimit"];
1241   
1242    //alt speed limit - down
1243    const int downLimitAlt = tr_sessionGetAltSpeed(fHandle, TR_DOWN);
1244    [fDefaults setInteger: downLimit forKey: @"SpeedLimitDownloadLimit"];
1245   
1246    //alt speed limit - up
1247    const int upLimitAlt = tr_sessionGetAltSpeed(fHandle, TR_UP);
1248    [fDefaults setInteger: upLimitAlt forKey: @"SpeedLimitDownloadLimit"];
1249   
1250    //alt speed limit schedule
1251    const BOOL useAltSpeedSched = tr_sessionUsesAltSpeedTime(fHandle);
1252    [fDefaults setBool: useAltSpeedSched forKey: @"SpeedLimitAuto"];
1253   
1254    NSDate * limitStartDate = [PrefsController timeSumToDate: tr_sessionGetAltSpeedBegin(fHandle)];
1255    [fDefaults setObject: limitStartDate forKey: @"SpeedLimitAutoOnDate"];
1256   
1257    NSDate * limitEndDate = [PrefsController timeSumToDate: tr_sessionGetAltSpeedEnd(fHandle)];
1258    [fDefaults setObject: limitEndDate forKey: @"SpeedLimitAutoOffDate"];
1259   
1260    #warning refactor how to work with schedule day
1261   
1262    //blocklist
1263    const BOOL blocklist = tr_blocklistIsEnabled(fHandle);
1264    [fDefaults setBool: blocklist forKey: @"Blocklist"];
1265   
1266    //seed ratio
1267    const BOOL ratioLimited = tr_sessionIsRatioLimited(fHandle);
1268    [fDefaults setBool: ratioLimited forKey: @"RatioCheck"];
1269   
1270    const float ratioLimit = tr_sessionGetRatioLimit(fHandle);
1271    [fDefaults setFloat: ratioLimit forKey: @"RatioLimit"];
1272   
1273    //update gui if loaded
1274    if (fHasLoaded)
1275    {
1276        //encryption handled by bindings
1277       
1278        //download directory handled by bindings
1279       
1280        [fPeersGlobalField setIntValue: peersTotal];
1281        [fPeersTorrentField setIntValue: peersTorrent];
1282       
1283        //pex handled by bindings
1284       
1285        [fPortField setIntValue: port];
1286        //port forwarding (nat) handled by bindings
1287        //random port handled by bindings
1288       
1289        //limit check handled by bindings
1290        [fDownloadField setIntValue: downLimit];
1291       
1292        //limit check handled by bindings
1293        [fUploadField setIntValue: upLimit];
1294       
1295        [fSpeedLimitDownloadField setIntValue: downLimitAlt];
1296       
1297        [fSpeedLimitUploadField setIntValue: upLimitAlt];
1298       
1299        //speed limit schedule handled by bindings
1300       
1301        //speed limit schedule times handled by bindings
1302       
1303        #warning need to set schedule day
1304       
1305        [self updateBlocklistFields];
1306       
1307        //ratio limit enabled handled by bindings
1308        [fRatioStopField setFloatValue: ratioLimit];
1309    }
1310   
1311    [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil];
1312}
1313
1314@end
1315
1316@implementation PrefsController (Private)
1317
1318- (void) setPrefView: (id) sender
1319{
1320    NSString * identifier;
1321    if (sender)
1322    {
1323        identifier = [sender itemIdentifier];
1324        [[NSUserDefaults standardUserDefaults] setObject: identifier forKey: @"SelectedPrefView"];
1325    }
1326    else
1327        identifier = [[NSUserDefaults standardUserDefaults] stringForKey: @"SelectedPrefView"];
1328   
1329    NSView * view;
1330    if ([identifier isEqualToString: TOOLBAR_TRANSFERS])
1331        view = fTransfersView;
1332    else if ([identifier isEqualToString: TOOLBAR_GROUPS])
1333        view = fGroupsView;
1334    else if ([identifier isEqualToString: TOOLBAR_BANDWIDTH])
1335        view = fBandwidthView;
1336    else if ([identifier isEqualToString: TOOLBAR_PEERS])
1337        view = fPeersView;
1338    else if ([identifier isEqualToString: TOOLBAR_NETWORK])
1339        view = fNetworkView;
1340    else if ([identifier isEqualToString: TOOLBAR_REMOTE])
1341        view = fRemoteView;
1342    else
1343    {
1344        identifier = TOOLBAR_GENERAL; //general view is the default selected
1345        view = fGeneralView;
1346    }
1347   
1348    [[[self window] toolbar] setSelectedItemIdentifier: identifier];
1349   
1350    NSWindow * window = [self window];
1351    if ([window contentView] == view)
1352        return;
1353   
1354    NSRect windowRect = [window frame];
1355    float difference = ([view frame].size.height - [[window contentView] frame].size.height) * [window userSpaceScaleFactor];
1356    windowRect.origin.y -= difference;
1357    windowRect.size.height += difference;
1358   
1359    [view setHidden: YES];
1360    [window setContentView: view];
1361    [window setFrame: windowRect display: YES animate: YES];
1362    [view setHidden: NO];
1363   
1364    //set title label
1365    if (sender)
1366        [window setTitle: [sender label]];
1367    else
1368    {
1369        NSToolbar * toolbar = [window toolbar];
1370        NSString * itemIdentifier = [toolbar selectedItemIdentifier];
1371        for (NSToolbarItem * item in [toolbar items])
1372            if ([[item itemIdentifier] isEqualToString: itemIdentifier])
1373            {
1374                [window setTitle: [item label]];
1375                break;
1376            }
1377    }
1378}
1379
1380- (void) folderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1381{
1382    if (code == NSOKButton)
1383    {
1384        [fFolderPopUp selectItemAtIndex: DOWNLOAD_FOLDER];
1385       
1386        NSString * folder = [[openPanel filenames] objectAtIndex: 0];
1387        [fDefaults setObject: folder forKey: @"DownloadFolder"];
1388        [fDefaults setObject: @"Constant" forKey: @"DownloadChoice"];
1389       
1390        tr_sessionSetDownloadDir(fHandle, [folder UTF8String]);
1391    }
1392    else
1393    {
1394        //reset if cancelled
1395        [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT];
1396    }
1397}
1398
1399- (void) incompleteFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1400{
1401    if (code == NSOKButton)
1402        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
1403    [fIncompleteFolderPopUp selectItemAtIndex: 0];
1404}
1405
1406- (void) importFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1407{
1408    NSString * path = [fDefaults stringForKey: @"AutoImportDirectory"];
1409    if (code == NSOKButton)
1410    {
1411        UKKQueue * sharedQueue = [UKKQueue sharedFileWatcher];
1412        if (path)
1413            [sharedQueue removePathFromQueue: [path stringByExpandingTildeInPath]];
1414       
1415        path = [[openPanel filenames] objectAtIndex: 0];
1416        [fDefaults setObject: path forKey: @"AutoImportDirectory"];
1417        [sharedQueue addPath: [path stringByExpandingTildeInPath]];
1418       
1419        [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoImportSettingChange" object: self];
1420    }
1421    else if (!path)
1422        [fDefaults setBool: NO forKey: @"AutoImport"];
1423   
1424    [fImportFolderPopUp selectItemAtIndex: 0];
1425}
1426
1427- (void) setKeychainPassword: (const char *) password forService: (const char *) service username: (const char *) username
1428{
1429    SecKeychainItemRef item = NULL;
1430    NSUInteger passwordLength = strlen(password);
1431   
1432    OSStatus result = SecKeychainFindGenericPassword(NULL, strlen(service), service, strlen(username), username, NULL, NULL, &item);
1433    if (result == noErr && item)
1434    {
1435        if (passwordLength > 0) //found, so update
1436        {
1437            result = SecKeychainItemModifyAttributesAndData(item, NULL, passwordLength, (const void *)password);
1438            if (result != noErr)
1439                NSLog(@"Problem updating Keychain item: %s", GetMacOSStatusErrorString(result));
1440        }
1441        else //remove the item
1442        {
1443            result = SecKeychainItemDelete(item);
1444            if (result != noErr)
1445                NSLog(@"Problem removing Keychain item: %s", GetMacOSStatusErrorString(result));
1446        }
1447    }
1448    else if (result == errSecItemNotFound) //not found, so add
1449    {
1450        if (passwordLength > 0)
1451        {
1452            result = SecKeychainAddGenericPassword(NULL, strlen(service), service, strlen(username), username,
1453                        passwordLength, (const void *)password, NULL);
1454            if (result != noErr)
1455                NSLog(@"Problem adding Keychain item: %s", GetMacOSStatusErrorString(result));
1456        }
1457    }
1458    else
1459        NSLog(@"Problem accessing Keychain: %s", GetMacOSStatusErrorString(result));
1460}
1461
1462@end
Note: See TracBrowser for help on using the repository browser.