source: trunk/macosx/PrefsController.m @ 8058

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

get the rpc password without using tr_sessionGetRPCPassword, in preparation for #1276

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