source: trunk/macosx/PrefsController.m @ 7290

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

#1395 - patch from Waldorf: Bonjour support for Web Interface

  • Property svn:keywords set to Date Rev Author Id
File size: 41.4 KB
Line 
1/******************************************************************************
2 * $Id: PrefsController.m 7290 2008-12-06 01:18:25Z 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 "NSApplicationAdditions.h"
31#import "NSStringAdditions.h"
32#import "UKKQueue.h"
33#import "utils.h"
34
35#define DOWNLOAD_FOLDER     0
36#define DOWNLOAD_TORRENT    2
37
38#define PROXY_HTTP      0
39#define PROXY_SOCKS4    1
40#define PROXY_SOCKS5    2
41
42#define RPC_IP_ADD_TAG      0
43#define RPC_IP_REMOVE_TAG   1
44
45#define TOOLBAR_GENERAL     @"TOOLBAR_GENERAL"
46#define TOOLBAR_TRANSFERS   @"TOOLBAR_TRANSFERS"
47#define TOOLBAR_GROUPS      @"TOOLBAR_GROUPS"
48#define TOOLBAR_BANDWIDTH   @"TOOLBAR_BANDWIDTH"
49#define TOOLBAR_PEERS       @"TOOLBAR_PEERS"
50#define TOOLBAR_NETWORK     @"TOOLBAR_NETWORK"
51#define TOOLBAR_REMOTE      @"TOOLBAR_REMOTE"
52
53#define PROXY_KEYCHAIN_SERVICE  "Transmission:Proxy"
54#define PROXY_KEYCHAIN_NAME     "Proxy"
55
56#define RPC_KEYCHAIN_SERVICE    "Transmission:Remote"
57#define RPC_KEYCHAIN_NAME       "Remote"
58
59#define WEBUI_URL   @"http://localhost:%d/transmission/web/"
60
61@interface PrefsController (Private)
62
63- (void) setPrefView: (id) sender;
64
65- (void) folderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info;
66- (void) incompleteFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info;
67- (void) importFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info;
68
69- (void) setKeychainPassword: (const char *) password forService: (const char *) service username: (const char *) username;
70
71@end
72
73@implementation PrefsController
74
75tr_handle * fHandle;
76+ (void) setHandle: (tr_handle *) handle
77{
78    fHandle = handle;
79}
80
81+ (tr_handle *) handle
82{
83    return fHandle;
84}
85
86- (id) init
87{
88    if ((self = [super initWithWindowNibName: @"PrefsWindow"]))
89    {
90        fDefaults = [NSUserDefaults standardUserDefaults];
91       
92        //checks for old version speeds of -1
93        if ([fDefaults integerForKey: @"UploadLimit"] < 0)
94        {
95            [fDefaults removeObjectForKey: @"UploadLimit"];
96            [fDefaults setBool: NO forKey: @"CheckUpload"];
97        }
98        if ([fDefaults integerForKey: @"DownloadLimit"] < 0)
99        {
100            [fDefaults removeObjectForKey: @"DownloadLimit"];
101            [fDefaults setBool: NO forKey: @"CheckDownload"];
102        }
103       
104        //check for old version download location (before 1.1)
105        NSString * choice;
106        if ((choice = [fDefaults stringForKey: @"DownloadChoice"]))
107        {
108            [fDefaults setBool: [choice isEqualToString: @"Constant"] forKey: @"DownloadLocationConstant"];
109            [fDefaults setBool: YES forKey: @"DownloadAsk"];
110           
111            [fDefaults removeObjectForKey: @"DownloadChoice"];
112        }
113       
114        //set auto import
115        NSString * autoPath;
116        if ([fDefaults boolForKey: @"AutoImport"] && (autoPath = [fDefaults stringForKey: @"AutoImportDirectory"]))
117            [[UKKQueue sharedFileWatcher] addPath: [autoPath stringByExpandingTildeInPath]];
118       
119        //set blocklist scheduler
120        [[BlocklistScheduler scheduler] updateSchedule];
121       
122        //set encryption
123        [self setEncryptionMode: nil];
124       
125        //actually set bandwidth limits
126        [self applySpeedSettings: nil];
127       
128        //set proxy type
129        [self updateProxyType];
130        [self updateProxyPassword];
131       
132        //update rpc whitelist
133        [self updateRPCPassword];
134       
135        fRPCWhitelistArray = [[fDefaults arrayForKey: @"RPCWhitelist"] mutableCopy];
136        if (!fRPCWhitelistArray)
137            fRPCWhitelistArray = [[NSMutableArray arrayWithObject: @"127.0.0.1"] retain];
138        [self updateRPCWhitelist];
139    }
140   
141    return self;
142}
143
144- (void) dealloc
145{
146    [[NSNotificationCenter defaultCenter] removeObserver: self];
147   
148    [fPortStatusTimer invalidate];
149    if (fPortChecker)
150    {
151        [fPortChecker cancelProbe];
152        [fPortChecker release];
153    }
154   
155    [fRPCWhitelistArray release];
156   
157    [super dealloc];
158}
159
160- (void) awakeFromNib
161{
162    fHasLoaded = YES;
163   
164    NSToolbar * toolbar = [[NSToolbar alloc] initWithIdentifier: @"Preferences Toolbar"];
165    [toolbar setDelegate: self];
166    [toolbar setAllowsUserCustomization: NO];
167    [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
168    [toolbar setSizeMode: NSToolbarSizeModeRegular];
169    [toolbar setSelectedItemIdentifier: TOOLBAR_GENERAL];
170    [[self window] setToolbar: toolbar];
171    [toolbar release];
172   
173    [self setPrefView: nil];
174   
175    if (![NSApp isOnLeopardOrBetter])
176    {
177        [fRPCAddRemoveControl sizeToFit];
178        [fRPCAddRemoveControl setLabel: @"+" forSegment: RPC_IP_ADD_TAG];
179        [fRPCAddRemoveControl setLabel: @"-" forSegment: RPC_IP_REMOVE_TAG];
180    }
181   
182    //set download folder
183    [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT];
184   
185    //set stop ratio
186    [self updateRatioStopField];
187   
188    //set limits
189    [self updateLimitFields];
190   
191    //set speed limit
192    [fSpeedLimitUploadField setIntValue: [fDefaults integerForKey: @"SpeedLimitUploadLimit"]];
193    [fSpeedLimitDownloadField setIntValue: [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]];
194   
195    //set port
196    [fPortField setIntValue: [fDefaults integerForKey: @"BindPort"]];
197    fNatStatus = -1;
198   
199    [self updatePortStatus];
200    fPortStatusTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target: self
201                        selector: @selector(updatePortStatus) userInfo: nil repeats: YES];
202   
203    //set peer connections
204    [fPeersGlobalField setIntValue: [fDefaults integerForKey: @"PeersTotal"]];
205    [fPeersTorrentField setIntValue: [fDefaults integerForKey: @"PeersTorrent"]];
206   
207    //set queue values
208    [fQueueDownloadField setIntValue: [fDefaults integerForKey: @"QueueDownloadNumber"]];
209    [fQueueSeedField setIntValue: [fDefaults integerForKey: @"QueueSeedNumber"]];
210    [fStalledField setIntValue: [fDefaults integerForKey: @"StalledMinutes"]];
211   
212    //set proxy type
213    [fProxyAddressField setStringValue: [fDefaults stringForKey: @"ProxyAddress"]];
214    int proxyType;
215    switch(tr_sessionGetProxyType(fHandle))
216    {
217        case TR_PROXY_SOCKS4:
218            proxyType = PROXY_SOCKS4;
219            break;
220        case TR_PROXY_SOCKS5:
221            proxyType = PROXY_SOCKS5;
222            break;
223        case TR_PROXY_HTTP:
224            proxyType = PROXY_HTTP;
225    }
226    [fProxyTypePopUp selectItemAtIndex: proxyType];
227   
228    //set proxy password - does NOT need to be released
229    [fProxyPasswordField setStringValue: [NSString stringWithUTF8String: tr_sessionGetProxyPassword(fHandle)]];
230   
231    //set proxy port
232    [fProxyPortField setIntValue: [fDefaults integerForKey: @"ProxyPort"]];
233   
234    //set blocklist
235    [self updateBlocklistFields];
236    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateBlocklistFields)
237        name: @"BlocklistUpdated" object: nil];
238   
239    //set rpc port
240    [fRPCPortField setIntValue: [fDefaults integerForKey: @"RPCPort"]];
241   
242    //set rpc password - has to be released
243    char * rpcPassword = tr_sessionGetRPCPassword(fHandle);
244    [fRPCPasswordField setStringValue: [NSString stringWithUTF8String: rpcPassword]];
245    tr_free(rpcPassword);
246}
247
248- (NSToolbarItem *) toolbar: (NSToolbar *) toolbar itemForItemIdentifier: (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
249{
250    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
251
252    if ([ident isEqualToString: TOOLBAR_GENERAL])
253    {
254        [item setLabel: NSLocalizedString(@"General", "Preferences -> toolbar item title")];
255        [item setImage: [NSImage imageNamed: [NSApp isOnLeopardOrBetter] ? NSImageNamePreferencesGeneral : @"Preferences.png"]];
256        [item setTarget: self];
257        [item setAction: @selector(setPrefView:)];
258        [item setAutovalidates: NO];
259    }
260    else if ([ident isEqualToString: TOOLBAR_TRANSFERS])
261    {
262        [item setLabel: NSLocalizedString(@"Transfers", "Preferences -> toolbar item title")];
263        [item setImage: [NSImage imageNamed: @"Transfers.png"]];
264        [item setTarget: self];
265        [item setAction: @selector(setPrefView:)];
266        [item setAutovalidates: NO];
267    }
268    else if ([ident isEqualToString: TOOLBAR_GROUPS])
269    {
270        [item setLabel: NSLocalizedString(@"Groups", "Preferences -> toolbar item title")];
271        [item setImage: [NSImage imageNamed: @"Groups.png"]];
272        [item setTarget: self];
273        [item setAction: @selector(setPrefView:)];
274        [item setAutovalidates: NO];
275    }
276    else if ([ident isEqualToString: TOOLBAR_BANDWIDTH])
277    {
278        [item setLabel: NSLocalizedString(@"Bandwidth", "Preferences -> toolbar item title")];
279        [item setImage: [NSImage imageNamed: @"Bandwidth.png"]];
280        [item setTarget: self];
281        [item setAction: @selector(setPrefView:)];
282        [item setAutovalidates: NO];
283    }
284    else if ([ident isEqualToString: TOOLBAR_PEERS])
285    {
286        [item setLabel: NSLocalizedString(@"Peers", "Preferences -> toolbar item title")];
287        [item setImage: [NSImage imageNamed: [NSApp isOnLeopardOrBetter] ? NSImageNameUserGroup : @"Peers.png"]];
288        [item setTarget: self];
289        [item setAction: @selector(setPrefView:)];
290        [item setAutovalidates: NO];
291    }
292    else if ([ident isEqualToString: TOOLBAR_NETWORK])
293    {
294        [item setLabel: NSLocalizedString(@"Network", "Preferences -> toolbar item title")];
295        [item setImage: [NSImage imageNamed: [NSApp isOnLeopardOrBetter] ? NSImageNameNetwork : @"Network.png"]];
296        [item setTarget: self];
297        [item setAction: @selector(setPrefView:)];
298        [item setAutovalidates: NO];
299    }
300    else if ([ident isEqualToString: TOOLBAR_REMOTE])
301    {
302        [item setLabel: NSLocalizedString(@"Remote", "Preferences -> toolbar item title")];
303        [item setImage: [NSImage imageNamed: @"Remote.png"]];
304        [item setTarget: self];
305        [item setAction: @selector(setPrefView:)];
306        [item setAutovalidates: NO];
307    }
308    else
309    {
310        [item release];
311        return nil;
312    }
313
314    return [item autorelease];
315}
316
317- (NSArray *) toolbarSelectableItemIdentifiers: (NSToolbar *) toolbar
318{
319    return [self toolbarDefaultItemIdentifiers: toolbar];
320}
321
322- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
323{
324    return [self toolbarAllowedItemIdentifiers: toolbar];
325}
326
327- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
328{
329    return [NSArray arrayWithObjects: TOOLBAR_GENERAL, TOOLBAR_TRANSFERS, TOOLBAR_GROUPS, TOOLBAR_BANDWIDTH,
330                                        TOOLBAR_PEERS, TOOLBAR_NETWORK, TOOLBAR_REMOTE, nil];
331}
332
333- (void) setPort: (id) sender
334{
335    int port = [sender intValue];
336    [fDefaults setInteger: port forKey: @"BindPort"];
337    tr_sessionSetPeerPort(fHandle, port);
338   
339    fPeerPort = -1;
340    [self updatePortStatus];
341}
342
343- (void) setNat: (id) sender
344{
345    tr_sessionSetPortForwardingEnabled(fHandle, [fDefaults boolForKey: @"NatTraversal"]);
346   
347    fNatStatus = -1;
348    [self updatePortStatus];
349}
350
351- (void) updatePortStatus
352{
353    const tr_port_forwarding fwd = tr_sessionGetPortForwarding(fHandle);
354    const int port = tr_sessionGetPeerPort(fHandle);
355    BOOL natStatusChanged = (fNatStatus != fwd);
356    BOOL peerPortChanged = (fPeerPort != port);
357
358    if (natStatusChanged || peerPortChanged)
359    {
360        fNatStatus = fwd;
361        fPeerPort = port;
362       
363        [fPortStatusField setStringValue: @""];
364        [fPortStatusImage setImage: nil];
365        [fPortStatusProgress startAnimation: self];
366       
367        if (fPortChecker)
368        {
369            [fPortChecker cancelProbe];
370            [fPortChecker release];
371        }
372        BOOL delay = natStatusChanged || tr_sessionIsPortForwardingEnabled(fHandle);
373        fPortChecker = [[PortChecker alloc] initForPort: fPeerPort delay: delay withDelegate: self];
374    }
375}
376
377- (void) portCheckerDidFinishProbing: (PortChecker *) portChecker
378{
379    [fPortStatusProgress stopAnimation: self];
380    switch ([fPortChecker status])
381    {
382        case PORT_STATUS_OPEN:
383            [fPortStatusField setStringValue: NSLocalizedString(@"Port is open", "Preferences -> Network -> port status")];
384            [fPortStatusImage setImage: [NSImage imageNamed: @"GreenDot.png"]];
385            break;
386        case PORT_STATUS_CLOSED:
387            [fPortStatusField setStringValue: NSLocalizedString(@"Port is closed", "Preferences -> Network -> port status")];
388            [fPortStatusImage setImage: [NSImage imageNamed: @"RedDot.png"]];
389            break;
390        case PORT_STATUS_ERROR:
391            [fPortStatusField setStringValue: NSLocalizedString(@"Port check site is down", "Preferences -> Network -> port status")];
392            [fPortStatusImage setImage: [NSImage imageNamed: @"YellowDot.png"]];
393            break;
394    }
395    [fPortChecker release];
396    fPortChecker = nil;
397}
398
399- (NSArray *) sounds
400{
401    NSMutableArray * sounds = [NSMutableArray array];
402   
403    NSMutableArray * directories = [NSMutableArray arrayWithObjects: @"/System/Library/Sounds", @"/Library/Sounds", nil];
404    if ([NSApp isOnLeopardOrBetter])
405        [directories addObject: [NSHomeDirectory() stringByAppendingPathComponent: @"Library/Sounds"]];
406   
407    BOOL isDirectory;
408    NSString * directory;
409    NSEnumerator * enumerator = [directories objectEnumerator];
410    while ((directory = [enumerator nextObject]))
411        if ([[NSFileManager defaultManager] fileExistsAtPath: directory isDirectory: &isDirectory] && isDirectory)
412        {
413            NSString * sound;
414            NSEnumerator * soundEnumerator = [[[NSFileManager defaultManager] directoryContentsAtPath: directory] objectEnumerator];
415            while ((sound = [soundEnumerator nextObject]))
416            {
417                sound = [sound stringByDeletingPathExtension];
418                if ([NSSound soundNamed: sound])
419                    [sounds addObject: sound];
420            }
421        }
422   
423    return sounds;
424}
425
426- (void) setSound: (id) sender
427{
428    //play sound when selecting
429    NSSound * sound;
430    if ((sound = [NSSound soundNamed: [sender titleOfSelectedItem]]))
431        [sound play];
432}
433
434- (void) setPeersGlobal: (id) sender
435{
436    int count = [sender intValue];
437    [fDefaults setInteger: count forKey: @"PeersTotal"];
438    tr_sessionSetPeerLimit(fHandle, count);
439}
440
441- (void) setPeersTorrent: (id) sender
442{
443    int count = [sender intValue];
444    [fDefaults setInteger: count forKey: @"PeersTorrent"];
445}
446
447- (void) setPEX: (id) sender
448{
449    tr_sessionSetPexEnabled(fHandle, [fDefaults boolForKey: @"PEXGlobal"]);
450}
451
452- (void) setEncryptionMode: (id) sender
453{
454    tr_sessionSetEncryption(fHandle, [fDefaults boolForKey: @"EncryptionPrefer"] ?
455        ([fDefaults boolForKey: @"EncryptionRequire"] ? TR_ENCRYPTION_REQUIRED : TR_ENCRYPTION_PREFERRED) : TR_CLEAR_PREFERRED);
456}
457
458- (void) setBlocklistEnabled: (id) sender
459{
460    BOOL enable = [sender state] == NSOnState;
461    [fDefaults setBool: enable forKey: @"Blocklist"];
462    tr_blocklistSetEnabled(fHandle, enable);
463   
464    [[BlocklistScheduler scheduler] updateSchedule];
465}
466
467- (void) updateBlocklist: (id) sender
468{
469    [BlocklistDownloaderViewController downloadWithPrefsController: self];
470}
471
472- (void) setBlocklistAutoUpdate: (id) sender
473{
474    [[BlocklistScheduler scheduler] updateSchedule];
475}
476
477- (void) updateBlocklistFields
478{
479    BOOL exists = tr_blocklistExists(fHandle);
480   
481    if (exists)
482    {
483        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
484        [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
485        [numberFormatter setMaximumFractionDigits: 0];
486        NSString * countString = [numberFormatter stringFromNumber: [NSNumber numberWithInt: tr_blocklistGetRuleCount(fHandle)]];
487        [numberFormatter release];
488       
489        [fBlocklistMessageField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ IP address rules in list",
490            "Prefs -> blocklist -> message"), countString]];
491    }
492    else
493        [fBlocklistMessageField setStringValue: NSLocalizedString(@"A blocklist must first be downloaded",
494            "Prefs -> blocklist -> message")];
495   
496    [fBlocklistEnableCheck setEnabled: exists];
497    [fBlocklistEnableCheck setState: exists && [fDefaults boolForKey: @"Blocklist"]];
498   
499    NSString * updatedDateString;
500    if (exists)
501    {
502        NSDate * updatedDate = [fDefaults objectForKey: @"BlocklistLastUpdate"];
503        if (updatedDate)
504        {
505            NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
506            [dateFormatter setDateStyle: NSDateFormatterFullStyle];
507            [dateFormatter setTimeStyle: NSDateFormatterShortStyle];
508           
509            updatedDateString = [dateFormatter stringFromDate: updatedDate];
510            [dateFormatter release];
511        }
512        else
513            updatedDateString = NSLocalizedString(@"N/A", "Prefs -> blocklist -> message");
514    }
515    else
516        updatedDateString = NSLocalizedString(@"Never", "Prefs -> blocklist -> message");
517   
518    [fBlocklistDateField setStringValue: [NSString stringWithFormat: @"%@: %@",
519        NSLocalizedString(@"Last updated", "Prefs -> blocklist -> message"), updatedDateString]];
520}
521
522- (void) applySpeedSettings: (id) sender
523{
524    if ([fDefaults boolForKey: @"SpeedLimit"])
525    {
526        tr_sessionSetSpeedLimitEnabled(fHandle, TR_UP, 1);
527        tr_sessionSetSpeedLimit(fHandle, TR_UP, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]);
528       
529        tr_sessionSetSpeedLimitEnabled(fHandle, TR_DOWN, 1);
530        tr_sessionSetSpeedLimit(fHandle, TR_DOWN, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]);
531    }
532    else
533    {
534        tr_sessionSetSpeedLimitEnabled(fHandle, TR_UP, [fDefaults boolForKey: @"CheckUpload"]);
535        tr_sessionSetSpeedLimit(fHandle, TR_UP, [fDefaults integerForKey: @"UploadLimit"]);
536       
537        tr_sessionSetSpeedLimitEnabled(fHandle, TR_DOWN, [fDefaults boolForKey: @"CheckDownload"]);
538        tr_sessionSetSpeedLimit(fHandle, TR_DOWN, [fDefaults integerForKey: @"DownloadLimit"]);
539    }
540   
541    [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil];
542}
543
544- (void) applyRatioSetting: (id) sender
545{
546    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUI" object: nil];
547}
548
549- (void) updateRatioStopField
550{
551    if (!fHasLoaded)
552        return;
553   
554    [fRatioStopField setFloatValue: [fDefaults floatForKey: @"RatioLimit"]];
555   
556    [self applyRatioSetting: nil];
557}
558
559- (void) setRatioStop: (id) sender
560{
561    [fDefaults setFloat: [sender floatValue] forKey: @"RatioLimit"];
562    [self applyRatioSetting: nil];
563}
564
565- (void) updateLimitFields
566{
567    if (!fHasLoaded)
568        return;
569   
570    [fUploadField setIntValue: [fDefaults integerForKey: @"UploadLimit"]];
571    [fDownloadField setIntValue: [fDefaults integerForKey: @"DownloadLimit"]];
572}
573
574- (void) setGlobalLimit: (id) sender
575{
576    [fDefaults setInteger: [sender intValue] forKey: sender == fUploadField ? @"UploadLimit" : @"DownloadLimit"];
577    [self applySpeedSettings: self];
578}
579
580- (void) setSpeedLimit: (id) sender
581{
582    [fDefaults setInteger: [sender intValue] forKey: sender == fSpeedLimitUploadField
583                                                        ? @"SpeedLimitUploadLimit" : @"SpeedLimitDownloadLimit"];
584    [self applySpeedSettings: self];
585}
586
587- (void) setAutoSpeedLimit: (id) sender
588{
589    [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoSpeedLimitChange" object: self];
590}
591
592- (BOOL) control: (NSControl *) control textShouldBeginEditing: (NSText *) fieldEditor
593{
594    [fInitialString release];
595    fInitialString = [[control stringValue] retain];
596   
597    return YES;
598}
599
600- (BOOL) control: (NSControl *) control didFailToFormatString: (NSString *) string errorDescription: (NSString *) error
601{
602    NSBeep();
603    if (fInitialString)
604    {
605        [control setStringValue: fInitialString];
606        [fInitialString release];
607        fInitialString = nil;
608    }
609    return NO;
610}
611
612- (void) setBadge: (id) sender
613{
614    [[NSNotificationCenter defaultCenter] postNotificationName: @"DockBadgeChange" object: self];
615}
616
617- (void) resetWarnings: (id) sender
618{
619    [fDefaults removeObjectForKey: @"WarningDuplicate"];
620    [fDefaults removeObjectForKey: @"WarningRemainingSpace"];
621    [fDefaults removeObjectForKey: @"WarningFolderDataSameName"];
622    [fDefaults removeObjectForKey: @"WarningResetStats"];
623    [fDefaults removeObjectForKey: @"WarningCreatorBlankAddress"];
624    [fDefaults removeObjectForKey: @"WarningRemoveBuiltInTracker"];
625    [fDefaults removeObjectForKey: @"WarningInvalidOpen"];
626    [fDefaults removeObjectForKey: @"WarningCheckContentsForRemove"];
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    //Registering the Web UI to Bonjour
827    if (enable)
828        [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]];
829    else
830        [[BonjourController defaultController] stop];
831}
832
833- (void) linkWebUI: (id) sender
834{
835    NSString * urlString = [NSString stringWithFormat: WEBUI_URL, [fDefaults integerForKey: @"RPCPort"]];
836    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: urlString]];
837}
838
839- (void) setRPCAuthorize: (id) sender
840{
841    tr_sessionSetRPCPasswordEnabled(fHandle, [fDefaults boolForKey: @"RPCAuthorize"]);
842}
843
844- (void) setRPCUsername: (id) sender
845{
846    tr_sessionSetRPCUsername(fHandle, [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
847}
848
849- (void) setRPCPassword: (id) sender
850{
851    const char * password = [[sender stringValue] UTF8String];
852    [self setKeychainPassword: password forService: RPC_KEYCHAIN_SERVICE username: RPC_KEYCHAIN_NAME];
853   
854    tr_sessionSetRPCPassword(fHandle, password);
855}
856
857- (void) updateRPCPassword
858{
859    UInt32 passwordLength;
860    const char * password = nil;
861    SecKeychainFindGenericPassword(NULL, strlen(RPC_KEYCHAIN_SERVICE), RPC_KEYCHAIN_SERVICE,
862        strlen(RPC_KEYCHAIN_NAME), RPC_KEYCHAIN_NAME, &passwordLength, (void **)&password, NULL);
863   
864    if (password != NULL)
865    {
866        char fullPassword[passwordLength+1];
867        strncpy(fullPassword, password, passwordLength);
868        fullPassword[passwordLength] = '\0';
869        SecKeychainItemFreeContent(NULL, (void *)password);
870       
871        tr_sessionSetRPCPassword(fHandle, fullPassword);
872        [fRPCPasswordField setStringValue: [NSString stringWithUTF8String: fullPassword]];
873    }
874}
875
876- (void) setRPCPort: (id) sender
877{
878    int port = [sender intValue];
879    [fDefaults setInteger: port forKey: @"RPCPort"];
880    tr_sessionSetRPCPort(fHandle, port);
881   
882    //Registering the Web UI to Bonjour
883    if ([fDefaults boolForKey:@"RPC"])
884        [[BonjourController defaultController] startWithPort: port];
885}
886
887- (void) setRPCUseWhitelist: (id) sender
888{
889    tr_sessionSetRPCWhitelistEnabled(fHandle, [fDefaults boolForKey: @"RPCUseWhitelist"]);
890}
891
892- (void) updateRPCWhitelist
893{
894    NSString * string = [fRPCWhitelistArray componentsJoinedByString: @","];
895    tr_sessionSetRPCWhitelist(fHandle, [string UTF8String]);
896}
897
898- (void) addRemoveRPCIP: (id) sender
899{
900    //don't allow add/remove when currently adding - it leads to weird results
901    if ([fRPCWhitelistTable editedRow] != -1)
902        return;
903   
904    if ([[sender cell] tagForSegment: [sender selectedSegment]] == RPC_IP_REMOVE_TAG)
905    {
906        [fRPCWhitelistArray removeObjectsAtIndexes: [fRPCWhitelistTable selectedRowIndexes]];
907        [fRPCWhitelistTable deselectAll: self];
908        [fRPCWhitelistTable reloadData];
909       
910        [fDefaults setObject: fRPCWhitelistArray forKey: @"RPCWhitelist"];
911        [self updateRPCWhitelist];
912    }
913    else
914    {
915        [fRPCWhitelistArray addObject: @""];
916        [fRPCWhitelistTable reloadData];
917       
918        int row = [fRPCWhitelistArray count] - 1;
919        [fRPCWhitelistTable selectRow: row byExtendingSelection: NO];
920        [fRPCWhitelistTable editColumn: 0 row: row withEvent: nil select: YES];
921    }
922}
923
924- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
925{
926    return [fRPCWhitelistArray count];
927}
928
929- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row
930{
931    return [fRPCWhitelistArray objectAtIndex: row];
932}
933
934- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn
935    row: (NSInteger) row
936{
937    NSArray * components = [object componentsSeparatedByString: @"."];
938    NSMutableArray * newComponents = [NSMutableArray arrayWithCapacity: 4];
939       
940    //create better-formatted ip string
941    BOOL valid = false;
942    if ([components count] == 4)
943    {
944        valid = true;
945        NSEnumerator * enumerator = [components objectEnumerator];
946        NSString * component;
947        while ((component = [enumerator nextObject]))
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    int 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        NSEnumerator * enumerator = [[toolbar items] objectEnumerator];
1143        NSToolbarItem * item;
1144        while ((item = [enumerator nextObject]))
1145            if ([[item itemIdentifier] isEqualToString: itemIdentifier])
1146            {
1147                [window setTitle: [item label]];
1148                break;
1149            }
1150    }
1151   
1152    //for network view make sure progress indicator hides itself (get around a Tiger bug)
1153    if (![NSApp isOnLeopardOrBetter] && view == fNetworkView && [fPortStatusImage image])
1154        [fPortStatusProgress setDisplayedWhenStopped: NO];
1155}
1156
1157- (void) folderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1158{
1159    if (code == NSOKButton)
1160    {
1161        [fFolderPopUp selectItemAtIndex: DOWNLOAD_FOLDER];
1162        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"DownloadFolder"];
1163        [fDefaults setObject: @"Constant" forKey: @"DownloadChoice"];
1164    }
1165    else
1166    {
1167        //reset if cancelled
1168        [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT];
1169    }
1170}
1171
1172- (void) incompleteFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1173{
1174    if (code == NSOKButton)
1175        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
1176    [fIncompleteFolderPopUp selectItemAtIndex: 0];
1177}
1178
1179- (void) importFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1180{
1181    NSString * path = [fDefaults stringForKey: @"AutoImportDirectory"];
1182    if (code == NSOKButton)
1183    {
1184        UKKQueue * sharedQueue = [UKKQueue sharedFileWatcher];
1185        if (path)
1186            [sharedQueue removePathFromQueue: [path stringByExpandingTildeInPath]];
1187       
1188        path = [[openPanel filenames] objectAtIndex: 0];
1189        [fDefaults setObject: path forKey: @"AutoImportDirectory"];
1190        [sharedQueue addPath: [path stringByExpandingTildeInPath]];
1191       
1192        [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoImportSettingChange" object: self];
1193    }
1194    else if (!path)
1195        [fDefaults setBool: NO forKey: @"AutoImport"];
1196   
1197    [fImportFolderPopUp selectItemAtIndex: 0];
1198}
1199
1200- (void) setKeychainPassword: (const char *) password forService: (const char *) service username: (const char *) username
1201{
1202    SecKeychainItemRef item = NULL;
1203    NSUInteger passwordLength = strlen(password);
1204   
1205    OSStatus result = SecKeychainFindGenericPassword(NULL, strlen(service), service, strlen(username), username, NULL, NULL, &item);
1206    if (result == noErr && item)
1207    {
1208        if (passwordLength > 0) //found, so update
1209        {
1210            result = SecKeychainItemModifyAttributesAndData(item, NULL, passwordLength, (const void *)password);
1211            if (result != noErr)
1212                NSLog(@"Problem updating Keychain item: %s", GetMacOSStatusErrorString(result));
1213        }
1214        else //remove the item
1215        {
1216            result = SecKeychainItemDelete(item);
1217            if (result != noErr)
1218                NSLog(@"Problem removing Keychain item: %s", GetMacOSStatusErrorString(result));
1219        }
1220    }
1221    else if (result == errSecItemNotFound) //not found, so add
1222    {
1223        if (passwordLength > 0)
1224        {
1225            result = SecKeychainAddGenericPassword(NULL, strlen(service), service, strlen(username), username,
1226                        passwordLength, (const void *)password, NULL);
1227            if (result != noErr)
1228                NSLog(@"Problem adding Keychain item: %s", GetMacOSStatusErrorString(result));
1229        }
1230    }
1231    else
1232        NSLog(@"Problem accessing Keychain: %s", GetMacOSStatusErrorString(result));
1233}
1234
1235@end
Note: See TracBrowser for help on using the repository browser.