File: ConfigReader.py

package info (click to toggle)
bittornado 0.3.18-10.3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 3,624 kB
  • ctags: 3,675
  • sloc: python: 16,627; sh: 4,400; makefile: 54
file content (1190 lines) | stat: -rw-r--r-- 56,075 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
#written by John Hoffman

from ConnChoice import *
import wx
from types import IntType, FloatType, StringType
from download_bt1 import defaults
from ConfigDir import ConfigDir
import sys,os
import socket
from parseargs import defaultargs
from BTcrypto import CRYPTO_OK

try:
    True
except:
    True = 1
    False = 0
    
if (sys.platform == 'win32'):
    _FONT = 9
else:
    _FONT = 10

def HexToColor(s):
    r,g,b = s.split(' ')
    return wx.Colour(red=int(r,16), green=int(g,16), blue=int(b,16))
    
def hex2(c):
    h = hex(c)[2:]
    if len(h) == 1:
        h = '0'+h
    return h
def ColorToHex(c):
    return hex2(c.Red()) + ' ' + hex2(c.Green()) + ' ' + hex2(c.Blue())

ratesettingslist = []
for x in connChoices:
    if not x.has_key('super-seed'):
        ratesettingslist.append(x['name'])


configFileDefaults = [
    #args only available for the gui client
    ('win32_taskbar_icon', 1,
         "whether to iconize do system try or not on win32"),
    ('gui_stretchwindow', 0,
         "whether to stretch the download status window to fit the torrent name"),
    ('gui_displaystats', 1,
         "whether to display statistics on peers and seeds"),
    ('gui_displaymiscstats', 1,
         "whether to display miscellaneous other statistics"),
    ('gui_ratesettingsdefault', ratesettingslist[0],
         "the default setting for maximum upload rate and users"),
    ('gui_ratesettingsmode', 'full',
         "what rate setting controls to display; options are 'none', 'basic', and 'full'"),
    ('gui_forcegreenonfirewall', 0,
         "forces the status icon to be green even if the client seems to be firewalled"),
    ('gui_default_savedir', '',
         "default save directory"),
    ('last_saved', '',       # hidden; not set in config
         "where the last torrent was saved"),
    ('gui_font', _FONT,
         "the font size to use"),
    ('gui_saveas_ask', -1,
         "whether to ask where to download to (0 = never, 1 = always, -1 = automatic resume"),
]

def setwxconfigfiledefaults():
    CHECKINGCOLOR = ColorToHex(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DSHADOW))
    DOWNLOADCOLOR = ColorToHex(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION))
    
    configFileDefaults.extend([
        ('gui_checkingcolor', CHECKINGCOLOR,
            "progress bar checking color"),
        ('gui_downloadcolor', DOWNLOADCOLOR,
            "progress bar downloading color"),
        ('gui_seedingcolor', '00 FF 00',
            "progress bar seeding color"),
    ])

defaultsToIgnore = ['responsefile', 'url', 'priority']


class configReader:

    def __init__(self):
        self.configfile = wx.Config("BitTorrent",style=wx.CONFIG_USE_LOCAL_FILE)
        self.configMenuBox = None
        self.advancedMenuBox = None
        self.cryptoMenuBox = None
        self._configReset = True         # run reset for the first time

        setwxconfigfiledefaults()

        defaults.extend(configFileDefaults)
        self.defaults = defaultargs(defaults)

        self.configDir = ConfigDir('gui')
        self.configDir.setDefaults(defaults,defaultsToIgnore)
        if self.configDir.checkConfig():
            self.config = self.configDir.loadConfig()
        else:
            self.config = self.configDir.getConfig()
            self.importOldGUIConfig()
            self.configDir.saveConfig()

        updated = False     # make all config default changes here

        if self.config['gui_ratesettingsdefault'] not in ratesettingslist:
            self.config['gui_ratesettingsdefault'] = (
                                self.defaults['gui_ratesettingsdefault'] )
            updated = True
        if self.config['ipv6_enabled'] and (
                        sys.version_info < (2,3) or not socket.has_ipv6 ):
            self.config['ipv6_enabled'] = 0
            updated = True
        for c in ['gui_checkingcolor','gui_downloadcolor','gui_seedingcolor']:
            try:
                HexToColor(self.config[c])
            except:
                self.config[c] = self.defaults[c]
                updated = True

        if updated:
            self.configDir.saveConfig()

        self.configDir.deleteOldCacheData(self.config['expire_cache_data'])


    def importOldGUIConfig(self):
        oldconfig = wx.Config("BitTorrent",style=wx.CONFIG_USE_LOCAL_FILE)
        cont, s, i = oldconfig.GetFirstEntry()
        if not cont:
            oldconfig.DeleteAll()
            return False
        while cont:     # import old config data
            if self.config.has_key(s):
                t = oldconfig.GetEntryType(s)
                try:
                    if t == 1:
                        assert type(self.config[s]) == type('')
                        self.config[s] = oldconfig.Read(s)
                    elif t == 2 or t == 3:
                        assert type(self.config[s]) == type(1)
                        self.config[s] = int(oldconfig.ReadInt(s))
                    elif t == 4:
                        assert type(self.config[s]) == type(1.0)
                        self.config[s] = oldconfig.ReadFloat(s)
                except:
                    pass
            cont, s, i = oldconfig.GetNextEntry(i)

#        oldconfig.DeleteAll()
        return True


    def resetConfigDefaults(self):
        for p,v in self.defaults.items():
            if not p in defaultsToIgnore:
                self.config[p] = v
        self.configDir.saveConfig()

    def writeConfigFile(self):
        self.configDir.saveConfig()

    def WriteLastSaved(self, l):
        self.config['last_saved'] = l
        self.configDir.saveConfig()


    def getcheckingcolor(self):
        return HexToColor(self.config['gui_checkingcolor'])
    def getdownloadcolor(self):
        return HexToColor(self.config['gui_downloadcolor'])
    def getseedingcolor(self):
        return HexToColor(self.config['gui_seedingcolor'])

    def configReset(self):
        r = self._configReset
        self._configReset = False
        return r

    def getConfigDir(self):
        return self.configDir

    def getIconDir(self):
        return self.configDir.getIconDir()

    def getTorrentData(self,t):
        return self.configDir.getTorrentData(t)

    def setColorIcon(self, xxicon, xxiconptr, xxcolor):
        idata = wx.MemoryDC()
        idata.SelectObject(xxicon)
        idata.SetBrush(wx.Brush(xxcolor,wx.SOLID))
        idata.DrawRectangle(0,0,16,16)
        idata.SelectObject(wx.NullBitmap)
        xxiconptr.Refresh()


    def getColorFromUser(self, parent, colInit):
        data = wx.ColourData()
        if colInit.Ok():
            data.SetColour(colInit)
        data.SetCustomColour(0, self.checkingcolor)
        data.SetCustomColour(1, self.downloadcolor)
        data.SetCustomColour(2, self.seedingcolor)
        dlg = wx.ColourDialog(parent,data)
        if not dlg.ShowModal():
            return colInit
        return dlg.GetColourData().GetColour()


    def configMenu(self, parent):
      self.parent = parent
      try:
        self.FONT = self.config['gui_font']
        self.default_font = wx.Font(self.FONT, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)
        self.checkingcolor = HexToColor(self.config['gui_checkingcolor'])
        self.downloadcolor = HexToColor(self.config['gui_downloadcolor'])
        self.seedingcolor = HexToColor(self.config['gui_seedingcolor'])
        
        if (self.configMenuBox is not None):
            try:
                self.configMenuBox.Close()
            except wx.PyDeadObjectError, e:
                self.configMenuBox = None

        self.configMenuBox = wx.Frame(None, -1, 'BitTornado Preferences', size = (1,1),
                            style = wx.DEFAULT_FRAME_STYLE|wx.FULL_REPAINT_ON_RESIZE)
        if (sys.platform == 'win32'):
            self.icon = self.parent.icon
            self.configMenuBox.SetIcon(self.icon)

        panel = wx.Panel(self.configMenuBox, -1)
        self.panel = panel

        def StaticText(text, font = self.FONT, underline = False, color = None, panel = panel):
            x = wx.StaticText(panel, -1, text, style = wx.ALIGN_LEFT)
            x.SetFont(wx.Font(font, wx.DEFAULT, wx.NORMAL, wx.NORMAL, underline))
            if color is not None:
                x.SetForegroundColour(color)
            return x

        colsizer = wx.FlexGridSizer(cols = 1, vgap = 8)

        self.gui_stretchwindow_checkbox = wx.CheckBox(panel, -1, "Stretch window to fit torrent name *")
        self.gui_stretchwindow_checkbox.SetFont(self.default_font)
        self.gui_stretchwindow_checkbox.SetValue(self.config['gui_stretchwindow'])

        self.gui_displaystats_checkbox = wx.CheckBox(panel, -1, "Display peer and seed statistics")
        self.gui_displaystats_checkbox.SetFont(self.default_font)
        self.gui_displaystats_checkbox.SetValue(self.config['gui_displaystats'])

        self.gui_displaymiscstats_checkbox = wx.CheckBox(panel, -1, "Display miscellaneous other statistics")
        self.gui_displaymiscstats_checkbox.SetFont(self.default_font)
        self.gui_displaymiscstats_checkbox.SetValue(self.config['gui_displaymiscstats'])

        self.buffering_checkbox = wx.CheckBox(panel, -1, "Enable read/write buffering *")
        self.buffering_checkbox.SetFont(self.default_font)
        self.buffering_checkbox.SetValue(self.config['buffer_reads'])

        self.breakup_checkbox = wx.CheckBox(panel, -1, "Break-up seed bitfield to foil ISP manipulation")
        self.breakup_checkbox.SetFont(self.default_font)
        self.breakup_checkbox.SetValue(self.config['breakup_seed_bitfield'])

        self.autoflush_checkbox = wx.CheckBox(panel, -1, "Flush data to disk every 5 minutes")
        self.autoflush_checkbox.SetFont(self.default_font)
        self.autoflush_checkbox.SetValue(self.config['auto_flush'])

        if sys.version_info >= (2,3) and socket.has_ipv6:
            self.ipv6enabled_checkbox = wx.CheckBox(panel, -1, "Initiate and receive connections via IPv6 *")
            self.ipv6enabled_checkbox.SetFont(self.default_font)
            self.ipv6enabled_checkbox.SetValue(self.config['ipv6_enabled'])

        self.gui_forcegreenonfirewall_checkbox = wx.CheckBox(panel, -1,
                            "Force icon to display green when firewalled")
        self.gui_forcegreenonfirewall_checkbox.SetFont(self.default_font)
        self.gui_forcegreenonfirewall_checkbox.SetValue(self.config['gui_forcegreenonfirewall'])

        cryptoButton = wx.Button(panel, -1, 'Encryption/Security Settings...')

        self.minport_data = wx.SpinCtrl(panel, -1, '', (-1,-1), (self.FONT*8, -1))
        self.minport_data.SetFont(self.default_font)
        self.minport_data.SetRange(1,65535)
        self.minport_data.SetValue(self.config['minport'])

        self.maxport_data = wx.SpinCtrl(panel, -1, '', (-1,-1), (self.FONT*8, -1))
        self.maxport_data.SetFont(self.default_font)
        self.maxport_data.SetRange(1,65535)
        self.maxport_data.SetValue(self.config['maxport'])
        
        self.randomport_checkbox = wx.CheckBox(panel, -1, "randomize")
        self.randomport_checkbox.SetFont(self.default_font)
        self.randomport_checkbox.SetValue(self.config['random_port'])
        
        self.gui_font_data = wx.SpinCtrl(panel, -1, '', (-1,-1), (self.FONT*5, -1))
        self.gui_font_data.SetFont(self.default_font)
        self.gui_font_data.SetRange(8,16)
        self.gui_font_data.SetValue(self.config['gui_font'])

        self.gui_ratesettingsdefault_data=wx.Choice(panel, -1, choices = ratesettingslist)
        self.gui_ratesettingsdefault_data.SetFont(self.default_font)
        self.gui_ratesettingsdefault_data.SetStringSelection(self.config['gui_ratesettingsdefault'])

        self.maxdownload_data = wx.SpinCtrl(panel, -1, '', (-1,-1), (self.FONT*7, -1))
        self.maxdownload_data.SetFont(self.default_font)
        self.maxdownload_data.SetRange(0,5000)
        self.maxdownload_data.SetValue(self.config['max_download_rate'])

        self.gui_ratesettingsmode_data=wx.RadioBox(panel, -1, 'Rate Settings Mode',
                 choices = [ 'none', 'basic', 'full' ] )
        self.gui_ratesettingsmode_data.SetFont(self.default_font)
        self.gui_ratesettingsmode_data.SetStringSelection(self.config['gui_ratesettingsmode'])

        if (sys.platform == 'win32'):
            self.win32_taskbar_icon_checkbox = wx.CheckBox(panel, -1, "Minimize to system tray")
            self.win32_taskbar_icon_checkbox.SetFont(self.default_font)
            self.win32_taskbar_icon_checkbox.SetValue(self.config['win32_taskbar_icon'])
            
            self.upnp_data=wx.Choice(panel, -1,
                        choices = ['disabled', 'type 1 (fast)', 'type 2 (slow)'])
            self.upnp_data.SetFont(self.default_font)
            self.upnp_data.SetSelection(self.config['upnp_nat_access'])

        self.gui_default_savedir_ctrl = wx.TextCtrl(parent = panel, id = -1,
                            value = self.config['gui_default_savedir'],        
                            size = (26*self.FONT, -1), style = wx.TE_PROCESS_TAB)
        self.gui_default_savedir_ctrl.SetFont(self.default_font)

        self.gui_savemode_data=wx.RadioBox(panel, -1, 'Ask where to save: *',
                 choices = [ 'always', 'never', 'auto-resume' ] )
        self.gui_savemode_data.SetFont(self.default_font)
        self.gui_savemode_data.SetSelection(1-self.config['gui_saveas_ask'])

        self.checkingcolor_icon = wx.EmptyBitmap(16,16)
        self.checkingcolor_iconptr = wx.StaticBitmap(panel, -1, self.checkingcolor_icon)
        self.setColorIcon(self.checkingcolor_icon, self.checkingcolor_iconptr, self.checkingcolor)

        self.downloadcolor_icon = wx.EmptyBitmap(16,16)
        self.downloadcolor_iconptr = wx.StaticBitmap(panel, -1, self.downloadcolor_icon)
        self.setColorIcon(self.downloadcolor_icon, self.downloadcolor_iconptr, self.downloadcolor)

        self.seedingcolor_icon = wx.EmptyBitmap(16,16)
        self.seedingcolor_iconptr = wx.StaticBitmap(panel, -1, self.seedingcolor_icon)
        self.setColorIcon(self.seedingcolor_icon, self.downloadcolor_iconptr, self.seedingcolor)
        
        rowsizer = wx.FlexGridSizer(cols = 2, hgap = 20)

        block12sizer = wx.FlexGridSizer(cols = 1, vgap = 12)

        block1sizer = wx.FlexGridSizer(cols = 1, vgap = 2)
        if (sys.platform == 'win32'):
            block1sizer.Add(self.win32_taskbar_icon_checkbox)
        block1sizer.Add(self.gui_stretchwindow_checkbox)
        block1sizer.Add(self.gui_displaystats_checkbox)
        block1sizer.Add(self.gui_displaymiscstats_checkbox)
        block1sizer.Add(self.buffering_checkbox)
        block1sizer.Add(self.breakup_checkbox)
        block1sizer.Add(self.autoflush_checkbox)
        if sys.version_info >= (2,3) and socket.has_ipv6:
            block1sizer.Add(self.ipv6enabled_checkbox)
        block1sizer.Add(self.gui_forcegreenonfirewall_checkbox)
        block12sizer.Add(block1sizer)
        block12sizer.Add(cryptoButton, 0, wx.ALIGN_CENTER)

        colorsizer = wx.StaticBoxSizer(wx.StaticBox(panel, -1, "Gauge Colors:"), wx.VERTICAL)
        colorsizer1 = wx.FlexGridSizer(cols = 7)
        colorsizer1.Add(StaticText('           Checking: '), 1, wx.ALIGN_BOTTOM)
        colorsizer1.Add(self.checkingcolor_iconptr, 1, wx.ALIGN_BOTTOM)
        colorsizer1.Add(StaticText('   Downloading: '), 1, wx.ALIGN_BOTTOM)
        colorsizer1.Add(self.downloadcolor_iconptr, 1, wx.ALIGN_BOTTOM)
        colorsizer1.Add(StaticText('   Seeding: '), 1, wx.ALIGN_BOTTOM)
        colorsizer1.Add(self.seedingcolor_iconptr, 1, wx.ALIGN_BOTTOM)
        colorsizer1.Add(StaticText('  '))
        minsize = self.checkingcolor_iconptr.GetBestSize()
        minsize.SetHeight(minsize.GetHeight()+5)
        colorsizer1.SetMinSize(minsize)
        colorsizer.Add(colorsizer1)
       
        block12sizer.Add(colorsizer, 1, wx.ALIGN_LEFT)

        rowsizer.Add(block12sizer)

        block3sizer = wx.FlexGridSizer(cols = 1)

        portsettingsSizer = wx.StaticBoxSizer(wx.StaticBox(panel, -1, "Port Range:*"), wx.VERTICAL)
        portsettingsSizer1 = wx.GridSizer(cols = 2, vgap = 1)
        portsettingsSizer1.Add(StaticText('From: '), 1, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
        portsettingsSizer1.Add(self.minport_data, 1, wx.ALIGN_BOTTOM)
        portsettingsSizer1.Add(StaticText('To: '), 1, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
        portsettingsSizer1.Add(self.maxport_data, 1, wx.ALIGN_BOTTOM)
        portsettingsSizer.Add(portsettingsSizer1)
        portsettingsSizer.Add(self.randomport_checkbox, 1, wx.ALIGN_CENTER)
        block3sizer.Add(portsettingsSizer, 1, wx.ALIGN_CENTER)
        block3sizer.Add(StaticText(' '))
        block3sizer.Add(self.gui_ratesettingsmode_data, 1, wx.ALIGN_CENTER)
        block3sizer.Add(StaticText(' '))
        ratesettingsSizer = wx.FlexGridSizer(cols = 1, vgap = 2)
        ratesettingsSizer.Add(StaticText('Default Rate Setting: *'), 1, wx.ALIGN_CENTER)
        ratesettingsSizer.Add(self.gui_ratesettingsdefault_data, 1, wx.ALIGN_CENTER)
        block3sizer.Add(ratesettingsSizer, 1, wx.ALIGN_CENTER)
        if (sys.platform == 'win32'):
            block3sizer.Add(StaticText(' '))
            upnpSizer = wx.FlexGridSizer(cols = 1, vgap = 2)
            upnpSizer.Add(StaticText('UPnP Port Forwarding: *'), 1, wx.ALIGN_CENTER)
            upnpSizer.Add(self.upnp_data, 1, wx.ALIGN_CENTER)
            block3sizer.Add(upnpSizer, 1, wx.ALIGN_CENTER)
        
        rowsizer.Add(block3sizer)
        colsizer.Add(rowsizer)

        block4sizer = wx.FlexGridSizer(cols = 3, hgap = 15)
        savepathsizer = wx.FlexGridSizer(cols = 2, vgap = 1)
        savepathsizer.Add(StaticText('Default Save Path: *'))
        savepathsizer.Add(StaticText(' '))
        savepathsizer.Add(self.gui_default_savedir_ctrl, 1, wx.EXPAND)
        savepathButton = wx.Button(panel, -1, '...', size = (18,18))
#        savepathButton.SetFont(self.default_font)
        savepathsizer.Add(savepathButton, 0, wx.ALIGN_CENTER)
        savepathsizer.Add(self.gui_savemode_data, 0, wx.ALIGN_CENTER)
        block4sizer.Add(savepathsizer, -1, wx.ALIGN_BOTTOM)

        fontsizer = wx.FlexGridSizer(cols = 1, vgap = 2)
        fontsizer.Add(StaticText(''))
        fontsizer.Add(StaticText('Font: *'), 1, wx.ALIGN_CENTER)
        fontsizer.Add(self.gui_font_data, 1, wx.ALIGN_CENTER)
        block4sizer.Add(fontsizer, 1, wx.ALIGN_CENTER_VERTICAL)

        dratesettingsSizer = wx.FlexGridSizer(cols = 1, vgap = 2)
        dratesettingsSizer.Add(StaticText('Default Max'), 1, wx.ALIGN_CENTER)
        dratesettingsSizer.Add(StaticText('Download Rate'), 1, wx.ALIGN_CENTER)
        dratesettingsSizer.Add(StaticText('(kB/s): *'), 1, wx.ALIGN_CENTER)
        dratesettingsSizer.Add(self.maxdownload_data, 1, wx.ALIGN_CENTER)
        dratesettingsSizer.Add(StaticText('(0 = disabled)'), 1, wx.ALIGN_CENTER)
        
        block4sizer.Add(dratesettingsSizer, 1, wx.ALIGN_CENTER_VERTICAL)

        colsizer.Add(block4sizer, 0, wx.ALIGN_CENTER)

        savesizer = wx.GridSizer(cols = 4, hgap = 10)
        saveButton = wx.Button(panel, -1, 'Save')
#        saveButton.SetFont(self.default_font)
        savesizer.Add(saveButton, 0, wx.ALIGN_CENTER)

        cancelButton = wx.Button(panel, -1, 'Cancel')
#        cancelButton.SetFont(self.default_font)
        savesizer.Add(cancelButton, 0, wx.ALIGN_CENTER)

        defaultsButton = wx.Button(panel, -1, 'Revert to Defaults')
#        defaultsButton.SetFont(self.default_font)
        savesizer.Add(defaultsButton, 0, wx.ALIGN_CENTER)

        advancedButton = wx.Button(panel, -1, 'Advanced...')
#        advancedButton.SetFont(self.default_font)
        savesizer.Add(advancedButton, 0, wx.ALIGN_CENTER)
        colsizer.Add(savesizer, 1, wx.ALIGN_CENTER)

        resizewarningtext=StaticText('* These settings will not take effect until the next time you start BitTorrent', self.FONT-2)
        colsizer.Add(resizewarningtext, 1, wx.ALIGN_CENTER)

        border = wx.BoxSizer(wx.HORIZONTAL)
        border.Add(colsizer, 1, wx.EXPAND | wx.ALL, 4)
        
        panel.SetSizer(border)
        panel.SetAutoLayout(True)

        self.advancedConfig = {}
        self.cryptoConfig = {}

        def setDefaults(evt, self = self):
          try:
            self.minport_data.SetValue(self.defaults['minport'])
            self.maxport_data.SetValue(self.defaults['maxport'])
            self.randomport_checkbox.SetValue(self.defaults['random_port'])
            self.gui_stretchwindow_checkbox.SetValue(self.defaults['gui_stretchwindow'])
            self.gui_displaystats_checkbox.SetValue(self.defaults['gui_displaystats'])
            self.gui_displaymiscstats_checkbox.SetValue(self.defaults['gui_displaymiscstats'])
            self.buffering_checkbox.SetValue(self.defaults['buffer_reads'])
            self.breakup_checkbox.SetValue(self.defaults['breakup_seed_bitfield'])
            self.autoflush_checkbox.SetValue(self.defaults['auto_flush'])
            if sys.version_info >= (2,3) and socket.has_ipv6:
                self.ipv6enabled_checkbox.SetValue(self.defaults['ipv6_enabled'])
            self.gui_forcegreenonfirewall_checkbox.SetValue(self.defaults['gui_forcegreenonfirewall'])
            self.gui_font_data.SetValue(self.defaults['gui_font'])
            self.gui_ratesettingsdefault_data.SetStringSelection(self.defaults['gui_ratesettingsdefault'])
            self.maxdownload_data.SetValue(self.defaults['max_download_rate'])
            self.gui_ratesettingsmode_data.SetStringSelection(self.defaults['gui_ratesettingsmode'])
            self.gui_default_savedir_ctrl.SetValue(self.defaults['gui_default_savedir'])
            self.gui_savemode_data.SetSelection(1-self.defaults['gui_saveas_ask'])

            self.checkingcolor = HexToColor(self.defaults['gui_checkingcolor'])
            self.setColorIcon(self.checkingcolor_icon, self.checkingcolor_iconptr, self.checkingcolor)
            self.downloadcolor = HexToColor(self.defaults['gui_downloadcolor'])
            self.setColorIcon(self.downloadcolor_icon, self.downloadcolor_iconptr, self.downloadcolor)
            self.seedingcolor = HexToColor(self.defaults['gui_seedingcolor'])
            self.setColorIcon(self.seedingcolor_icon, self.seedingcolor_iconptr, self.seedingcolor)

            if (sys.platform == 'win32'):
                self.win32_taskbar_icon_checkbox.SetValue(self.defaults['win32_taskbar_icon'])
                self.upnp_data.SetSelection(self.defaults['upnp_nat_access'])

            # reset advanced and crypto windows too
            self.advancedConfig = {}
            for key in ['ip', 'bind', 'min_peers', 'max_initiate', 'display_interval',
        'alloc_type', 'alloc_rate', 'max_files_open', 'max_connections', 'super_seeder',
        'ipv6_binds_v4', 'double_check', 'triple_check', 'lock_files', 'lock_while_reading',
        'expire_cache_data']:
                self.advancedConfig[key] = self.defaults[key]
            self.cryptoConfig = {}
            for key in ['security', 'auto_kick',
        'crypto_allowed', 'crypto_only', 'crypto_stealth']:
                self.cryptoConfig[key] = self.config[key]
            self.CloseAdvanced()
          except:
            self.parent.exception()


        def saveConfigs(evt, self = self):
          try:
            self.config['gui_stretchwindow']=int(self.gui_stretchwindow_checkbox.GetValue())
            self.config['gui_displaystats']=int(self.gui_displaystats_checkbox.GetValue())
            self.config['gui_displaymiscstats']=int(self.gui_displaymiscstats_checkbox.GetValue())
            buffering=int(self.buffering_checkbox.GetValue())
            self.config['buffer_reads']=buffering
            if buffering:
                self.config['write_buffer_size']=self.defaults['write_buffer_size']
            else:
                self.config['write_buffer_size']=0
            self.config['breakup_seed_bitfield']=int(self.breakup_checkbox.GetValue())
            if self.autoflush_checkbox.GetValue():
                self.config['auto_flush']=5
            else:
                self.config['auto_flush']=0
            if sys.version_info >= (2,3) and socket.has_ipv6:
                self.config['ipv6_enabled']=int(self.ipv6enabled_checkbox.GetValue())
            self.config['gui_forcegreenonfirewall']=int(self.gui_forcegreenonfirewall_checkbox.GetValue())
            self.config['minport']=self.minport_data.GetValue()
            self.config['maxport']=self.maxport_data.GetValue()
            self.config['random_port']=int(self.randomport_checkbox.GetValue())
            self.config['gui_font']=self.gui_font_data.GetValue()
            self.config['gui_ratesettingsdefault']=self.gui_ratesettingsdefault_data.GetStringSelection()
            self.config['max_download_rate']=self.maxdownload_data.GetValue()
            self.config['gui_ratesettingsmode']=self.gui_ratesettingsmode_data.GetStringSelection()
            self.config['gui_default_savedir']=self.gui_default_savedir_ctrl.GetValue()
            self.config['gui_saveas_ask']=1-self.gui_savemode_data.GetSelection()
            self.config['gui_checkingcolor']=ColorToHex(self.checkingcolor)
            self.config['gui_downloadcolor']=ColorToHex(self.downloadcolor)
            self.config['gui_seedingcolor']=ColorToHex(self.seedingcolor)
            
            if (sys.platform == 'win32'):
                self.config['win32_taskbar_icon']=int(self.win32_taskbar_icon_checkbox.GetValue())
                self.config['upnp_nat_access']=self.upnp_data.GetSelection()

            if self.advancedConfig:
                for key,val in self.advancedConfig.items():
                    self.config[key] = val
            if self.cryptoConfig:
                for key,val in self.cryptoConfig.items():
                    self.config[key] = val

            self.writeConfigFile()
            self._configReset = True
            self.Close()
          except:
            self.parent.exception()

        def cancelConfigs(evt, self = self):
            self.Close()

        def savepath_set(evt, self = self):
          try:
            d = self.gui_default_savedir_ctrl.GetValue()
            if d == '':
                d = self.config['last_saved']
            dl = wx.DirDialog(self.panel, 'Choose a default directory to save to',
                d, style = wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
            if dl.ShowModal() == wx.ID_OK:
                self.gui_default_savedir_ctrl.SetValue(dl.GetPath())
          except:
            self.parent.exception()

        def checkingcoloricon_set(evt, self = self):
          try:
            newcolor = self.getColorFromUser(self.panel,self.checkingcolor)
            self.setColorIcon(self.checkingcolor_icon, self.checkingcolor_iconptr, newcolor)
            self.checkingcolor = newcolor
          except:
            self.parent.exception()

        def downloadcoloricon_set(evt, self = self):
          try:
            newcolor = self.getColorFromUser(self.panel,self.downloadcolor)
            self.setColorIcon(self.downloadcolor_icon, self.downloadcolor_iconptr, newcolor)
            self.downloadcolor = newcolor
          except:
            self.parent.exception()

        def seedingcoloricon_set(evt, self = self):
          try:
            newcolor = self.getColorFromUser(self.panel,self.seedingcolor)
            self.setColorIcon(self.seedingcolor_icon, self.seedingcolor_iconptr, newcolor)
            self.seedingcolor = newcolor
          except:
            self.parent.exception()
            
        wx.EVT_BUTTON(self.configMenuBox, saveButton.GetId(), saveConfigs)
        wx.EVT_BUTTON(self.configMenuBox, cancelButton.GetId(), cancelConfigs)
        wx.EVT_BUTTON(self.configMenuBox, defaultsButton.GetId(), setDefaults)
        wx.EVT_BUTTON(self.configMenuBox, advancedButton.GetId(), self.advancedMenu)
        wx.EVT_BUTTON(self.configMenuBox, cryptoButton.GetId(), self.cryptoMenu)
        wx.EVT_BUTTON(self.configMenuBox, savepathButton.GetId(), savepath_set)
        wx.EVT_LEFT_DOWN(self.checkingcolor_iconptr, checkingcoloricon_set)
        wx.EVT_LEFT_DOWN(self.downloadcolor_iconptr, downloadcoloricon_set)
        wx.EVT_LEFT_DOWN(self.seedingcolor_iconptr, seedingcoloricon_set)

        self.configMenuBox.Show ()
        border.Fit(panel)
        self.configMenuBox.Fit()
      except:
        self.parent.exception()


    def Close(self):
        self.CloseAdvanced()
        if self.configMenuBox is not None:
            try:
                self.configMenuBox.Close ()
            except wx.PyDeadObjectError, e:
                pass
            self.configMenuBox = None

    def advancedMenu(self, event = None):
      try:
        if not self.advancedConfig:
            for key in ['ip', 'bind', 'min_peers', 'max_initiate', 'display_interval',
        'alloc_type', 'alloc_rate', 'max_files_open', 'max_connections', 'super_seeder',
        'ipv6_binds_v4', 'double_check', 'triple_check', 'lock_files', 'lock_while_reading',
        'expire_cache_data']:
                self.advancedConfig[key] = self.config[key]

        if (self.advancedMenuBox is not None):
            try:
                self.advancedMenuBox.Close ()
            except wx.PyDeadObjectError, e:
                self.advancedMenuBox = None

        self.advancedMenuBox = wx.Frame(None, -1, 'BitTornado Advanced Preferences', size = (1,1),
                            style = wx.DEFAULT_FRAME_STYLE|wx.FULL_REPAINT_ON_RESIZE)
        if (sys.platform == 'win32'):
            self.advancedMenuBox.SetIcon(self.icon)

        panel = wx.Panel(self.advancedMenuBox, -1)

        def StaticText(text, font = self.FONT, underline = False, color = None, panel = panel):
            x = wx.StaticText(panel, -1, text, style = wx.ALIGN_LEFT)
            x.SetFont(wx.Font(font, wx.DEFAULT, wx.NORMAL, wx.NORMAL, underline))
            if color is not None:
                x.SetForegroundColour(color)
            return x

        colsizer = wx.FlexGridSizer(cols = 1, hgap = 13, vgap = 13)
        warningtext = StaticText('CHANGE THESE SETTINGS AT YOUR OWN RISK', self.FONT+4, True, 'Red')
        colsizer.Add(warningtext, 1, wx.ALIGN_CENTER)

        self.ip_data = wx.TextCtrl(parent = panel, id = -1,
                    value = self.advancedConfig['ip'],
                    size = (self.FONT*13, int(self.FONT*2.2)), style = wx.TE_PROCESS_TAB)
        self.ip_data.SetFont(self.default_font)
        
        self.bind_data = wx.TextCtrl(parent = panel, id = -1,
                    value = self.advancedConfig['bind'],
                    size = (self.FONT*13, int(self.FONT*2.2)), style = wx.TE_PROCESS_TAB)
        self.bind_data.SetFont(self.default_font)
        
        if sys.version_info >= (2,3) and socket.has_ipv6:
            self.ipv6bindsv4_data=wx.Choice(panel, -1,
                             choices = ['separate sockets', 'single socket'])
            self.ipv6bindsv4_data.SetFont(self.default_font)
            self.ipv6bindsv4_data.SetSelection(self.advancedConfig['ipv6_binds_v4'])

        self.minpeers_data = wx.SpinCtrl(panel, -1, '', (-1,-1), (self.FONT*7, -1))
        self.minpeers_data.SetFont(self.default_font)
        self.minpeers_data.SetRange(10,100)
        self.minpeers_data.SetValue(self.advancedConfig['min_peers'])
        # max_initiate = 2*minpeers

        self.displayinterval_data = wx.SpinCtrl(panel, -1, '', (-1,-1), (self.FONT*7, -1))
        self.displayinterval_data.SetFont(self.default_font)
        self.displayinterval_data.SetRange(100,2000)
        self.displayinterval_data.SetValue(int(self.advancedConfig['display_interval']*1000))

        self.alloctype_data=wx.Choice(panel, -1,
                         choices = ['normal', 'background', 'pre-allocate', 'sparse'])
        self.alloctype_data.SetFont(self.default_font)
        self.alloctype_data.SetStringSelection(self.advancedConfig['alloc_type'])

        self.allocrate_data = wx.SpinCtrl(panel, -1, '', (-1,-1), (self.FONT*7,-1))
        self.allocrate_data.SetFont(self.default_font)
        self.allocrate_data.SetRange(1,100)
        self.allocrate_data.SetValue(int(self.advancedConfig['alloc_rate']))

        self.locking_data=wx.Choice(panel, -1,
                           choices = ['no locking', 'lock while writing', 'lock always'])
        self.locking_data.SetFont(self.default_font)
        if self.advancedConfig['lock_files']:
            if self.advancedConfig['lock_while_reading']:
                self.locking_data.SetSelection(2)
            else:
                self.locking_data.SetSelection(1)
        else:
            self.locking_data.SetSelection(0)

        self.doublecheck_data=wx.Choice(panel, -1,
                           choices = ['no extra checking', 'double-check', 'triple-check'])
        self.doublecheck_data.SetFont(self.default_font)
        if self.advancedConfig['double_check']:
            if self.advancedConfig['triple_check']:
                self.doublecheck_data.SetSelection(2)
            else:
                self.doublecheck_data.SetSelection(1)
        else:
            self.doublecheck_data.SetSelection(0)

        self.maxfilesopen_choices = ['50', '100', '200', 'no limit ']
        self.maxfilesopen_data=wx.Choice(panel, -1, choices = self.maxfilesopen_choices)
        self.maxfilesopen_data.SetFont(self.default_font)
        setval = self.advancedConfig['max_files_open']
        if setval == 0:
            setval = 'no limit '
        else:
            setval = str(setval)
        if not setval in self.maxfilesopen_choices:
            setval = self.maxfilesopen_choices[0]
        self.maxfilesopen_data.SetStringSelection(setval)

        self.maxconnections_choices = ['no limit ', '20', '30', '40', '50', '60', '100', '200']
        self.maxconnections_data=wx.Choice(panel, -1, choices = self.maxconnections_choices)
        self.maxconnections_data.SetFont(self.default_font)
        setval = self.advancedConfig['max_connections']
        if setval == 0:
            setval = 'no limit '
        else:
            setval = str(setval)
        if not setval in self.maxconnections_choices:
            setval = self.maxconnections_choices[0]
        self.maxconnections_data.SetStringSelection(setval)

        self.superseeder_data=wx.Choice(panel, -1,
                         choices = ['normal', 'super-seed'])
        self.superseeder_data.SetFont(self.default_font)
        self.superseeder_data.SetSelection(self.advancedConfig['super_seeder'])

        self.expirecache_choices = ['never ', '3', '5', '7', '10', '15', '30', '60', '90']
        self.expirecache_data=wx.Choice(panel, -1, choices = self.expirecache_choices)
        setval = self.advancedConfig['expire_cache_data']
        if setval == 0:
            setval = 'never '
        else:
            setval = str(setval)
        if not setval in self.expirecache_choices:
            setval = self.expirecache_choices[0]
        self.expirecache_data.SetFont(self.default_font)
        self.expirecache_data.SetStringSelection(setval)
       

        twocolsizer = wx.FlexGridSizer(cols = 2, hgap = 20)
        datasizer = wx.FlexGridSizer(cols = 2, vgap = 2)
        datasizer.Add(StaticText('Local IP: '), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.ip_data)
        datasizer.Add(StaticText('IP to bind to: '), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.bind_data)
        if sys.version_info >= (2,3) and socket.has_ipv6:
            datasizer.Add(StaticText('IPv6 socket handling: '), 1, wx.ALIGN_CENTER_VERTICAL)
            datasizer.Add(self.ipv6bindsv4_data)
        datasizer.Add(StaticText('Minimum number of peers: '), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.minpeers_data)
        datasizer.Add(StaticText('Display interval (ms): '), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.displayinterval_data)
        datasizer.Add(StaticText('Disk allocation type:'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.alloctype_data)
        datasizer.Add(StaticText('Allocation rate (MiB/s):'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.allocrate_data)
        datasizer.Add(StaticText('File locking:'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.locking_data)
        datasizer.Add(StaticText('Extra data checking:'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.doublecheck_data)
        datasizer.Add(StaticText('Max files open:'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.maxfilesopen_data)
        datasizer.Add(StaticText('Max peer connections:'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.maxconnections_data)
        datasizer.Add(StaticText('Default seeding mode:'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.superseeder_data)
        datasizer.Add(StaticText('Expire resume data(days):'), 1, wx.ALIGN_CENTER_VERTICAL)
        datasizer.Add(self.expirecache_data)
        
        twocolsizer.Add(datasizer)

        infosizer = wx.FlexGridSizer(cols = 1)
        self.hinttext = StaticText('', self.FONT, False, 'Blue')
        infosizer.Add(self.hinttext, 1, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
        infosizer.SetMinSize((180,100))
        twocolsizer.Add(infosizer, 1, wx.EXPAND)

        colsizer.Add(twocolsizer)

        savesizer = wx.GridSizer(cols = 3, hgap = 20)
        okButton = wx.Button(panel, -1, 'OK')
#        okButton.SetFont(self.default_font)
        savesizer.Add(okButton, 0, wx.ALIGN_CENTER)

        cancelButton = wx.Button(panel, -1, 'Cancel')
#        cancelButton.SetFont(self.default_font)
        savesizer.Add(cancelButton, 0, wx.ALIGN_CENTER)

        defaultsButton = wx.Button(panel, -1, 'Revert to Defaults')
#        defaultsButton.SetFont(self.default_font)
        savesizer.Add(defaultsButton, 0, wx.ALIGN_CENTER)
        colsizer.Add(savesizer, 1, wx.ALIGN_CENTER)

        resizewarningtext=StaticText('None of these settings will take effect until the next time you start BitTorrent', self.FONT-2)
        colsizer.Add(resizewarningtext, 1, wx.ALIGN_CENTER)

        border = wx.BoxSizer(wx.HORIZONTAL)
        border.Add(colsizer, 1, wx.EXPAND | wx.ALL, 4)
        
        panel.SetSizer(border)
        panel.SetAutoLayout(True)

        def setDefaults(evt, self = self):
          try:
            self.ip_data.SetValue(self.defaults['ip'])
            self.bind_data.SetValue(self.defaults['bind'])
            if sys.version_info >= (2,3) and socket.has_ipv6:
                self.ipv6bindsv4_data.SetSelection(self.defaults['ipv6_binds_v4'])
            self.minpeers_data.SetValue(self.defaults['min_peers'])
            self.displayinterval_data.SetValue(int(self.defaults['display_interval']*1000))
            self.alloctype_data.SetStringSelection(self.defaults['alloc_type'])
            self.allocrate_data.SetValue(int(self.defaults['alloc_rate']))
            if self.defaults['lock_files']:
                if self.defaults['lock_while_reading']:
                    self.locking_data.SetSelection(2)
                else:
                    self.locking_data.SetSelection(1)
            else:
                self.locking_data.SetSelection(0)
            if self.defaults['double_check']:
                if self.defaults['triple_check']:
                    self.doublecheck_data.SetSelection(2)
                else:
                    self.doublecheck_data.SetSelection(1)
            else:
                self.doublecheck_data.SetSelection(0)
            setval = self.defaults['max_files_open']
            if setval == 0:
                setval = 'no limit '
            else:
                setval = str(setval)
            if not setval in self.maxfilesopen_choices:
                setval = self.maxfilesopen_choices[0]
            self.maxfilesopen_data.SetStringSelection(setval)
            setval = self.defaults['max_connections']
            if setval == 0:
                setval = 'no limit '
            else:
                setval = str(setval)
            if not setval in self.maxconnections_choices:
                setval = self.maxconnections_choices[0]
            self.maxconnections_data.SetStringSelection(setval)
            self.superseeder_data.SetSelection(int(self.defaults['super_seeder']))
            setval = self.defaults['expire_cache_data']
            if setval == 0:
                setval = 'never '
            else:
                setval = str(setval)
            if not setval in self.expirecache_choices:
                setval = self.expirecache_choices[0]
            self.expirecache_data.SetStringSelection(setval)
          except:
            self.parent.exception()

        def saveConfigs(evt, self = self):
          try:
            self.advancedConfig['ip'] = self.ip_data.GetValue()
            self.advancedConfig['bind'] = self.bind_data.GetValue()
            if sys.version_info >= (2,3) and socket.has_ipv6:
                self.advancedConfig['ipv6_binds_v4'] = self.ipv6bindsv4_data.GetSelection()
            self.advancedConfig['min_peers'] = self.minpeers_data.GetValue()
            self.advancedConfig['display_interval'] = float(self.displayinterval_data.GetValue())/1000
            self.advancedConfig['alloc_type'] = self.alloctype_data.GetStringSelection()
            self.advancedConfig['alloc_rate'] = float(self.allocrate_data.GetValue())
            self.advancedConfig['lock_files'] = int(self.locking_data.GetSelection() >= 1)
            self.advancedConfig['lock_while_reading'] = int(self.locking_data.GetSelection() > 1)
            self.advancedConfig['double_check'] = int(self.doublecheck_data.GetSelection() >= 1)
            self.advancedConfig['triple_check'] = int(self.doublecheck_data.GetSelection() > 1)
            try:
                self.advancedConfig['max_files_open'] = int(self.maxfilesopen_data.GetStringSelection())
            except:       # if it ain't a number, it must be "no limit"
                self.advancedConfig['max_files_open'] = 0
            try:
                self.advancedConfig['max_connections'] = int(self.maxconnections_data.GetStringSelection())
                self.advancedConfig['max_initiate'] = min(
                    2*self.advancedConfig['min_peers'], self.advancedConfig['max_connections'])
            except:       # if it ain't a number, it must be "no limit"
                self.advancedConfig['max_connections'] = 0
                self.advancedConfig['max_initiate'] = 2*self.advancedConfig['min_peers']
            self.advancedConfig['super_seeder']=int(self.superseeder_data.GetSelection())
            try:
                self.advancedConfig['expire_cache_data'] = int(self.expirecache_data.GetStringSelection())
            except:
                self.advancedConfig['expire_cache_data'] = 0
            self.advancedMenuBox.Close()
          except:
            self.parent.exception()

        def cancelConfigs(evt, self = self):            
            self.advancedMenuBox.Close()

        def ip_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nThe IP reported to the tracker.\n' +
                                  'unless the tracker is on the\n' +
                                  'same intranet as this client,\n' +
                                  'the tracker will autodetect the\n' +
                                  "client's IP and ignore this\n" +
                                  "value.")

        def bind_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nThe IP the client will bind to.\n' +
                                  'Only useful if your machine is\n' +
                                  'directly handling multiple IPs.\n' +
                                  "If you don't know what this is,\n" +
                                  "leave it blank.")

        def ipv6bindsv4_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nCertain operating systems will\n' +
                                  'open IPv4 protocol connections on\n' +
                                  'an IPv6 socket; others require you\n' +
                                  "to open two sockets on the same\n" +
                                  "port, one IPv4 and one IPv6.")

        def minpeers_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nThe minimum number of peers the\n' +
                                  'client tries to stay connected\n' +
                                  'with.  Do not set this higher\n' +
                                  'unless you have a very fast\n' +
                                  "connection and a lot of system\n" +
                                  "resources.")

        def displayinterval_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nHow often to update the\n' +
                                  'graphical display, in 1/1000s\n' +
                                  'of a second. Setting this too low\n' +
                                  "will strain your computer's\n" +
                                  "processor and video access.")

        def alloctype_hint(evt, self = self):
            self.hinttext.SetLabel('\n\nHow to allocate disk space.\n' +
                                  'normal allocates space as data is\n' +
                                  'received, background also adds\n' +
                                  "space in the background, pre-\n" +
                                  "allocate reserves up front, and\n" +
                                  'sparse is only for filesystems\n' +
                                  'that support it by default.')

        def allocrate_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nAt what rate to allocate disk\n' +
                                  'space when allocating in the\n' +
                                  'background.  Set this too high on a\n' +
                                  "slow filesystem and your download\n" +
                                  "will slow to a crawl.")

        def locking_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\n\nFile locking prevents other\n' +
                                  'programs (including other instances\n' +
                                  'of BitTorrent) from accessing files\n' +
                                  "you are downloading.")

        def doublecheck_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nHow much extra checking to do\n' +
                                  'making sure no data is corrupted.\n' +
                                  'Double-check mode uses more CPU,\n' +
                                  "while triple-check mode increases\n" +
                                  "disk accesses.")

        def maxfilesopen_hint(evt, self = self):
            self.hinttext.SetLabel('\n\n\nThe maximum number of files to\n' +
                                  'keep open at the same time.  Zero\n' +
                                  'means no limit.  Please note that\n' +
                                  "if this option is in effect,\n" +
                                  "files are not guaranteed to be\n" +
                                  "locked.")

        def maxconnections_hint(evt, self = self):
            self.hinttext.SetLabel('\n\nSome operating systems, most\n' +
                                  'notably Windows 9x/ME combined\n' +
                                  'with certain network drivers,\n' +
                                  "cannot handle more than a certain\n" +
                                  "number of open ports.  If the\n" +
                                  "client freezes, try setting this\n" +
                                  "to 60 or below.")

        def superseeder_hint(evt, self = self):
            self.hinttext.SetLabel('\n\nThe "super-seed" method allows\n' +
                                  'a single source to more efficiently\n' +
                                  'seed a large torrent, but is not\n' +
                                  "necessary in a well-seeded torrent,\n" +
                                  "and causes problems with statistics.\n" +
                                  "Unless you routinely seed torrents\n" +
                                  "you can enable this by selecting\n" +
                                  '"SUPER-SEED" for connection type.\n' +
                                  '(once enabled it does not turn off.)')

        def expirecache_hint(evt, self = self):
            self.hinttext.SetLabel('\n\nThe client stores temporary data\n' +
                                  'in order to handle downloading only\n' +
                                  'specific files from the torrent and\n' +
                                  "so it can resume downloads more\n" +
                                  "quickly.  This sets how long the\n" +
                                  "client will keep this data before\n" +
                                  "deleting it to free disk space.")

        wx.EVT_BUTTON(self.advancedMenuBox, okButton.GetId(), saveConfigs)
        wx.EVT_BUTTON(self.advancedMenuBox, cancelButton.GetId(), cancelConfigs)
        wx.EVT_BUTTON(self.advancedMenuBox, defaultsButton.GetId(), setDefaults)
        wx.EVT_ENTER_WINDOW(self.ip_data, ip_hint)
        wx.EVT_ENTER_WINDOW(self.bind_data, bind_hint)
        if sys.version_info >= (2,3) and socket.has_ipv6:
            wx.EVT_ENTER_WINDOW(self.ipv6bindsv4_data, ipv6bindsv4_hint)
        wx.EVT_ENTER_WINDOW(self.minpeers_data, minpeers_hint)
        wx.EVT_ENTER_WINDOW(self.displayinterval_data, displayinterval_hint)
        wx.EVT_ENTER_WINDOW(self.alloctype_data, alloctype_hint)
        wx.EVT_ENTER_WINDOW(self.allocrate_data, allocrate_hint)
        wx.EVT_ENTER_WINDOW(self.locking_data, locking_hint)
        wx.EVT_ENTER_WINDOW(self.doublecheck_data, doublecheck_hint)
        wx.EVT_ENTER_WINDOW(self.maxfilesopen_data, maxfilesopen_hint)
        wx.EVT_ENTER_WINDOW(self.maxconnections_data, maxconnections_hint)
        wx.EVT_ENTER_WINDOW(self.superseeder_data, superseeder_hint)
        wx.EVT_ENTER_WINDOW(self.expirecache_data, expirecache_hint)

        self.advancedMenuBox.Show ()
        border.Fit(panel)
        self.advancedMenuBox.Fit()
      except:
        self.parent.exception()


    def CloseAdvanced(self):
        if self.advancedMenuBox is not None:
            try:
                self.advancedMenuBox.Close()
            except wx.PyDeadObjectError, e:
                self.advancedMenuBox = None


    def cryptoMenu(self, event = None):
      try:
        if not self.cryptoConfig:
            for key in ['security', 'auto_kick',
        'crypto_allowed', 'crypto_only', 'crypto_stealth']:
                self.cryptoConfig[key] = self.config[key]

        if (self.cryptoMenuBox is not None):
            try:
                self.cryptoMenuBox.Close ()
            except wx.PyDeadObjectError, e:
                self.cryptoMenuBox = None

        self.cryptoMenuBox = wx.Frame(None, -1, 'BitTornado Encryption/Security Preferences', size = (1,1),
                            style = wx.DEFAULT_FRAME_STYLE|wx.FULL_REPAINT_ON_RESIZE)
        if (sys.platform == 'win32'):
            self.cryptoMenuBox.SetIcon(self.icon)

        panel = wx.Panel(self.cryptoMenuBox, -1)
#        self.panel = panel

        def StaticText(text, font = self.FONT, underline = False, color = None, panel = panel):
            x = wx.StaticText(panel, -1, text, style = wx.ALIGN_LEFT)
            x.SetFont(wx.Font(font, wx.DEFAULT, wx.NORMAL, wx.NORMAL, underline))
            if color is not None:
                x.SetForegroundColour(color)
            return x

        colsizer = wx.FlexGridSizer(cols = 1, hgap = 13, vgap = 13)

        self.cryptomode_data=wx.RadioBox(panel, -1, 'Encryption',
                style = wx.RA_SPECIFY_COLS, majorDimension = 1,
                choices = [
                    'no encryption permitted',
                    'encryption enabled (default)',
                    'encrypted connections only',
                    'full stealth encryption'+
                    ' (may cause effective firewalling)' ] )
        self.cryptomode_data.SetFont(self.default_font)
        if self.cryptoConfig['crypto_stealth']:
            m = 3
        elif self.cryptoConfig['crypto_only']:
            m = 2
        elif self.cryptoConfig['crypto_allowed']:
            m = 1
        else:
            m = 0
        self.cryptomode_data.SetSelection(m)
        if not CRYPTO_OK:   # no crypto library in place
            self.cryptomode_data.Enable(False)

        self.security_checkbox = wx.CheckBox(panel, -1, "Don't allow multiple connections from the same IP")
        self.security_checkbox.SetFont(self.default_font)
        self.security_checkbox.SetValue(self.cryptoConfig['security'])

        self.autokick_checkbox = wx.CheckBox(panel, -1, "Kick/ban clients that send you bad data")
        self.autokick_checkbox.SetFont(self.default_font)
        self.autokick_checkbox.SetValue(self.cryptoConfig['auto_kick'])

        colsizer.Add(self.cryptomode_data)

        block2sizer = wx.FlexGridSizer(cols = 1, vgap = 2)
        block2sizer.Add(self.security_checkbox)
        block2sizer.Add(self.autokick_checkbox)
        colsizer.Add(block2sizer)

        savesizer = wx.GridSizer(cols = 3, hgap = 20)
        okButton = wx.Button(panel, -1, 'OK')
        savesizer.Add(okButton, 0, wx.ALIGN_CENTER)

        cancelButton = wx.Button(panel, -1, 'Cancel')
        savesizer.Add(cancelButton, 0, wx.ALIGN_CENTER)

        defaultsButton = wx.Button(panel, -1, 'Revert to Defaults')
        savesizer.Add(defaultsButton, 0, wx.ALIGN_CENTER)
        colsizer.Add(savesizer, 1, wx.ALIGN_CENTER)

        resizewarningtext=StaticText('None of these settings will take effect until the next time you start BitTorrent', self.FONT-2)
        colsizer.Add(resizewarningtext, 1, wx.ALIGN_CENTER)

        border = wx.BoxSizer(wx.HORIZONTAL)
        border.Add(colsizer, 1, wx.EXPAND | wx.ALL, 4)
        
        panel.SetSizer(border)
        panel.SetAutoLayout(True)

        def setDefaults(evt, self = self):
          try:
            if self.defaults['crypto_stealth']:
                m = 3
            elif self.defaults['crypto_only']:
                m = 2
            elif self.defaults['crypto_allowed']:
                m = 1
            else:
                m = 0
            self.cryptomode_data.SetSelection(m)
            self.security_checkbox.SetValue(self.defaults['security'])
            self.autokick_checkbox.SetValue(self.defaults['auto_kick'])
          except:
            self.parent.exception()

        def saveConfigs(evt, self = self):
          try:
            m = self.cryptomode_data.GetSelection()
            self.cryptoConfig['crypto_stealth'] = int(m==3)
            self.cryptoConfig['crypto_only'] = int(m>=2)
            self.cryptoConfig['crypto_allowed'] = int(m>=1)
            self.cryptoConfig['security']=int(self.security_checkbox.GetValue())
            self.cryptoConfig['auto_kick']=int(self.autokick_checkbox.GetValue())
            self.cryptoMenuBox.Close()
          except:
            self.parent.exception()

        def cancelConfigs(evt, self = self):            
            self.cryptoMenuBox.Close()

        wx.EVT_BUTTON(self.cryptoMenuBox, okButton.GetId(), saveConfigs)
        wx.EVT_BUTTON(self.cryptoMenuBox, cancelButton.GetId(), cancelConfigs)
        wx.EVT_BUTTON(self.cryptoMenuBox, defaultsButton.GetId(), setDefaults)

        self.cryptoMenuBox.Show ()
        border.Fit(panel)
        self.cryptoMenuBox.Fit()
      except:
        self.parent.exception()


    def CloseCrypt(self):
        if self.cryptMenuBox is not None:
            try:
                self.cryptMenuBox.Close()
            except wx.PyDeadObjectError, e:
                self.cryptMenuBox = None