source: trunk/macosx/PrefsController.m @ 7727

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

allow checking for betas when autoupdate is off

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