source: trunk/macosx/PrefsController.m @ 7514

Last change on this file since 7514 was 7514, checked in by livings124, 12 years ago

eliminate some more enumerator objects

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