source: trunk/macosx/PrefsController.m @ 10119

Last change on this file since 10119 was 10119, checked in by livings124, 12 years ago

#2844 Add option to disable ".part" suffix for incomplete files (Mac)

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