source: trunk/macosx/PrefsController.m @ 8934

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

whoops

  • Property svn:keywords set to Date Rev Author Id
File size: 45.0 KB
Line 
1/******************************************************************************
2 * $Id: PrefsController.m 8934 2009-08-14 23:50:03Z 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    const 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    const tr_port port = tr_sessionSetPeerPortRandom(fHandle);
351   
352    [fPortField setIntValue: port];
353    [self setPort: fPortField];
354}
355
356- (void) setRandomPortOnStart: (id) sender
357{
358    tr_sessionSetPeerPortRandomOnStart(fHandle, [sender state] == NSOnState);
359}
360
361- (void) setNat: (id) sender
362{
363    tr_sessionSetPortForwardingEnabled(fHandle, [fDefaults boolForKey: @"NatTraversal"]);
364   
365    fNatStatus = -1;
366    [self updatePortStatus];
367}
368
369- (void) updatePortStatus
370{
371    const tr_port_forwarding fwd = tr_sessionGetPortForwarding(fHandle);
372    const int port = tr_sessionGetPeerPort(fHandle);
373    BOOL natStatusChanged = (fNatStatus != fwd);
374    BOOL peerPortChanged = (fPeerPort != port);
375
376    if (natStatusChanged || peerPortChanged)
377    {
378        fNatStatus = fwd;
379        fPeerPort = port;
380       
381        [fPortStatusField setStringValue: @""];
382        [fPortStatusImage setImage: nil];
383        [fPortStatusProgress startAnimation: self];
384       
385        if (fPortChecker)
386        {
387            [fPortChecker cancelProbe];
388            [fPortChecker release];
389        }
390        BOOL delay = natStatusChanged || tr_sessionIsPortForwardingEnabled(fHandle);
391        fPortChecker = [[PortChecker alloc] initForPort: fPeerPort delay: delay withDelegate: self];
392    }
393}
394
395- (void) portCheckerDidFinishProbing: (PortChecker *) portChecker
396{
397    [fPortStatusProgress stopAnimation: self];
398    switch ([fPortChecker status])
399    {
400        case PORT_STATUS_OPEN:
401            [fPortStatusField setStringValue: NSLocalizedString(@"Port is open", "Preferences -> Network -> port status")];
402            [fPortStatusImage setImage: [NSImage imageNamed: @"GreenDot.png"]];
403            break;
404        case PORT_STATUS_CLOSED:
405            [fPortStatusField setStringValue: NSLocalizedString(@"Port is closed", "Preferences -> Network -> port status")];
406            [fPortStatusImage setImage: [NSImage imageNamed: @"RedDot.png"]];
407            break;
408        case PORT_STATUS_ERROR:
409            [fPortStatusField setStringValue: NSLocalizedString(@"Port check site is down", "Preferences -> Network -> port status")];
410            [fPortStatusImage setImage: [NSImage imageNamed: @"YellowDot.png"]];
411            break;
412    }
413    [fPortChecker release];
414    fPortChecker = nil;
415}
416
417- (NSArray *) sounds
418{
419    NSMutableArray * sounds = [NSMutableArray array];
420   
421    NSArray * directories = [NSArray arrayWithObjects: @"/System/Library/Sounds", @"/Library/Sounds", @"Library/Sounds", nil];
422   
423    for (NSString * directory in directories)
424    {
425        BOOL isDirectory;
426        if ([[NSFileManager defaultManager] fileExistsAtPath: directory isDirectory: &isDirectory] && isDirectory)
427        {
428            NSArray * directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: directory];
429            for (NSString * sound in directoryContents)
430            {
431                sound = [sound stringByDeletingPathExtension];
432                if ([NSSound soundNamed: sound])
433                    [sounds addObject: sound];
434            }
435        }
436    }
437   
438    return sounds;
439}
440
441- (void) setSound: (id) sender
442{
443    //play sound when selecting
444    NSSound * sound;
445    if ((sound = [NSSound soundNamed: [sender titleOfSelectedItem]]))
446        [sound play];
447}
448
449- (void) setPeersGlobal: (id) sender
450{
451    const int count = [sender intValue];
452    [fDefaults setInteger: count forKey: @"PeersTotal"];
453    tr_sessionSetPeerLimit(fHandle, count);
454}
455
456- (void) setPeersTorrent: (id) sender
457{
458    const int count = [sender intValue];
459    [fDefaults setInteger: count forKey: @"PeersTorrent"];
460}
461
462- (void) setPEX: (id) sender
463{
464    tr_sessionSetPexEnabled(fHandle, [fDefaults boolForKey: @"PEXGlobal"]);
465}
466
467- (void) setDHT: (id) sender
468{
469    tr_sessionSetDHTEnabled(fHandle, [fDefaults boolForKey: @"DHTGlobal"]);
470}
471
472- (void) setEncryptionMode: (id) sender
473{
474    const tr_encryption_mode mode = [fDefaults boolForKey: @"EncryptionPrefer"] ?
475        ([fDefaults boolForKey: @"EncryptionRequire"] ? TR_ENCRYPTION_REQUIRED : TR_ENCRYPTION_PREFERRED) : TR_CLEAR_PREFERRED;
476    tr_sessionSetEncryption(fHandle, mode);
477}
478
479- (void) setBlocklistEnabled: (id) sender
480{
481    const BOOL enable = [sender state] == NSOnState;
482    [fDefaults setBool: enable forKey: @"Blocklist"];
483    tr_blocklistSetEnabled(fHandle, enable);
484   
485    [[BlocklistScheduler scheduler] updateSchedule];
486}
487
488- (void) updateBlocklist: (id) sender
489{
490    [BlocklistDownloaderViewController downloadWithPrefsController: self];
491}
492
493- (void) setBlocklistAutoUpdate: (id) sender
494{
495    [[BlocklistScheduler scheduler] updateSchedule];
496}
497
498- (void) updateBlocklistFields
499{
500    const BOOL exists = tr_blocklistExists(fHandle);
501   
502    if (exists)
503    {
504        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
505        [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
506        [numberFormatter setMaximumFractionDigits: 0];
507        NSString * countString = [numberFormatter stringFromNumber: [NSNumber numberWithInt: tr_blocklistGetRuleCount(fHandle)]];
508        [numberFormatter release];
509       
510        [fBlocklistMessageField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ IP address rules in list",
511            "Prefs -> blocklist -> message"), countString]];
512    }
513    else
514        [fBlocklistMessageField setStringValue: NSLocalizedString(@"A blocklist must first be downloaded",
515            "Prefs -> blocklist -> message")];
516   
517    [fBlocklistEnableCheck setEnabled: exists];
518    [fBlocklistEnableCheck setState: exists && [fDefaults boolForKey: @"Blocklist"]];
519   
520    NSString * updatedDateString;
521    if (exists)
522    {
523        NSDate * updatedDate = [fDefaults objectForKey: @"BlocklistLastUpdate"];
524        if (updatedDate)
525        {
526            NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
527            [dateFormatter setDateStyle: NSDateFormatterFullStyle];
528            [dateFormatter setTimeStyle: NSDateFormatterShortStyle];
529           
530            updatedDateString = [dateFormatter stringFromDate: updatedDate];
531            [dateFormatter release];
532        }
533        else
534            updatedDateString = NSLocalizedString(@"N/A", "Prefs -> blocklist -> message");
535    }
536    else
537        updatedDateString = NSLocalizedString(@"Never", "Prefs -> blocklist -> message");
538   
539    [fBlocklistDateField setStringValue: [NSString stringWithFormat: @"%@: %@",
540        NSLocalizedString(@"Last updated", "Prefs -> blocklist -> message"), updatedDateString]];
541}
542
543- (void) applySpeedSettings: (id) sender
544{
545    tr_sessionLimitSpeed(fHandle, TR_UP, [fDefaults boolForKey: @"CheckUpload"]);
546    tr_sessionSetSpeedLimit(fHandle, TR_UP, [fDefaults integerForKey: @"UploadLimit"]);
547   
548    tr_sessionLimitSpeed(fHandle, TR_DOWN, [fDefaults boolForKey: @"CheckDownload"]);
549    tr_sessionSetSpeedLimit(fHandle, TR_DOWN, [fDefaults integerForKey: @"DownloadLimit"]);
550   
551    [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil];
552}
553
554- (void) applyAltSpeedSettings
555{
556    tr_sessionSetAltSpeed(fHandle, TR_UP, [fDefaults integerForKey: @"SpeedLimitUploadLimit"]);
557    tr_sessionSetAltSpeed(fHandle, TR_DOWN, [fDefaults integerForKey: @"SpeedLimitDownloadLimit"]);
558       
559    [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil];
560}
561
562- (void) applyRatioSetting: (id) sender
563{
564    //[[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUI" object: nil];
565    tr_sessionSetRatioLimited(fHandle, [fDefaults boolForKey: @"RatioCheck"]);
566    tr_sessionSetRatioLimit(fHandle, [fDefaults floatForKey: @"RatioLimit"]);
567}
568
569- (void) updateRatioStopField
570{
571    if (fHasLoaded)
572        [fRatioStopField setFloatValue: [fDefaults floatForKey: @"RatioLimit"]];
573   
574    [self applyRatioSetting: nil];
575}
576
577- (void) setRatioStop: (id) sender
578{
579    [fDefaults setFloat: [sender floatValue] forKey: @"RatioLimit"];
580   
581    [self applyRatioSetting: nil];
582}
583
584- (void) updateLimitFields
585{
586    if (!fHasLoaded)
587        return;
588   
589    [fUploadField setIntValue: [fDefaults integerForKey: @"UploadLimit"]];
590    [fDownloadField setIntValue: [fDefaults integerForKey: @"DownloadLimit"]];
591}
592
593- (void) setGlobalLimit: (id) sender
594{
595    [fDefaults setInteger: [sender intValue] forKey: sender == fUploadField ? @"UploadLimit" : @"DownloadLimit"];
596    [self applySpeedSettings: self];
597}
598
599- (void) setSpeedLimit: (id) sender
600{
601    [fDefaults setInteger: [sender intValue] forKey: sender == fSpeedLimitUploadField
602                                                        ? @"SpeedLimitUploadLimit" : @"SpeedLimitDownloadLimit"];
603    [self applyAltSpeedSettings];
604}
605
606- (void) setAutoSpeedLimit: (id) sender
607{
608    tr_sessionUseAltSpeedTime(fHandle, [fDefaults boolForKey: @"SpeedLimitAuto"]);
609}
610
611- (void) setAutoSpeedLimitTime: (id) sender
612{
613    tr_sessionSetAltSpeedBegin(fHandle, [PrefsController dateToTimeSum: [fDefaults objectForKey: @"SpeedLimitAutoOnDate"]]);
614    tr_sessionSetAltSpeedEnd(fHandle, [PrefsController dateToTimeSum: [fDefaults objectForKey: @"SpeedLimitAutoOffDate"]]);
615}
616
617- (void) setAutoSpeedLimitDay: (id) sender
618{
619    tr_sessionSetAltSpeedDay(fHandle, [[sender selectedItem] tag]);
620}
621
622+ (NSInteger) dateToTimeSum: (NSDate *) date
623{
624    NSCalendar * calendar = [NSCalendar currentCalendar];
625    NSDateComponents * components = [calendar components: NSHourCalendarUnit | NSMinuteCalendarUnit fromDate: date];
626    return [components hour] * 60 + [components minute];
627}
628
629+ (NSDate *) timeSumToDate: (NSInteger) sum
630{
631    NSDateComponents * comps = [[[NSDateComponents alloc] init] autorelease];
632    [comps setHour: sum / 60];
633    [comps setMinute: sum % 60];
634   
635    return [[NSCalendar currentCalendar] dateFromComponents: comps];
636}
637
638- (BOOL) control: (NSControl *) control textShouldBeginEditing: (NSText *) fieldEditor
639{
640    [fInitialString release];
641    fInitialString = [[control stringValue] retain];
642   
643    return YES;
644}
645
646- (BOOL) control: (NSControl *) control didFailToFormatString: (NSString *) string errorDescription: (NSString *) error
647{
648    NSBeep();
649    if (fInitialString)
650    {
651        [control setStringValue: fInitialString];
652        [fInitialString release];
653        fInitialString = nil;
654    }
655    return NO;
656}
657
658- (void) setBadge: (id) sender
659{
660    [[NSNotificationCenter defaultCenter] postNotificationName: @"DockBadgeChange" object: self];
661}
662
663- (void) resetWarnings: (id) sender
664{
665    [fDefaults removeObjectForKey: @"WarningDuplicate"];
666    [fDefaults removeObjectForKey: @"WarningRemainingSpace"];
667    [fDefaults removeObjectForKey: @"WarningFolderDataSameName"];
668    [fDefaults removeObjectForKey: @"WarningResetStats"];
669    [fDefaults removeObjectForKey: @"WarningCreatorBlankAddress"];
670    [fDefaults removeObjectForKey: @"WarningRemoveBuiltInTracker"];
671    [fDefaults removeObjectForKey: @"WarningInvalidOpen"];
672    [fDefaults removeObjectForKey: @"WarningDonate"];
673}
674
675- (void) setQueue: (id) sender
676{
677    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
678}
679
680- (void) setQueueNumber: (id) sender
681{
682    [fDefaults setInteger: [sender intValue] forKey: sender == fQueueDownloadField ? @"QueueDownloadNumber" : @"QueueSeedNumber"];
683    [self setQueue: nil];
684}
685
686- (void) setStalled: (id) sender
687{
688    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
689}
690
691- (void) setStalledMinutes: (id) sender
692{
693    [fDefaults setInteger: [sender intValue] forKey: @"StalledMinutes"];
694    [self setStalled: nil];
695}
696
697- (void) setDownloadLocation: (id) sender
698{
699    [fDefaults setBool: [fFolderPopUp indexOfSelectedItem] == DOWNLOAD_FOLDER forKey: @"DownloadLocationConstant"];
700}
701
702- (void) folderSheetShow: (id) sender
703{
704    NSOpenPanel * panel = [NSOpenPanel openPanel];
705
706    [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")];
707    [panel setAllowsMultipleSelection: NO];
708    [panel setCanChooseFiles: NO];
709    [panel setCanChooseDirectories: YES];
710    [panel setCanCreateDirectories: YES];
711
712    [panel beginSheetForDirectory: nil file: nil types: nil
713        modalForWindow: [self window] modalDelegate: self didEndSelector:
714        @selector(folderSheetClosed:returnCode:contextInfo:) contextInfo: nil];
715}
716
717- (void) incompleteFolderSheetShow: (id) sender
718{
719    NSOpenPanel * panel = [NSOpenPanel openPanel];
720
721    [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")];
722    [panel setAllowsMultipleSelection: NO];
723    [panel setCanChooseFiles: NO];
724    [panel setCanChooseDirectories: YES];
725    [panel setCanCreateDirectories: YES];
726
727    [panel beginSheetForDirectory: nil file: nil types: nil
728        modalForWindow: [self window] modalDelegate: self didEndSelector:
729        @selector(incompleteFolderSheetClosed:returnCode:contextInfo:) contextInfo: nil];
730}
731
732- (void) setAutoImport: (id) sender
733{
734    NSString * path;
735    if ((path = [fDefaults stringForKey: @"AutoImportDirectory"]))
736    {
737        path = [path stringByExpandingTildeInPath];
738        if ([fDefaults boolForKey: @"AutoImport"])
739            [[UKKQueue sharedFileWatcher] addPath: path];
740        else
741            [[UKKQueue sharedFileWatcher] removePathFromQueue: path];
742       
743        [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoImportSettingChange" object: self];
744    }
745    else
746        [self importFolderSheetShow: nil];
747}
748
749- (void) importFolderSheetShow: (id) sender
750{
751    NSOpenPanel * panel = [NSOpenPanel openPanel];
752
753    [panel setPrompt: NSLocalizedString(@"Select", "Preferences -> Open panel prompt")];
754    [panel setAllowsMultipleSelection: NO];
755    [panel setCanChooseFiles: NO];
756    [panel setCanChooseDirectories: YES];
757    [panel setCanCreateDirectories: YES];
758
759    [panel beginSheetForDirectory: nil file: nil types: nil
760        modalForWindow: [self window] modalDelegate: self didEndSelector:
761        @selector(importFolderSheetClosed:returnCode:contextInfo:) contextInfo: nil];
762}
763
764- (void) setAutoSize: (id) sender
765{
766    [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoSizeSettingChange" object: self];
767}
768
769- (void) setProxyEnabled: (id) sender
770{
771    tr_sessionSetProxyEnabled(fHandle, [fDefaults boolForKey: @"Proxy"]);
772}
773
774- (void) setProxyAddress: (id) sender
775{
776    NSString * address = [sender stringValue];
777    tr_sessionSetProxy(fHandle, [address UTF8String]);
778    [fDefaults setObject: address forKey: @"ProxyAddress"];
779}
780
781- (void) setProxyPort: (id) sender
782{
783    int port = [sender intValue];
784    [fDefaults setInteger: port forKey: @"ProxyPort"];
785    tr_sessionSetProxyPort(fHandle, port);
786}
787
788- (void) setProxyType: (id) sender
789{
790    NSString * type;
791    switch ([sender indexOfSelectedItem])
792    {
793        case PROXY_HTTP:
794            type = @"HTTP";
795            break;
796        case PROXY_SOCKS4:
797            type = @"SOCKS4";
798            break;
799        case PROXY_SOCKS5:
800            type = @"SOCKS5";
801    }
802   
803    [fDefaults setObject: type forKey: @"ProxyType"];
804    [self updateProxyType];
805}
806
807- (void) updateProxyType
808{
809    NSString * typeString = [fDefaults stringForKey: @"ProxyType"];
810    tr_proxy_type type;
811    if ([typeString isEqualToString: @"SOCKS4"])
812        type = TR_PROXY_SOCKS4;
813    else if ([typeString isEqualToString: @"SOCKS5"])
814        type = TR_PROXY_SOCKS5;
815    else
816    {
817        //safety
818        if (![typeString isEqualToString: @"HTTP"])
819        {
820            typeString = @"HTTP";
821            [fDefaults setObject: typeString forKey: @"ProxyType"];
822        }
823        type = TR_PROXY_HTTP;
824    }
825   
826    tr_sessionSetProxyType(fHandle, type);
827}
828
829- (void) setProxyAuthorize: (id) sender
830{
831    BOOL enable = [fDefaults boolForKey: @"ProxyAuthorize"];
832    tr_sessionSetProxyAuthEnabled(fHandle, enable);
833}
834
835- (void) setProxyUsername: (id) sender
836{
837    tr_sessionSetProxyUsername(fHandle, [[fDefaults stringForKey: @"ProxyUsername"] UTF8String]);
838}
839
840- (void) setProxyPassword: (id) sender
841{
842    const char * password = [[sender stringValue] UTF8String];
843    [self setKeychainPassword: password forService: PROXY_KEYCHAIN_SERVICE username: PROXY_KEYCHAIN_NAME];
844   
845    tr_sessionSetProxyPassword(fHandle, password);
846}
847
848- (void) updateProxyPassword
849{
850    UInt32 passwordLength;
851    const char * password = nil;
852    SecKeychainFindGenericPassword(NULL, strlen(PROXY_KEYCHAIN_SERVICE), PROXY_KEYCHAIN_SERVICE,
853        strlen(PROXY_KEYCHAIN_NAME), PROXY_KEYCHAIN_NAME, &passwordLength, (void **)&password, NULL);
854   
855    if (password != NULL)
856    {
857        char fullPassword[passwordLength+1];
858        strncpy(fullPassword, password, passwordLength);
859        fullPassword[passwordLength] = '\0';
860        SecKeychainItemFreeContent(NULL, (void *)password);
861       
862        tr_sessionSetProxyPassword(fHandle, fullPassword);
863        [fProxyPasswordField setStringValue: [NSString stringWithUTF8String: fullPassword]];
864    }
865}
866
867- (void) setRPCEnabled: (id) sender
868{
869    BOOL enable = [fDefaults boolForKey: @"RPC"];
870    tr_sessionSetRPCEnabled(fHandle, enable);
871   
872    [self setRPCWebUIDiscovery: nil];
873}
874
875- (void) linkWebUI: (id) sender
876{
877    NSString * urlString = [NSString stringWithFormat: WEBUI_URL, [fDefaults integerForKey: @"RPCPort"]];
878    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: urlString]];
879}
880
881- (void) setRPCAuthorize: (id) sender
882{
883    tr_sessionSetRPCPasswordEnabled(fHandle, [fDefaults boolForKey: @"RPCAuthorize"]);
884}
885
886- (void) setRPCUsername: (id) sender
887{
888    tr_sessionSetRPCUsername(fHandle, [[fDefaults stringForKey: @"RPCUsername"] UTF8String]);
889}
890
891- (void) setRPCPassword: (id) sender
892{
893    [fRPCPassword release];
894    fRPCPassword = [[sender stringValue] copy];
895   
896    const char * password = [[sender stringValue] UTF8String];
897    [self setKeychainPassword: password forService: RPC_KEYCHAIN_SERVICE username: RPC_KEYCHAIN_NAME];
898   
899    tr_sessionSetRPCPassword(fHandle, password);
900}
901
902- (void) updateRPCPassword
903{
904    UInt32 passwordLength;
905    const char * password = nil;
906    SecKeychainFindGenericPassword(NULL, strlen(RPC_KEYCHAIN_SERVICE), RPC_KEYCHAIN_SERVICE,
907        strlen(RPC_KEYCHAIN_NAME), RPC_KEYCHAIN_NAME, &passwordLength, (void **)&password, NULL);
908   
909    [fRPCPassword release];
910    if (password != NULL)
911    {
912        char fullPassword[passwordLength+1];
913        strncpy(fullPassword, password, passwordLength);
914        fullPassword[passwordLength] = '\0';
915        SecKeychainItemFreeContent(NULL, (void *)password);
916       
917        tr_sessionSetRPCPassword(fHandle, fullPassword);
918       
919        fRPCPassword = [[NSString alloc] initWithUTF8String: fullPassword];
920        [fRPCPasswordField setStringValue: fRPCPassword];
921    }
922    else
923        fRPCPassword = nil;
924}
925
926- (void) setRPCPort: (id) sender
927{
928    int port = [sender intValue];
929    [fDefaults setInteger: port forKey: @"RPCPort"];
930    tr_sessionSetRPCPort(fHandle, port);
931   
932    [self setRPCWebUIDiscovery: nil];
933}
934
935- (void) setRPCUseWhitelist: (id) sender
936{
937    tr_sessionSetRPCWhitelistEnabled(fHandle, [fDefaults boolForKey: @"RPCUseWhitelist"]);
938}
939
940- (void) setRPCWebUIDiscovery: (id) sender
941{
942    if ([fDefaults boolForKey:@"RPC"] && [fDefaults boolForKey: @"RPCWebDiscovery"])
943        [[BonjourController defaultController] startWithPort: [fDefaults integerForKey: @"RPCPort"]];
944    else
945        [[BonjourController defaultController] stop];
946}
947
948- (void) updateRPCWhitelist
949{
950    NSString * string = [fRPCWhitelistArray componentsJoinedByString: @","];
951    tr_sessionSetRPCWhitelist(fHandle, [string UTF8String]);
952}
953
954- (void) addRemoveRPCIP: (id) sender
955{
956    //don't allow add/remove when currently adding - it leads to weird results
957    if ([fRPCWhitelistTable editedRow] != -1)
958        return;
959   
960    if ([[sender cell] tagForSegment: [sender selectedSegment]] == RPC_IP_REMOVE_TAG)
961    {
962        [fRPCWhitelistArray removeObjectsAtIndexes: [fRPCWhitelistTable selectedRowIndexes]];
963        [fRPCWhitelistTable deselectAll: self];
964        [fRPCWhitelistTable reloadData];
965       
966        [fDefaults setObject: fRPCWhitelistArray forKey: @"RPCWhitelist"];
967        [self updateRPCWhitelist];
968    }
969    else
970    {
971        [fRPCWhitelistArray addObject: @""];
972        [fRPCWhitelistTable reloadData];
973       
974        int row = [fRPCWhitelistArray count] - 1;
975        [fRPCWhitelistTable selectRow: row byExtendingSelection: NO];
976        [fRPCWhitelistTable editColumn: 0 row: row withEvent: nil select: YES];
977    }
978}
979
980- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
981{
982    return [fRPCWhitelistArray count];
983}
984
985- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row
986{
987    return [fRPCWhitelistArray objectAtIndex: row];
988}
989
990- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn
991    row: (NSInteger) row
992{
993    NSArray * components = [object componentsSeparatedByString: @"."];
994    NSMutableArray * newComponents = [NSMutableArray arrayWithCapacity: 4];
995       
996    //create better-formatted ip string
997    BOOL valid = false;
998    if ([components count] == 4)
999    {
1000        valid = true;
1001        for (NSString * component in components)
1002        {
1003            if ([component isEqualToString: @"*"])
1004                [newComponents addObject: component];
1005            else
1006            {
1007                int num = [component intValue];
1008                if (num >= 0 && num < 256)
1009                    [newComponents addObject: [[NSNumber numberWithInt: num] stringValue]];
1010                else
1011                {
1012                    valid = false;
1013                    break;
1014                }
1015            }
1016        }
1017    }
1018   
1019    NSString * newIP;
1020    if (valid)
1021    {
1022        newIP = [newComponents componentsJoinedByString: @"."];
1023       
1024        //don't allow the same ip address
1025        if ([fRPCWhitelistArray containsObject: newIP] && ![[fRPCWhitelistArray objectAtIndex: row] isEqualToString: newIP])
1026            valid = false;
1027    }
1028   
1029    if (valid)
1030    {
1031        [fRPCWhitelistArray replaceObjectAtIndex: row withObject: newIP];
1032        [fRPCWhitelistArray sortUsingSelector: @selector(compareNumeric:)];
1033    }
1034    else
1035    {
1036        NSBeep();
1037        if ([[fRPCWhitelistArray objectAtIndex: row] isEqualToString: @""])
1038            [fRPCWhitelistArray removeObjectAtIndex: row];
1039    }
1040       
1041    [fRPCWhitelistTable deselectAll: self];
1042    [fRPCWhitelistTable reloadData];
1043   
1044    [fDefaults setObject: fRPCWhitelistArray forKey: @"RPCWhitelist"];
1045    [self updateRPCWhitelist];
1046}
1047
1048- (void) tableViewSelectionDidChange: (NSNotification *) notification
1049{
1050    [fRPCAddRemoveControl setEnabled: [fRPCWhitelistTable numberOfSelectedRows] > 0 forSegment: RPC_IP_REMOVE_TAG];
1051}
1052
1053- (void) helpForPeers: (id) sender
1054{
1055    [[NSHelpManager sharedHelpManager] openHelpAnchor: @"PeersPrefs"
1056        inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]];
1057}
1058
1059- (void) helpForNetwork: (id) sender
1060{
1061    [[NSHelpManager sharedHelpManager] openHelpAnchor: @"NetworkPrefs"
1062        inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]];
1063}
1064
1065- (void) helpForRemote: (id) sender
1066{
1067    [[NSHelpManager sharedHelpManager] openHelpAnchor: @"RemotePrefs"
1068        inBook: [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleHelpBookName"]];
1069}
1070
1071- (void) rpcUpdatePrefs
1072{
1073    //encryption
1074    const tr_encryption_mode encryptionMode = tr_sessionGetEncryption(fHandle);
1075    [fDefaults setBool: encryptionMode != TR_CLEAR_PREFERRED forKey: @"EncryptionPrefer"];
1076    [fDefaults setBool: encryptionMode == TR_ENCRYPTION_REQUIRED forKey: @"EncryptionRequire"];
1077   
1078    //download directory
1079    NSString * downloadLocation = [[NSString stringWithUTF8String: tr_sessionGetDownloadDir(fHandle)] stringByStandardizingPath];
1080    [fDefaults setObject: downloadLocation forKey: @"DownloadFolder"];
1081   
1082    //peers
1083    const uint16_t peersTotal = tr_sessionGetPeerLimit(fHandle);
1084    [fDefaults setInteger: peersTotal forKey: @"PeersTotal"];
1085   
1086    const uint16_t peersTorrent = tr_sessionGetPeerLimitPerTorrent(fHandle);
1087    [fDefaults setInteger: peersTotal forKey: @"PeersTorrent"];
1088   
1089    //pex
1090    const BOOL pex = tr_sessionIsPexEnabled(fHandle);
1091    [fDefaults setBool: pex forKey: @"PEXGlobal"];
1092   
1093    //dht
1094    const BOOL dht = tr_sessionIsDHTEnabled(fHandle);
1095    [fDefaults setBool: dht forKey: @"DHTGlobal"];
1096   
1097    //port
1098    const tr_port port = tr_sessionGetPeerPort(fHandle);
1099    [fDefaults setInteger: port forKey: @"BindPort"];
1100   
1101    const BOOL nat = tr_sessionIsPortForwardingEnabled(fHandle);
1102    [fDefaults setBool: nat forKey: @"NatTraversal"];
1103   
1104    fPeerPort = -1;
1105    fNatStatus = -1;
1106    [self updatePortStatus];
1107   
1108    const BOOL randomPort = tr_sessionGetPeerPortRandomOnStart(fHandle);
1109    [fDefaults setBool: randomPort forKey: @"RandomPort"];
1110   
1111    //speed limit - down
1112    const BOOL downLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_DOWN);
1113    [fDefaults setBool: downLimitEnabled forKey: @"CheckDownload"];
1114   
1115    const int downLimit = tr_sessionGetSpeedLimit(fHandle, TR_DOWN);
1116    [fDefaults setInteger: downLimit forKey: @"DownloadLimit"];
1117   
1118    //speed limit - up
1119    const BOOL upLimitEnabled = tr_sessionIsSpeedLimited(fHandle, TR_UP);
1120    [fDefaults setBool: upLimitEnabled forKey: @"CheckUpload"];
1121   
1122    const int upLimit = tr_sessionGetSpeedLimit(fHandle, TR_UP);
1123    [fDefaults setInteger: upLimit forKey: @"UploadLimit"];
1124   
1125    //alt speed limit enabled
1126    const BOOL useAltSpeed = tr_sessionUsesAltSpeed(fHandle);
1127    [fDefaults setBool: useAltSpeed forKey: @"SpeedLimit"];
1128   
1129    //alt speed limit - down
1130    const int downLimitAlt = tr_sessionGetAltSpeed(fHandle, TR_DOWN);
1131    [fDefaults setInteger: downLimit forKey: @"SpeedLimitDownloadLimit"];
1132   
1133    //alt speed limit - up
1134    const int upLimitAlt = tr_sessionGetAltSpeed(fHandle, TR_UP);
1135    [fDefaults setInteger: upLimitAlt forKey: @"SpeedLimitDownloadLimit"];
1136   
1137    //alt speed limit schedule
1138    const BOOL useAltSpeedSched = tr_sessionUsesAltSpeedTime(fHandle);
1139    [fDefaults setBool: useAltSpeedSched forKey: @"SpeedLimitAuto"];
1140   
1141    NSDate * limitStartDate = [PrefsController timeSumToDate: tr_sessionGetAltSpeedBegin(fHandle)];
1142    [fDefaults setObject: limitStartDate forKey: @"SpeedLimitAutoOnDate"];
1143   
1144    NSDate * limitEndDate = [PrefsController timeSumToDate: tr_sessionGetAltSpeedEnd(fHandle)];
1145    [fDefaults setObject: limitEndDate forKey: @"SpeedLimitAutoOffDate"];
1146   
1147    const int limitDay = tr_sessionGetAltSpeedDay(fHandle);
1148    [fDefaults setInteger: limitDay forKey: @"SpeedLimitAutoDay"];
1149   
1150    //blocklist
1151    const BOOL blocklist = tr_blocklistIsEnabled(fHandle);
1152    [fDefaults setBool: blocklist forKey: @"Blocklist"];
1153   
1154    //seed ratio
1155    const BOOL ratioLimited = tr_sessionIsRatioLimited(fHandle);
1156    [fDefaults setBool: ratioLimited forKey: @"RatioCheck"];
1157   
1158    const float ratioLimit = tr_sessionGetRatioLimit(fHandle);
1159    [fDefaults setFloat: ratioLimit forKey: @"RatioLimit"];
1160   
1161    //update gui if loaded
1162    if (fHasLoaded)
1163    {
1164        //encryption handled by bindings
1165       
1166        //download directory handled by bindings
1167       
1168        [fPeersGlobalField setIntValue: peersTotal];
1169        [fPeersTorrentField setIntValue: peersTorrent];
1170       
1171        //pex handled by bindings
1172       
1173        //dht handled by bindings
1174       
1175        [fPortField setIntValue: port];
1176        //port forwarding (nat) handled by bindings
1177        //random port handled by bindings
1178       
1179        //limit check handled by bindings
1180        [fDownloadField setIntValue: downLimit];
1181       
1182        //limit check handled by bindings
1183        [fUploadField setIntValue: upLimit];
1184       
1185        [fSpeedLimitDownloadField setIntValue: downLimitAlt];
1186       
1187        [fSpeedLimitUploadField setIntValue: upLimitAlt];
1188       
1189        //speed limit schedule handled by bindings
1190       
1191        //speed limit schedule times and day handled by bindings
1192       
1193        [self updateBlocklistFields];
1194       
1195        //ratio limit enabled handled by bindings
1196        [fRatioStopField setFloatValue: ratioLimit];
1197    }
1198   
1199    [[NSNotificationCenter defaultCenter] postNotificationName: @"SpeedLimitUpdate" object: nil];
1200}
1201
1202@end
1203
1204@implementation PrefsController (Private)
1205
1206- (void) setPrefView: (id) sender
1207{
1208    NSString * identifier;
1209    if (sender)
1210    {
1211        identifier = [sender itemIdentifier];
1212        [[NSUserDefaults standardUserDefaults] setObject: identifier forKey: @"SelectedPrefView"];
1213    }
1214    else
1215        identifier = [[NSUserDefaults standardUserDefaults] stringForKey: @"SelectedPrefView"];
1216   
1217    NSView * view;
1218    if ([identifier isEqualToString: TOOLBAR_TRANSFERS])
1219        view = fTransfersView;
1220    else if ([identifier isEqualToString: TOOLBAR_GROUPS])
1221        view = fGroupsView;
1222    else if ([identifier isEqualToString: TOOLBAR_BANDWIDTH])
1223        view = fBandwidthView;
1224    else if ([identifier isEqualToString: TOOLBAR_PEERS])
1225        view = fPeersView;
1226    else if ([identifier isEqualToString: TOOLBAR_NETWORK])
1227        view = fNetworkView;
1228    else if ([identifier isEqualToString: TOOLBAR_REMOTE])
1229        view = fRemoteView;
1230    else
1231    {
1232        identifier = TOOLBAR_GENERAL; //general view is the default selected
1233        view = fGeneralView;
1234    }
1235   
1236    [[[self window] toolbar] setSelectedItemIdentifier: identifier];
1237   
1238    NSWindow * window = [self window];
1239    if ([window contentView] == view)
1240        return;
1241   
1242    NSRect windowRect = [window frame];
1243    float difference = ([view frame].size.height - [[window contentView] frame].size.height) * [window userSpaceScaleFactor];
1244    windowRect.origin.y -= difference;
1245    windowRect.size.height += difference;
1246   
1247    [view setHidden: YES];
1248    [window setContentView: view];
1249    [window setFrame: windowRect display: YES animate: YES];
1250    [view setHidden: NO];
1251   
1252    //set title label
1253    if (sender)
1254        [window setTitle: [sender label]];
1255    else
1256    {
1257        NSToolbar * toolbar = [window toolbar];
1258        NSString * itemIdentifier = [toolbar selectedItemIdentifier];
1259        for (NSToolbarItem * item in [toolbar items])
1260            if ([[item itemIdentifier] isEqualToString: itemIdentifier])
1261            {
1262                [window setTitle: [item label]];
1263                break;
1264            }
1265    }
1266}
1267
1268- (void) folderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1269{
1270    if (code == NSOKButton)
1271    {
1272        [fFolderPopUp selectItemAtIndex: DOWNLOAD_FOLDER];
1273       
1274        NSString * folder = [[openPanel filenames] objectAtIndex: 0];
1275        [fDefaults setObject: folder forKey: @"DownloadFolder"];
1276        [fDefaults setObject: @"Constant" forKey: @"DownloadChoice"];
1277       
1278        tr_sessionSetDownloadDir(fHandle, [folder UTF8String]);
1279    }
1280    else
1281    {
1282        //reset if cancelled
1283        [fFolderPopUp selectItemAtIndex: [fDefaults boolForKey: @"DownloadLocationConstant"] ? DOWNLOAD_FOLDER : DOWNLOAD_TORRENT];
1284    }
1285}
1286
1287- (void) incompleteFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1288{
1289    if (code == NSOKButton)
1290        [fDefaults setObject: [[openPanel filenames] objectAtIndex: 0] forKey: @"IncompleteDownloadFolder"];
1291    [fIncompleteFolderPopUp selectItemAtIndex: 0];
1292}
1293
1294- (void) importFolderSheetClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) info
1295{
1296    NSString * path = [fDefaults stringForKey: @"AutoImportDirectory"];
1297    if (code == NSOKButton)
1298    {
1299        UKKQueue * sharedQueue = [UKKQueue sharedFileWatcher];
1300        if (path)
1301            [sharedQueue removePathFromQueue: [path stringByExpandingTildeInPath]];
1302       
1303        path = [[openPanel filenames] objectAtIndex: 0];
1304        [fDefaults setObject: path forKey: @"AutoImportDirectory"];
1305        [sharedQueue addPath: [path stringByExpandingTildeInPath]];
1306       
1307        [[NSNotificationCenter defaultCenter] postNotificationName: @"AutoImportSettingChange" object: self];
1308    }
1309    else if (!path)
1310        [fDefaults setBool: NO forKey: @"AutoImport"];
1311   
1312    [fImportFolderPopUp selectItemAtIndex: 0];
1313}
1314
1315- (void) setKeychainPassword: (const char *) password forService: (const char *) service username: (const char *) username
1316{
1317    SecKeychainItemRef item = NULL;
1318    NSUInteger passwordLength = strlen(password);
1319   
1320    OSStatus result = SecKeychainFindGenericPassword(NULL, strlen(service), service, strlen(username), username, NULL, NULL, &item);
1321    if (result == noErr && item)
1322    {
1323        if (passwordLength > 0) //found, so update
1324        {
1325            result = SecKeychainItemModifyAttributesAndData(item, NULL, passwordLength, (const void *)password);
1326            if (result != noErr)
1327                NSLog(@"Problem updating Keychain item: %s", GetMacOSStatusErrorString(result));
1328        }
1329        else //remove the item
1330        {
1331            result = SecKeychainItemDelete(item);
1332            if (result != noErr)
1333                NSLog(@"Problem removing Keychain item: %s", GetMacOSStatusErrorString(result));
1334        }
1335    }
1336    else if (result == errSecItemNotFound) //not found, so add
1337    {
1338        if (passwordLength > 0)
1339        {
1340            result = SecKeychainAddGenericPassword(NULL, strlen(service), service, strlen(username), username,
1341                        passwordLength, (const void *)password, NULL);
1342            if (result != noErr)
1343                NSLog(@"Problem adding Keychain item: %s", GetMacOSStatusErrorString(result));
1344        }
1345    }
1346    else
1347        NSLog(@"Problem accessing Keychain: %s", GetMacOSStatusErrorString(result));
1348}
1349
1350@end
Note: See TracBrowser for help on using the repository browser.