source: trunk/macosx/PrefsController.m @ 9844

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

happy new year!

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