source: trunk/macosx/PrefsController.m @ 11417

Last change on this file since 11417 was 11417, checked in by livings124, 11 years ago

add a string function to format an NSUInteger as a formatted string

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