source: trunk/macosx/PrefsController.m @ 8098

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

the Mac build works with the new speed limit libT code - still a bit quirky

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