summaryrefslogtreecommitdiffstats
path: root/Lib/idlelib/idle_test/test_configdialog.py
blob: 1f14ed1f26473004c26c6bf74996c4caf3762a03 (plain)
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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
"""Test configdialog, coverage 94%.

Half the class creates dialog, half works with user customizations.
"""
from idlelib import configdialog
from test.support import requires
requires('gui')
import unittest
from unittest import mock
from idlelib.idle_test.mock_idle import Func
from tkinter import Tk, StringVar, IntVar, BooleanVar, DISABLED, NORMAL
from idlelib import config
from idlelib.configdialog import idleConf, changes, tracers

# Tests should not depend on fortuitous user configurations.
# They must not affect actual user .cfg files.
# Use solution from test_config: empty parsers with no filename.
usercfg = idleConf.userCfg
testcfg = {
    'main': config.IdleUserConfParser(''),
    'highlight': config.IdleUserConfParser(''),
    'keys': config.IdleUserConfParser(''),
    'extensions': config.IdleUserConfParser(''),
}

root = None
dialog = None
mainpage = changes['main']
highpage = changes['highlight']
keyspage = changes['keys']
extpage = changes['extensions']

def setUpModule():
    global root, dialog
    idleConf.userCfg = testcfg
    root = Tk()
    # root.withdraw()    # Comment out, see issue 30870
    dialog = configdialog.ConfigDialog(root, 'Test', _utest=True)

def tearDownModule():
    global root, dialog
    idleConf.userCfg = usercfg
    tracers.detach()
    tracers.clear()
    changes.clear()
    root.update_idletasks()
    root.destroy()
    root = dialog = None


class FontPageTest(unittest.TestCase):
    """Test that font widgets enable users to make font changes.

    Test that widget actions set vars, that var changes add three
    options to changes and call set_samples, and that set_samples
    changes the font of both sample boxes.
    """
    @classmethod
    def setUpClass(cls):
        page = cls.page = dialog.fontpage
        dialog.note.select(page)
        page.set_samples = Func()  # Mask instance method.
        page.update()

    @classmethod
    def tearDownClass(cls):
        del cls.page.set_samples  # Unmask instance method.

    def setUp(self):
        changes.clear()

    def test_load_font_cfg(self):
        # Leave widget load test to human visual check.
        # TODO Improve checks when add IdleConf.get_font_values.
        tracers.detach()
        d = self.page
        d.font_name.set('Fake')
        d.font_size.set('1')
        d.font_bold.set(True)
        d.set_samples.called = 0
        d.load_font_cfg()
        self.assertNotEqual(d.font_name.get(), 'Fake')
        self.assertNotEqual(d.font_size.get(), '1')
        self.assertFalse(d.font_bold.get())
        self.assertEqual(d.set_samples.called, 1)
        tracers.attach()

    def test_fontlist_key(self):
        # Up and Down keys should select a new font.
        d = self.page
        if d.fontlist.size() < 2:
            self.skipTest('need at least 2 fonts')
        fontlist = d.fontlist
        fontlist.activate(0)
        font = d.fontlist.get('active')

        # Test Down key.
        fontlist.focus_force()
        fontlist.update()
        fontlist.event_generate('<Key-Down>')
        fontlist.event_generate('<KeyRelease-Down>')

        down_font = fontlist.get('active')
        self.assertNotEqual(down_font, font)
        self.assertIn(d.font_name.get(), down_font.lower())

        # Test Up key.
        fontlist.focus_force()
        fontlist.update()
        fontlist.event_generate('<Key-Up>')
        fontlist.event_generate('<KeyRelease-Up>')

        up_font = fontlist.get('active')
        self.assertEqual(up_font, font)
        self.assertIn(d.font_name.get(), up_font.lower())

    def test_fontlist_mouse(self):
        # Click on item should select that item.
        d = self.page
        if d.fontlist.size() < 2:
            self.skipTest('need at least 2 fonts')
        fontlist = d.fontlist
        fontlist.activate(0)

        # Select next item in listbox
        fontlist.focus_force()
        fontlist.see(1)
        fontlist.update()
        x, y, dx, dy = fontlist.bbox(1)
        x += dx // 2
        y += dy // 2
        fontlist.event_generate('<Button-1>', x=x, y=y)
        fontlist.event_generate('<ButtonRelease-1>', x=x, y=y)

        font1 = fontlist.get(1)
        select_font = fontlist.get('anchor')
        self.assertEqual(select_font, font1)
        self.assertIn(d.font_name.get(), font1.lower())

    def test_sizelist(self):
        # Click on number should select that number
        d = self.page
        d.sizelist.variable.set(40)
        self.assertEqual(d.font_size.get(), '40')

    def test_bold_toggle(self):
        # Click on checkbutton should invert it.
        d = self.page
        d.font_bold.set(False)
        d.bold_toggle.invoke()
        self.assertTrue(d.font_bold.get())
        d.bold_toggle.invoke()
        self.assertFalse(d.font_bold.get())

    def test_font_set(self):
        # Test that setting a font Variable results in 3 provisional
        # change entries and a call to set_samples. Use values sure to
        # not be defaults.

        default_font = idleConf.GetFont(root, 'main', 'EditorWindow')
        default_size = str(default_font[1])
        default_bold = default_font[2] == 'bold'
        d = self.page
        d.font_size.set(default_size)
        d.font_bold.set(default_bold)
        d.set_samples.called = 0

        d.font_name.set('Test Font')
        expected = {'EditorWindow': {'font': 'Test Font',
                                     'font-size': default_size,
                                     'font-bold': str(default_bold)}}
        self.assertEqual(mainpage, expected)
        self.assertEqual(d.set_samples.called, 1)
        changes.clear()

        d.font_size.set('20')
        expected = {'EditorWindow': {'font': 'Test Font',
                                     'font-size': '20',
                                     'font-bold': str(default_bold)}}
        self.assertEqual(mainpage, expected)
        self.assertEqual(d.set_samples.called, 2)
        changes.clear()

        d.font_bold.set(not default_bold)
        expected = {'EditorWindow': {'font': 'Test Font',
                                     'font-size': '20',
                                     'font-bold': str(not default_bold)}}
        self.assertEqual(mainpage, expected)
        self.assertEqual(d.set_samples.called, 3)

    def test_set_samples(self):
        d = self.page
        del d.set_samples  # Unmask method for test
        orig_samples = d.font_sample, d.highlight_sample
        d.font_sample, d.highlight_sample = {}, {}
        d.font_name.set('test')
        d.font_size.set('5')
        d.font_bold.set(1)
        expected = {'font': ('test', '5', 'bold')}

        # Test set_samples.
        d.set_samples()
        self.assertTrue(d.font_sample == d.highlight_sample == expected)

        d.font_sample, d.highlight_sample = orig_samples
        d.set_samples = Func()  # Re-mask for other tests.


class IndentTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.page = dialog.fontpage
        cls.page.update()

    def test_load_tab_cfg(self):
        d = self.page
        d.space_num.set(16)
        d.load_tab_cfg()
        self.assertEqual(d.space_num.get(), 4)

    def test_indent_scale(self):
        d = self.page
        changes.clear()
        d.indent_scale.set(20)
        self.assertEqual(d.space_num.get(), 16)
        self.assertEqual(mainpage, {'Indent': {'num-spaces': '16'}})


class HighPageTest(unittest.TestCase):
    """Test that highlight tab widgets enable users to make changes.

    Test that widget actions set vars, that var changes add
    options to changes and that themes work correctly.
    """

    @classmethod
    def setUpClass(cls):
        page = cls.page = dialog.highpage
        dialog.note.select(page)
        page.set_theme_type = Func()
        page.paint_theme_sample = Func()
        page.set_highlight_target = Func()
        page.set_color_sample = Func()
        page.update()

    @classmethod
    def tearDownClass(cls):
        d = cls.page
        del d.set_theme_type, d.paint_theme_sample
        del d.set_highlight_target, d.set_color_sample

    def setUp(self):
        d = self.page
        # The following is needed for test_load_key_cfg, _delete_custom_keys.
        # This may indicate a defect in some test or function.
        for section in idleConf.GetSectionList('user', 'highlight'):
            idleConf.userCfg['highlight'].remove_section(section)
        changes.clear()
        d.set_theme_type.called = 0
        d.paint_theme_sample.called = 0
        d.set_highlight_target.called = 0
        d.set_color_sample.called = 0

    def test_load_theme_cfg(self):
        tracers.detach()
        d = self.page
        eq = self.assertEqual

        # Use builtin theme with no user themes created.
        idleConf.CurrentTheme = mock.Mock(return_value='IDLE Classic')
        d.load_theme_cfg()
        self.assertTrue(d.theme_source.get())
        # builtinlist sets variable builtin_name to the CurrentTheme default.
        eq(d.builtin_name.get(), 'IDLE Classic')
        eq(d.custom_name.get(), '- no custom themes -')
        eq(d.custom_theme_on.state(), ('disabled',))
        eq(d.set_theme_type.called, 1)
        eq(d.paint_theme_sample.called, 1)
        eq(d.set_highlight_target.called, 1)

        # Builtin theme with non-empty user theme list.
        idleConf.SetOption('highlight', 'test1', 'option', 'value')
        idleConf.SetOption('highlight', 'test2', 'option2', 'value2')
        d.load_theme_cfg()
        eq(d.builtin_name.get(), 'IDLE Classic')
        eq(d.custom_name.get(), 'test1')
        eq(d.set_theme_type.called, 2)
        eq(d.paint_theme_sample.called, 2)
        eq(d.set_highlight_target.called, 2)

        # Use custom theme.
        idleConf.CurrentTheme = mock.Mock(return_value='test2')
        idleConf.SetOption('main', 'Theme', 'default', '0')
        d.load_theme_cfg()
        self.assertFalse(d.theme_source.get())
        eq(d.builtin_name.get(), 'IDLE Classic')
        eq(d.custom_name.get(), 'test2')
        eq(d.set_theme_type.called, 3)
        eq(d.paint_theme_sample.called, 3)
        eq(d.set_highlight_target.called, 3)

        del idleConf.CurrentTheme
        tracers.attach()

    def test_theme_source(self):
        eq = self.assertEqual
        d = self.page
        # Test these separately.
        d.var_changed_builtin_name = Func()
        d.var_changed_custom_name = Func()
        # Builtin selected.
        d.builtin_theme_on.invoke()
        eq(mainpage, {'Theme': {'default': 'True'}})
        eq(d.var_changed_builtin_name.called, 1)
        eq(d.var_changed_custom_name.called, 0)
        changes.clear()

        # Custom selected.
        d.custom_theme_on.state(('!disabled',))
        d.custom_theme_on.invoke()
        self.assertEqual(mainpage, {'Theme': {'default': 'False'}})
        eq(d.var_changed_builtin_name.called, 1)
        eq(d.var_changed_custom_name.called, 1)
        del d.var_changed_builtin_name, d.var_changed_custom_name

    def test_builtin_name(self):
        eq = self.assertEqual
        d = self.page
        item_list = ['IDLE Classic', 'IDLE Dark', 'IDLE New']

        # Not in old_themes, defaults name to first item.
        idleConf.SetOption('main', 'Theme', 'name', 'spam')
        d.builtinlist.SetMenu(item_list, 'IDLE Dark')
        eq(mainpage, {'Theme': {'name': 'IDLE Classic',
                                'name2': 'IDLE Dark'}})
        eq(d.theme_message['text'], 'New theme, see Help')
        eq(d.paint_theme_sample.called, 1)

        # Not in old themes - uses name2.
        changes.clear()
        idleConf.SetOption('main', 'Theme', 'name', 'IDLE New')
        d.builtinlist.SetMenu(item_list, 'IDLE Dark')
        eq(mainpage, {'Theme': {'name2': 'IDLE Dark'}})
        eq(d.theme_message['text'], 'New theme, see Help')
        eq(d.paint_theme_sample.called, 2)

        # Builtin name in old_themes.
        changes.clear()
        d.builtinlist.SetMenu(item_list, 'IDLE Classic')
        eq(mainpage, {'Theme': {'name': 'IDLE Classic', 'name2': ''}})
        eq(d.theme_message['text'], '')
        eq(d.paint_theme_sample.called, 3)

    def test_custom_name(self):
        d = self.page

        # If no selections, doesn't get added.
        d.customlist.SetMenu([], '- no custom themes -')
        self.assertNotIn('Theme', mainpage)
        self.assertEqual(d.paint_theme_sample.called, 0)

        # Custom name selected.
        changes.clear()
        d.customlist.SetMenu(['a', 'b', 'c'], 'c')
        self.assertEqual(mainpage, {'Theme': {'name': 'c'}})
        self.assertEqual(d.paint_theme_sample.called, 1)

    def test_color(self):
        d = self.page
        d.on_new_color_set = Func()
        # self.color is only set in get_color through ColorChooser.
        d.color.set('green')
        self.assertEqual(d.on_new_color_set.called, 1)
        del d.on_new_color_set

    def test_highlight_target_list_mouse(self):
        # Set highlight_target through targetlist.
        eq = self.assertEqual
        d = self.page

        d.targetlist.SetMenu(['a', 'b', 'c'], 'c')
        eq(d.highlight_target.get(), 'c')
        eq(d.set_highlight_target.called, 1)

    def test_highlight_target_text_mouse(self):
        # Set highlight_target through clicking highlight_sample.
        eq = self.assertEqual
        d = self.page

        elem = {}
        count = 0
        hs = d.highlight_sample
        hs.focus_force()
        hs.see(1.0)
        hs.update_idletasks()

        def tag_to_element(elem):
            for element, tag in d.theme_elements.items():
                elem[tag[0]] = element

        def click_it(start):
            x, y, dx, dy = hs.bbox(start)
            x += dx // 2
            y += dy // 2
            hs.event_generate('<Enter>', x=0, y=0)
            hs.event_generate('<Motion>', x=x, y=y)
            hs.event_generate('<ButtonPress-1>', x=x, y=y)
            hs.event_generate('<ButtonRelease-1>', x=x, y=y)

        # Flip theme_elements to make the tag the key.
        tag_to_element(elem)

        # If highlight_sample has a tag that isn't in theme_elements, there
        # will be a KeyError in the test run.
        for tag in hs.tag_names():
            for start_index in hs.tag_ranges(tag)[0::2]:
                count += 1
                click_it(start_index)
                eq(d.highlight_target.get(), elem[tag])
                eq(d.set_highlight_target.called, count)

    def test_set_theme_type(self):
        eq = self.assertEqual
        d = self.page
        del d.set_theme_type

        # Builtin theme selected.
        d.theme_source.set(True)
        d.set_theme_type()
        eq(d.builtinlist['state'], NORMAL)
        eq(d.customlist['state'], DISABLED)
        eq(d.button_delete_custom.state(), ('disabled',))

        # Custom theme selected.
        d.theme_source.set(False)
        d.set_theme_type()
        eq(d.builtinlist['state'], DISABLED)
        eq(d.custom_theme_on.state(), ('selected',))
        eq(d.customlist['state'], NORMAL)
        eq(d.button_delete_custom.state(), ())
        d.set_theme_type = Func()

    def test_get_color(self):
        eq = self.assertEqual
        d = self.page
        orig_chooser = configdialog.tkColorChooser.askcolor
        chooser = configdialog.tkColorChooser.askcolor = Func()
        gntn = d.get_new_theme_name = Func()

        d.highlight_target.set('Editor Breakpoint')
        d.color.set('#ffffff')

        # Nothing selected.
        chooser.result = (None, None)
        d.button_set_color.invoke()
        eq(d.color.get(), '#ffffff')

        # Selection same as previous color.
        chooser.result = ('', d.style.lookup(d.frame_color_set['style'], 'background'))
        d.button_set_color.invoke()
        eq(d.color.get(), '#ffffff')

        # Select different color.
        chooser.result = ((222.8671875, 0.0, 0.0), '#de0000')

        # Default theme.
        d.color.set('#ffffff')
        d.theme_source.set(True)

        # No theme name selected therefore color not saved.
        gntn.result = ''
        d.button_set_color.invoke()
        eq(gntn.called, 1)
        eq(d.color.get(), '#ffffff')
        # Theme name selected.
        gntn.result = 'My New Theme'
        d.button_set_color.invoke()
        eq(d.custom_name.get(), gntn.result)
        eq(d.color.get(), '#de0000')

        # Custom theme.
        d.color.set('#ffffff')
        d.theme_source.set(False)
        d.button_set_color.invoke()
        eq(d.color.get(), '#de0000')

        del d.get_new_theme_name
        configdialog.tkColorChooser.askcolor = orig_chooser

    def test_on_new_color_set(self):
        d = self.page
        color = '#3f7cae'
        d.custom_name.set('Python')
        d.highlight_target.set('Selected Text')
        d.fg_bg_toggle.set(True)

        d.color.set(color)
        self.assertEqual(d.style.lookup(d.frame_color_set['style'], 'background'), color)
        self.assertEqual(d.highlight_sample.tag_cget('hilite', 'foreground'), color)
        self.assertEqual(highpage,
                         {'Python': {'hilite-foreground': color}})

    def test_get_new_theme_name(self):
        orig_sectionname = configdialog.SectionName
        sn = configdialog.SectionName = Func(return_self=True)
        d = self.page

        sn.result = 'New Theme'
        self.assertEqual(d.get_new_theme_name(''), 'New Theme')

        configdialog.SectionName = orig_sectionname

    def test_save_as_new_theme(self):
        d = self.page
        gntn = d.get_new_theme_name = Func()
        d.theme_source.set(True)

        # No name entered.
        gntn.result = ''
        d.button_save_custom.invoke()
        self.assertNotIn(gntn.result, idleConf.userCfg['highlight'])

        # Name entered.
        gntn.result = 'my new theme'
        gntn.called = 0
        self.assertNotIn(gntn.result, idleConf.userCfg['highlight'])
        d.button_save_custom.invoke()
        self.assertIn(gntn.result, idleConf.userCfg['highlight'])

        del d.get_new_theme_name

    def test_create_new_and_save_new(self):
        eq = self.assertEqual
        d = self.page

        # Use default as previously active theme.
        d.theme_source.set(True)
        d.builtin_name.set('IDLE Classic')
        first_new = 'my new custom theme'
        second_new = 'my second custom theme'

        # No changes, so themes are an exact copy.
        self.assertNotIn(first_new, idleConf.userCfg)
        d.create_new(first_new)
        eq(idleConf.GetSectionList('user', 'highlight'), [first_new])
        eq(idleConf.GetThemeDict('default', 'IDLE Classic'),
           idleConf.GetThemeDict('user', first_new))
        eq(d.custom_name.get(), first_new)
        self.assertFalse(d.theme_source.get())  # Use custom set.
        eq(d.set_theme_type.called, 1)

        # Test that changed targets are in new theme.
        changes.add_option('highlight', first_new, 'hit-background', 'yellow')
        self.assertNotIn(second_new, idleConf.userCfg)
        d.create_new(second_new)
        eq(idleConf.GetSectionList('user', 'highlight'), [first_new, second_new])
        self.assertNotEqual(idleConf.GetThemeDict('user', first_new),
                            idleConf.GetThemeDict('user', second_new))
        # Check that difference in themes was in `hit-background` from `changes`.
        idleConf.SetOption('highlight', first_new, 'hit-background', 'yellow')
        eq(idleConf.GetThemeDict('user', first_new),
           idleConf.GetThemeDict('user', second_new))

    def test_set_highlight_target(self):
        eq = self.assertEqual
        d = self.page
        del d.set_highlight_target

        # Target is cursor.
        d.highlight_target.set('Cursor')
        eq(d.fg_on.state(), ('disabled', 'selected'))
        eq(d.bg_on.state(), ('disabled',))
        self.assertTrue(d.fg_bg_toggle)
        eq(d.set_color_sample.called, 1)

        # Target is not cursor.
        d.highlight_target.set('Comment')
        eq(d.fg_on.state(), ('selected',))
        eq(d.bg_on.state(), ())
        self.assertTrue(d.fg_bg_toggle)
        eq(d.set_color_sample.called, 2)

        d.set_highlight_target = Func()

    def test_set_color_sample_binding(self):
        d = self.page
        scs = d.set_color_sample

        d.fg_on.invoke()
        self.assertEqual(scs.called, 1)

        d.bg_on.invoke()
        self.assertEqual(scs.called, 2)

    def test_set_color_sample(self):
        d = self.page
        del d.set_color_sample
        d.highlight_target.set('Selected Text')
        d.fg_bg_toggle.set(True)
        d.set_color_sample()
        self.assertEqual(
                d.style.lookup(d.frame_color_set['style'], 'background'),
                d.highlight_sample.tag_cget('hilite', 'foreground'))
        d.set_color_sample = Func()

    def test_paint_theme_sample(self):
        eq = self.assertEqual
        page = self.page
        del page.paint_theme_sample  # Delete masking mock.
        hs_tag = page.highlight_sample.tag_cget
        gh = idleConf.GetHighlight

        # Create custom theme based on IDLE Dark.
        page.theme_source.set(True)
        page.builtin_name.set('IDLE Dark')
        theme = 'IDLE Test'
        page.create_new(theme)
        page.set_color_sample.called = 0

        # Base theme with nothing in `changes`.
        page.paint_theme_sample()
        new_console = {'foreground': 'blue',
                       'background': 'yellow',}
        for key, value in new_console.items():
            self.assertNotEqual(hs_tag('console', key), value)
        eq(page.set_color_sample.called, 1)

        # Apply changes.
        for key, value in new_console.items():
            changes.add_option('highlight', theme, 'console-'+key, value)
        page.paint_theme_sample()
        for key, value in new_console.items():
            eq(hs_tag('console', key), value)
        eq(page.set_color_sample.called, 2)

        page.paint_theme_sample = Func()

    def test_delete_custom(self):
        eq = self.assertEqual
        d = self.page
        d.button_delete_custom.state(('!disabled',))
        yesno = d.askyesno = Func()
        dialog.deactivate_current_config = Func()
        dialog.activate_config_changes = Func()

        theme_name = 'spam theme'
        idleConf.userCfg['highlight'].SetOption(theme_name, 'name', 'value')
        highpage[theme_name] = {'option': 'True'}

        # Force custom theme.
        d.theme_source.set(False)
        d.custom_name.set(theme_name)

        # Cancel deletion.
        yesno.result = False
        d.button_delete_custom.invoke()
        eq(yesno.called, 1)
        eq(highpage[theme_name], {'option': 'True'})
        eq(idleConf.GetSectionList('user', 'highlight'), ['spam theme'])
        eq(dialog.deactivate_current_config.called, 0)
        eq(dialog.activate_config_changes.called, 0)
        eq(d.set_theme_type.called, 0)

        # Confirm deletion.
        yesno.result = True
        d.button_delete_custom.invoke()
        eq(yesno.called, 2)
        self.assertNotIn(theme_name, highpage)
        eq(idleConf.GetSectionList('user', 'highlight'), [])
        eq(d.custom_theme_on.state(), ('disabled',))
        eq(d.custom_name.get(), '- no custom themes -')
        eq(dialog.deactivate_current_config.called, 1)
        eq(dialog.activate_config_changes.called, 1)
        eq(d.set_theme_type.called, 1)

        del dialog.activate_config_changes, dialog.deactivate_current_config
        del d.askyesno


class KeysPageTest(unittest.TestCase):
    """Test that keys tab widgets enable users to make changes.

    Test that widget actions set vars, that var changes add
    options to changes and that key sets works correctly.
    """

    @classmethod
    def setUpClass(cls):
        page = cls.page = dialog.keyspage
        dialog.note.select(page)
        page.set_keys_type = Func()
        page.load_keys_list = Func()

    @classmethod
    def tearDownClass(cls):
        page = cls.page
        del page.set_keys_type, page.load_keys_list

    def setUp(self):
        d = self.page
        # The following is needed for test_load_key_cfg, _delete_custom_keys.
        # This may indicate a defect in some test or function.
        for section in idleConf.GetSectionList('user', 'keys'):
            idleConf.userCfg['keys'].remove_section(section)
        changes.clear()
        d.set_keys_type.called = 0
        d.load_keys_list.called = 0

    def test_load_key_cfg(self):
        tracers.detach()
        d = self.page
        eq = self.assertEqual

        # Use builtin keyset with no user keysets created.
        idleConf.CurrentKeys = mock.Mock(return_value='IDLE Classic OSX')
        d.load_key_cfg()
        self.assertTrue(d.keyset_source.get())
        # builtinlist sets variable builtin_name to the CurrentKeys default.
        eq(d.builtin_name.get(), 'IDLE Classic OSX')
        eq(d.custom_name.get(), '- no custom keys -')
        eq(d.custom_keyset_on.state(), ('disabled',))
        eq(d.set_keys_type.called, 1)
        eq(d.load_keys_list.called, 1)
        eq(d.load_keys_list.args, ('IDLE Classic OSX', ))

        # Builtin keyset with non-empty user keyset list.
        idleConf.SetOption('keys', 'test1', 'option', 'value')
        idleConf.SetOption('keys', 'test2', 'option2', 'value2')
        d.load_key_cfg()
        eq(d.builtin_name.get(), 'IDLE Classic OSX')
        eq(d.custom_name.get(), 'test1')
        eq(d.set_keys_type.called, 2)
        eq(d.load_keys_list.called, 2)
        eq(d.load_keys_list.args, ('IDLE Classic OSX', ))

        # Use custom keyset.
        idleConf.CurrentKeys = mock.Mock(return_value='test2')
        idleConf.default_keys = mock.Mock(return_value='IDLE Modern Unix')
        idleConf.SetOption('main', 'Keys', 'default', '0')
        d.load_key_cfg()
        self.assertFalse(d.keyset_source.get())
        eq(d.builtin_name.get(), 'IDLE Modern Unix')
        eq(d.custom_name.get(), 'test2')
        eq(d.set_keys_type.called, 3)
        eq(d.load_keys_list.called, 3)
        eq(d.load_keys_list.args, ('test2', ))

        del idleConf.CurrentKeys, idleConf.default_keys
        tracers.attach()

    def test_keyset_source(self):
        eq = self.assertEqual
        d = self.page
        # Test these separately.
        d.var_changed_builtin_name = Func()
        d.var_changed_custom_name = Func()
        # Builtin selected.
        d.builtin_keyset_on.invoke()
        eq(mainpage, {'Keys': {'default': 'True'}})
        eq(d.var_changed_builtin_name.called, 1)
        eq(d.var_changed_custom_name.called, 0)
        changes.clear()

        # Custom selected.
        d.custom_keyset_on.state(('!disabled',))
        d.custom_keyset_on.invoke()
        self.assertEqual(mainpage, {'Keys': {'default': 'False'}})
        eq(d.var_changed_builtin_name.called, 1)
        eq(d.var_changed_custom_name.called, 1)
        del d.var_changed_builtin_name, d.var_changed_custom_name

    def test_builtin_name(self):
        eq = self.assertEqual
        d = self.page
        idleConf.userCfg['main'].remove_section('Keys')
        item_list = ['IDLE Classic Windows', 'IDLE Classic OSX',
                     'IDLE Modern UNIX']

        # Not in old_keys, defaults name to first item.
        d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX')
        eq(mainpage, {'Keys': {'name': 'IDLE Classic Windows',
                               'name2': 'IDLE Modern UNIX'}})
        eq(d.keys_message['text'], 'New key set, see Help')
        eq(d.load_keys_list.called, 1)
        eq(d.load_keys_list.args, ('IDLE Modern UNIX', ))

        # Not in old keys - uses name2.
        changes.clear()
        idleConf.SetOption('main', 'Keys', 'name', 'IDLE Classic Unix')
        d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX')
        eq(mainpage, {'Keys': {'name2': 'IDLE Modern UNIX'}})
        eq(d.keys_message['text'], 'New key set, see Help')
        eq(d.load_keys_list.called, 2)
        eq(d.load_keys_list.args, ('IDLE Modern UNIX', ))

        # Builtin name in old_keys.
        changes.clear()
        d.builtinlist.SetMenu(item_list, 'IDLE Classic OSX')
        eq(mainpage, {'Keys': {'name': 'IDLE Classic OSX', 'name2': ''}})
        eq(d.keys_message['text'], '')
        eq(d.load_keys_list.called, 3)
        eq(d.load_keys_list.args, ('IDLE Classic OSX', ))

    def test_custom_name(self):
        d = self.page

        # If no selections, doesn't get added.
        d.customlist.SetMenu([], '- no custom keys -')
        self.assertNotIn('Keys', mainpage)
        self.assertEqual(d.load_keys_list.called, 0)

        # Custom name selected.
        changes.clear()
        d.customlist.SetMenu(['a', 'b', 'c'], 'c')
        self.assertEqual(mainpage, {'Keys': {'name': 'c'}})
        self.assertEqual(d.load_keys_list.called, 1)

    def test_keybinding(self):
        idleConf.SetOption('extensions', 'ZzDummy', 'enable', 'True')
        d = self.page
        d.custom_name.set('my custom keys')
        d.bindingslist.delete(0, 'end')
        d.bindingslist.insert(0, 'copy')
        d.bindingslist.insert(1, 'z-in')
        d.bindingslist.selection_set(0)
        d.bindingslist.selection_anchor(0)
        # Core binding - adds to keys.
        d.keybinding.set('<Key-F11>')
        self.assertEqual(keyspage,
                         {'my custom keys': {'copy': '<Key-F11>'}})

        # Not a core binding - adds to extensions.
        d.bindingslist.selection_set(1)
        d.bindingslist.selection_anchor(1)
        d.keybinding.set('<Key-F11>')
        self.assertEqual(extpage,
                         {'ZzDummy_cfgBindings': {'z-in': '<Key-F11>'}})

    def test_set_keys_type(self):
        eq = self.assertEqual
        d = self.page
        del d.set_keys_type

        # Builtin keyset selected.
        d.keyset_source.set(True)
        d.set_keys_type()
        eq(d.builtinlist['state'], NORMAL)
        eq(d.customlist['state'], DISABLED)
        eq(d.button_delete_custom_keys.state(), ('disabled',))

        # Custom keyset selected.
        d.keyset_source.set(False)
        d.set_keys_type()
        eq(d.builtinlist['state'], DISABLED)
        eq(d.custom_keyset_on.state(), ('selected',))
        eq(d.customlist['state'], NORMAL)
        eq(d.button_delete_custom_keys.state(), ())
        d.set_keys_type = Func()

    def test_get_new_keys(self):
        eq = self.assertEqual
        d = self.page
        orig_getkeysdialog = configdialog.GetKeysDialog
        gkd = configdialog.GetKeysDialog = Func(return_self=True)
        gnkn = d.get_new_keys_name = Func()

        d.button_new_keys.state(('!disabled',))
        d.bindingslist.delete(0, 'end')
        d.bindingslist.insert(0, 'copy - <Control-Shift-Key-C>')
        d.bindingslist.selection_set(0)
        d.bindingslist.selection_anchor(0)
        d.keybinding.set('Key-a')
        d.keyset_source.set(True)  # Default keyset.

        # Default keyset; no change to binding.
        gkd.result = ''
        d.button_new_keys.invoke()
        eq(d.bindingslist.get('anchor'), 'copy - <Control-Shift-Key-C>')
        # Keybinding isn't changed when there isn't a change entered.
        eq(d.keybinding.get(), 'Key-a')

        # Default keyset; binding changed.
        gkd.result = '<Key-F11>'
        # No keyset name selected therefore binding not saved.
        gnkn.result = ''
        d.button_new_keys.invoke()
        eq(gnkn.called, 1)
        eq(d.bindingslist.get('anchor'), 'copy - <Control-Shift-Key-C>')
        # Keyset name selected.
        gnkn.result = 'My New Key Set'
        d.button_new_keys.invoke()
        eq(d.custom_name.get(), gnkn.result)
        eq(d.bindingslist.get('anchor'), 'copy - <Key-F11>')
        eq(d.keybinding.get(), '<Key-F11>')

        # User keyset; binding changed.
        d.keyset_source.set(False)  # Custom keyset.
        gnkn.called = 0
        gkd.result = '<Key-p>'
        d.button_new_keys.invoke()
        eq(gnkn.called, 0)
        eq(d.bindingslist.get('anchor'), 'copy - <Key-p>')
        eq(d.keybinding.get(), '<Key-p>')

        del d.get_new_keys_name
        configdialog.GetKeysDialog = orig_getkeysdialog

    def test_get_new_keys_name(self):
        orig_sectionname = configdialog.SectionName
        sn = configdialog.SectionName = Func(return_self=True)
        d = self.page

        sn.result = 'New Keys'
        self.assertEqual(d.get_new_keys_name(''), 'New Keys')

        configdialog.SectionName = orig_sectionname

    def test_save_as_new_key_set(self):
        d = self.page
        gnkn = d.get_new_keys_name = Func()
        d.keyset_source.set(True)

        # No name entered.
        gnkn.result = ''
        d.button_save_custom_keys.invoke()

        # Name entered.
        gnkn.result = 'my new key set'
        gnkn.called = 0
        self.assertNotIn(gnkn.result, idleConf.userCfg['keys'])
        d.button_save_custom_keys.invoke()
        self.assertIn(gnkn.result, idleConf.userCfg['keys'])

        del d.get_new_keys_name

    def test_on_bindingslist_select(self):
        d = self.page
        b = d.bindingslist
        b.delete(0, 'end')
        b.insert(0, 'copy')
        b.insert(1, 'find')
        b.activate(0)

        b.focus_force()
        b.see(1)
        b.update()
        x, y, dx, dy = b.bbox(1)
        x += dx // 2
        y += dy // 2
        b.event_generate('<Enter>', x=0, y=0)
        b.event_generate('<Motion>', x=x, y=y)
        b.event_generate('<Button-1>', x=x, y=y)
        b.event_generate('<ButtonRelease-1>', x=x, y=y)
        self.assertEqual(b.get('anchor'), 'find')
        self.assertEqual(d.button_new_keys.state(), ())

    def test_create_new_key_set_and_save_new_key_set(self):
        eq = self.assertEqual
        d = self.page

        # Use default as previously active keyset.
        d.keyset_source.set(True)
        d.builtin_name.set('IDLE Classic Windows')
        first_new = 'my new custom key set'
        second_new = 'my second custom keyset'

        # No changes, so keysets are an exact copy.
        self.assertNotIn(first_new, idleConf.userCfg)
        d.create_new_key_set(first_new)
        eq(idleConf.GetSectionList('user', 'keys'), [first_new])
        eq(idleConf.GetKeySet('IDLE Classic Windows'),
           idleConf.GetKeySet(first_new))
        eq(d.custom_name.get(), first_new)
        self.assertFalse(d.keyset_source.get())  # Use custom set.
        eq(d.set_keys_type.called, 1)

        # Test that changed keybindings are in new keyset.
        changes.add_option('keys', first_new, 'copy', '<Key-F11>')
        self.assertNotIn(second_new, idleConf.userCfg)
        d.create_new_key_set(second_new)
        eq(idleConf.GetSectionList('user', 'keys'), [first_new, second_new])
        self.assertNotEqual(idleConf.GetKeySet(first_new),
                            idleConf.GetKeySet(second_new))
        # Check that difference in keysets was in option `copy` from `changes`.
        idleConf.SetOption('keys', first_new, 'copy', '<Key-F11>')
        eq(idleConf.GetKeySet(first_new), idleConf.GetKeySet(second_new))

    def test_load_keys_list(self):
        eq = self.assertEqual
        d = self.page
        gks = idleConf.GetKeySet = Func()
        del d.load_keys_list
        b = d.bindingslist

        b.delete(0, 'end')
        b.insert(0, '<<find>>')
        b.insert(1, '<<help>>')
        gks.result = {'<<copy>>': ['<Control-Key-c>', '<Control-Key-C>'],
                      '<<force-open-completions>>': ['<Control-Key-space>'],
                      '<<spam>>': ['<Key-F11>']}
        changes.add_option('keys', 'my keys', 'spam', '<Shift-Key-a>')
        expected = ('copy - <Control-Key-c> <Control-Key-C>',
                    'force-open-completions - <Control-Key-space>',
                    'spam - <Shift-Key-a>')

        # No current selection.
        d.load_keys_list('my keys')
        eq(b.get(0, 'end'), expected)
        eq(b.get('anchor'), '')
        eq(b.curselection(), ())

        # Check selection.
        b.selection_set(1)
        b.selection_anchor(1)
        d.load_keys_list('my keys')
        eq(b.get(0, 'end'), expected)
        eq(b.get('anchor'), 'force-open-completions - <Control-Key-space>')
        eq(b.curselection(), (1, ))

        # Change selection.
        b.selection_set(2)
        b.selection_anchor(2)
        d.load_keys_list('my keys')
        eq(b.get(0, 'end'), expected)
        eq(b.get('anchor'), 'spam - <Shift-Key-a>')
        eq(b.curselection(), (2, ))
        d.load_keys_list = Func()

        del idleConf.GetKeySet

    def test_delete_custom_keys(self):
        eq = self.assertEqual
        d = self.page
        d.button_delete_custom_keys.state(('!disabled',))
        yesno = d.askyesno = Func()
        dialog.deactivate_current_config = Func()
        dialog.activate_config_changes = Func()

        keyset_name = 'spam key set'
        idleConf.userCfg['keys'].SetOption(keyset_name, 'name', 'value')
        keyspage[keyset_name] = {'option': 'True'}

        # Force custom keyset.
        d.keyset_source.set(False)
        d.custom_name.set(keyset_name)

        # Cancel deletion.
        yesno.result = False
        d.button_delete_custom_keys.invoke()
        eq(yesno.called, 1)
        eq(keyspage[keyset_name], {'option': 'True'})
        eq(idleConf.GetSectionList('user', 'keys'), ['spam key set'])
        eq(dialog.deactivate_current_config.called, 0)
        eq(dialog.activate_config_changes.called, 0)
        eq(d.set_keys_type.called, 0)

        # Confirm deletion.
        yesno.result = True
        d.button_delete_custom_keys.invoke()
        eq(yesno.called, 2)
        self.assertNotIn(keyset_name, keyspage)
        eq(idleConf.GetSectionList('user', 'keys'), [])
        eq(d.custom_keyset_on.state(), ('disabled',))
        eq(d.custom_name.get(), '- no custom keys -')
        eq(dialog.deactivate_current_config.called, 1)
        eq(dialog.activate_config_changes.called, 1)
        eq(d.set_keys_type.called, 1)

        del dialog.activate_config_changes, dialog.deactivate_current_config
        del d.askyesno


class GenPageTest(unittest.TestCase):
    """Test that general tab widgets enable users to make changes.

    Test that widget actions set vars, that var changes add
    options to changes and that helplist works correctly.
    """
    @classmethod
    def setUpClass(cls):
        page = cls.page = dialog.genpage
        dialog.note.select(page)
        page.set = page.set_add_delete_state = Func()
        page.upc = page.update_help_changes = Func()
        page.update()

    @classmethod
    def tearDownClass(cls):
        page = cls.page
        del page.set, page.set_add_delete_state
        del page.upc, page.update_help_changes
        page.helplist.delete(0, 'end')
        page.user_helplist.clear()

    def setUp(self):
        changes.clear()

    def test_load_general_cfg(self):
        # Set to wrong values, load, check right values.
        eq = self.assertEqual
        d = self.page
        d.startup_edit.set(1)
        d.autosave.set(1)
        d.win_width.set(1)
        d.win_height.set(1)
        d.helplist.insert('end', 'bad')
        d.user_helplist = ['bad', 'worse']
        idleConf.SetOption('main', 'HelpFiles', '1', 'name;file')
        d.load_general_cfg()
        eq(d.startup_edit.get(), 0)
        eq(d.autosave.get(), 0)
        eq(d.win_width.get(), '80')
        eq(d.win_height.get(), '40')
        eq(d.helplist.get(0, 'end'), ('name',))
        eq(d.user_helplist, [('name', 'file', '1')])

    def test_startup(self):
        d = self.page
        d.startup_editor_on.invoke()
        self.assertEqual(mainpage,
                         {'General': {'editor-on-startup': '1'}})
        changes.clear()
        d.startup_shell_on.invoke()
        self.assertEqual(mainpage,
                         {'General': {'editor-on-startup': '0'}})

    def test_editor_size(self):
        d = self.page
        d.win_height_int.delete(0, 'end')
        d.win_height_int.insert(0, '11')
        self.assertEqual(mainpage, {'EditorWindow': {'height': '11'}})
        changes.clear()
        d.win_width_int.delete(0, 'end')
        d.win_width_int.insert(0, '11')
        self.assertEqual(mainpage, {'EditorWindow': {'width': '11'}})

    def test_cursor_blink(self):
        self.page.cursor_blink_bool.invoke()
        self.assertEqual(mainpage, {'EditorWindow': {'cursor-blink': 'False'}})

    def test_autocomplete_wait(self):
        self.page.auto_wait_int.delete(0, 'end')
        self.page.auto_wait_int.insert(0, '11')
        self.assertEqual(extpage, {'AutoComplete': {'popupwait': '11'}})

    def test_parenmatch(self):
        d = self.page
        eq = self.assertEqual
        d.paren_style_type['menu'].invoke(0)
        eq(extpage, {'ParenMatch': {'style': 'opener'}})
        changes.clear()
        d.paren_flash_time.delete(0, 'end')
        d.paren_flash_time.insert(0, '11')
        eq(extpage, {'ParenMatch': {'flash-delay': '11'}})
        changes.clear()
        d.bell_on.invoke()
        eq(extpage, {'ParenMatch': {'bell': 'False'}})

    def test_autosave(self):
        d = self.page
        d.save_auto_on.invoke()
        self.assertEqual(mainpage, {'General': {'autosave': '1'}})
        d.save_ask_on.invoke()
        self.assertEqual(mainpage, {'General': {'autosave': '0'}})

    def test_paragraph(self):
        self.page.format_width_int.delete(0, 'end')
        self.page.format_width_int.insert(0, '11')
        self.assertEqual(extpage, {'FormatParagraph': {'max-width': '11'}})

    def test_context(self):
        self.page.context_int.delete(0, 'end')
        self.page.context_int.insert(0, '1')
        self.assertEqual(extpage, {'CodeContext': {'maxlines': '1'}})

    def test_source_selected(self):
        d = self.page
        d.set = d.set_add_delete_state
        d.upc = d.update_help_changes
        helplist = d.helplist
        dex = 'end'
        helplist.insert(dex, 'source')
        helplist.activate(dex)

        helplist.focus_force()
        helplist.see(dex)
        helplist.update()
        x, y, dx, dy = helplist.bbox(dex)
        x += dx // 2
        y += dy // 2
        d.set.called = d.upc.called = 0
        helplist.event_generate('<Enter>', x=0, y=0)
        helplist.event_generate('<Motion>', x=x, y=y)
        helplist.event_generate('<Button-1>', x=x, y=y)
        helplist.event_generate('<ButtonRelease-1>', x=x, y=y)
        self.assertEqual(helplist.get('anchor'), 'source')
        self.assertTrue(d.set.called)
        self.assertFalse(d.upc.called)

    def test_set_add_delete_state(self):
        # Call with 0 items, 1 unselected item, 1 selected item.
        eq = self.assertEqual
        d = self.page
        del d.set_add_delete_state  # Unmask method.
        sad = d.set_add_delete_state
        h = d.helplist

        h.delete(0, 'end')
        sad()
        eq(d.button_helplist_edit.state(), ('disabled',))
        eq(d.button_helplist_remove.state(), ('disabled',))

        h.insert(0, 'source')
        sad()
        eq(d.button_helplist_edit.state(), ('disabled',))
        eq(d.button_helplist_remove.state(), ('disabled',))

        h.selection_set(0)
        sad()
        eq(d.button_helplist_edit.state(), ())
        eq(d.button_helplist_remove.state(), ())
        d.set_add_delete_state = Func()  # Mask method.

    def test_helplist_item_add(self):
        # Call without and twice with HelpSource result.
        # Double call enables check on order.
        eq = self.assertEqual
        orig_helpsource = configdialog.HelpSource
        hs = configdialog.HelpSource = Func(return_self=True)
        d = self.page
        d.helplist.delete(0, 'end')
        d.user_helplist.clear()
        d.set.called = d.upc.called = 0

        hs.result = ''
        d.helplist_item_add()
        self.assertTrue(list(d.helplist.get(0, 'end')) ==
                        d.user_helplist == [])
        self.assertFalse(d.upc.called)

        hs.result = ('name1', 'file1')
        d.helplist_item_add()
        hs.result = ('name2', 'file2')
        d.helplist_item_add()
        eq(d.helplist.get(0, 'end'), ('name1', 'name2'))
        eq(d.user_helplist, [('name1', 'file1'), ('name2', 'file2')])
        eq(d.upc.called, 2)
        self.assertFalse(d.set.called)

        configdialog.HelpSource = orig_helpsource

    def test_helplist_item_edit(self):
        # Call without and with HelpSource change.
        eq = self.assertEqual
        orig_helpsource = configdialog.HelpSource
        hs = configdialog.HelpSource = Func(return_self=True)
        d = self.page
        d.helplist.delete(0, 'end')
        d.helplist.insert(0, 'name1')
        d.helplist.selection_set(0)
        d.helplist.selection_anchor(0)
        d.user_helplist.clear()
        d.user_helplist.append(('name1', 'file1'))
        d.set.called = d.upc.called = 0

        hs.result = ''
        d.helplist_item_edit()
        hs.result = ('name1', 'file1')
        d.helplist_item_edit()
        eq(d.helplist.get(0, 'end'), ('name1',))
        eq(d.user_helplist, [('name1', 'file1')])
        self.assertFalse(d.upc.called)

        hs.result = ('name2', 'file2')
        d.helplist_item_edit()
        eq(d.helplist.get(0, 'end'), ('name2',))
        eq(d.user_helplist, [('name2', 'file2')])
        self.assertTrue(d.upc.called == d.set.called == 1)

        configdialog.HelpSource = orig_helpsource

    def test_helplist_item_remove(self):
        eq = self.assertEqual
        d = self.page
        d.helplist.delete(0, 'end')
        d.helplist.insert(0, 'name1')
        d.helplist.selection_set(0)
        d.helplist.selection_anchor(0)
        d.user_helplist.clear()
        d.user_helplist.append(('name1', 'file1'))
        d.set.called = d.upc.called = 0

        d.helplist_item_remove()
        eq(d.helplist.get(0, 'end'), ())
        eq(d.user_helplist, [])
        self.assertTrue(d.upc.called == d.set.called == 1)

    def test_update_help_changes(self):
        d = self.page
        del d.update_help_changes
        d.user_helplist.clear()
        d.user_helplist.append(('name1', 'file1'))
        d.user_helplist.append(('name2', 'file2'))

        d.update_help_changes()
        self.assertEqual(mainpage['HelpFiles'],
                         {'1': 'name1;file1', '2': 'name2;file2'})
        d.update_help_changes = Func()


class VarTraceTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.tracers = configdialog.VarTrace()
        cls.iv = IntVar(root)
        cls.bv = BooleanVar(root)

    @classmethod
    def tearDownClass(cls):
        del cls.tracers, cls.iv, cls.bv

    def setUp(self):
        self.tracers.clear()
        self.called = 0

    def var_changed_increment(self, *params):
        self.called += 13

    def var_changed_boolean(self, *params):
        pass

    def test_init(self):
        tr = self.tracers
        tr.__init__()
        self.assertEqual(tr.untraced, [])
        self.assertEqual(tr.traced, [])

    def test_clear(self):
        tr = self.tracers
        tr.untraced.append(0)
        tr.traced.append(1)
        tr.clear()
        self.assertEqual(tr.untraced, [])
        self.assertEqual(tr.traced, [])

    def test_add(self):
        tr = self.tracers
        func = Func()
        cb = tr.make_callback = mock.Mock(return_value=func)

        iv = tr.add(self.iv, self.var_changed_increment)
        self.assertIs(iv, self.iv)
        bv = tr.add(self.bv, self.var_changed_boolean)
        self.assertIs(bv, self.bv)

        sv = StringVar(root)
        sv2 = tr.add(sv, ('main', 'section', 'option'))
        self.assertIs(sv2, sv)
        cb.assert_called_once()
        cb.assert_called_with(sv, ('main', 'section', 'option'))

        expected = [(iv, self.var_changed_increment),
                    (bv, self.var_changed_boolean),
                    (sv, func)]
        self.assertEqual(tr.traced, [])
        self.assertEqual(tr.untraced, expected)

        del tr.make_callback

    def test_make_callback(self):
        cb = self.tracers.make_callback(self.iv, ('main', 'section', 'option'))
        self.assertTrue(callable(cb))
        self.iv.set(42)
        # Not attached, so set didn't invoke the callback.
        self.assertNotIn('section', changes['main'])
        # Invoke callback manually.
        cb()
        self.assertIn('section', changes['main'])
        self.assertEqual(changes['main']['section']['option'], '42')
        changes.clear()

    def test_attach_detach(self):
        tr = self.tracers
        iv = tr.add(self.iv, self.var_changed_increment)
        bv = tr.add(self.bv, self.var_changed_boolean)
        expected = [(iv, self.var_changed_increment),
                    (bv, self.var_changed_boolean)]

        # Attach callbacks and test call increment.
        tr.attach()
        self.assertEqual(tr.untraced, [])
        self.assertCountEqual(tr.traced, expected)
        iv.set(1)
        self.assertEqual(iv.get(), 1)
        self.assertEqual(self.called, 13)

        # Check that only one callback is attached to a variable.
        # If more than one callback were attached, then var_changed_increment
        # would be called twice and the counter would be 2.
        self.called = 0
        tr.attach()
        iv.set(1)
        self.assertEqual(self.called, 13)

        # Detach callbacks.
        self.called = 0
        tr.detach()
        self.assertEqual(tr.traced, [])
        self.assertCountEqual(tr.untraced, expected)
        iv.set(1)
        self.assertEqual(self.called, 0)


if __name__ == '__main__':
    unittest.main(verbosity=2)
interp, "tearoff", TCL_STATIC); } else { Tcl_SetStringObj(Tcl_GetObjResult(interp), menuEntryTypeStrings[menuPtr->entries[index]->type], -1); } break; } case MENU_UNPOST: if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); goto error; } Tk_UnmapWindow(menuPtr->tkwin); result = TkPostSubmenu(interp, menuPtr, NULL); break; case MENU_XPOSITION: if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "index"); goto error; } result = MenuDoXPosition(interp, menuPtr, objv[2]); break; case MENU_YPOSITION: if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "index"); goto error; } result = MenuDoYPosition(interp, menuPtr, objv[2]); break; } done: Tcl_Release((ClientData) menuPtr); return result; error: Tcl_Release((ClientData) menuPtr); return TCL_ERROR; } /* *---------------------------------------------------------------------- * * TkInvokeMenu -- * * Given a menu and an index, takes the appropriate action for the entry * associated with that index. * * Results: * Standard Tcl result. * * Side effects: * Commands may get excecuted; variables may get set; sub-menus may get * posted. * *---------------------------------------------------------------------- */ int TkInvokeMenu( Tcl_Interp *interp, /* The interp that the menu lives in. */ TkMenu *menuPtr, /* The menu we are invoking. */ int index) /* The zero based index of the item we are * invoking. */ { int result = TCL_OK; TkMenuEntry *mePtr; if (index < 0) { goto done; } mePtr = menuPtr->entries[index]; if (mePtr->state == ENTRY_DISABLED) { goto done; } Tcl_Preserve((ClientData) mePtr); if (mePtr->type == TEAROFF_ENTRY) { Tcl_DString ds; Tcl_DStringInit(&ds); Tcl_DStringAppend(&ds, "tk::TearOffMenu ", -1); Tcl_DStringAppend(&ds, Tk_PathName(menuPtr->tkwin), -1); result = Tcl_Eval(interp, Tcl_DStringValue(&ds)); Tcl_DStringFree(&ds); } else if ((mePtr->type == CHECK_BUTTON_ENTRY) && (mePtr->namePtr != NULL)) { Tcl_Obj *valuePtr; if (mePtr->entryFlags & ENTRY_SELECTED) { valuePtr = mePtr->offValuePtr; } else { valuePtr = mePtr->onValuePtr; } if (valuePtr == NULL) { valuePtr = Tcl_NewObj(); } Tcl_IncrRefCount(valuePtr); if (Tcl_ObjSetVar2(interp, mePtr->namePtr, NULL, valuePtr, TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { result = TCL_ERROR; } Tcl_DecrRefCount(valuePtr); } else if ((mePtr->type == RADIO_BUTTON_ENTRY) && (mePtr->namePtr != NULL)) { Tcl_Obj *valuePtr = mePtr->onValuePtr; if (valuePtr == NULL) { valuePtr = Tcl_NewObj(); } Tcl_IncrRefCount(valuePtr); if (Tcl_ObjSetVar2(interp, mePtr->namePtr, NULL, valuePtr, TCL_GLOBAL_ONLY|TCL_LEAVE_ERR_MSG) == NULL) { result = TCL_ERROR; } Tcl_DecrRefCount(valuePtr); } /* * We check numEntries in addition to whether the menu entry has a command * because that goes to zero if the menu gets deleted (e.g., during * command evaluation). */ if ((menuPtr->numEntries != 0) && (result == TCL_OK) && (mePtr->commandPtr != NULL)) { Tcl_Obj *commandPtr = mePtr->commandPtr; Tcl_IncrRefCount(commandPtr); result = Tcl_EvalObjEx(interp, commandPtr, TCL_EVAL_GLOBAL); Tcl_DecrRefCount(commandPtr); } Tcl_Release((ClientData) mePtr); done: return result; } /* *---------------------------------------------------------------------- * * DestroyMenuInstance -- * * This function is invoked by TkDestroyMenu to clean up the internal * structure of a menu at a safe time (when no-one is using it anymore). * Only takes care of one instance of the menu. * * Results: * None. * * Side effects: * Everything associated with the menu is freed up. * *---------------------------------------------------------------------- */ static void DestroyMenuInstance( TkMenu *menuPtr) /* Info about menu widget. */ { int i; TkMenu *menuInstancePtr; TkMenuEntry *cascadePtr, *nextCascadePtr; Tcl_Obj *newObjv[2]; TkMenu *parentMasterMenuPtr; TkMenuEntry *parentMasterEntryPtr; /* * If the menu has any cascade menu entries pointing to it, the cascade * entries need to be told that the menu is going away. We need to clear * the menu ptr field in the menu reference at this point in the code so * that everything else can forget about this menu properly. We also need * to reset -menu field of all entries that are not master menus back to * this entry name if this is a master menu pointed to by another master * menu. If there is a clone menu that points to this menu, then this menu * is itself a clone, so when this menu goes away, the -menu field of the * pointing entry must be set back to this menu's master menu name so that * later if another menu is created the cascade hierarchy can be * maintained. */ TkpDestroyMenu(menuPtr); if (menuPtr->menuRefPtr == NULL) { return; } cascadePtr = menuPtr->menuRefPtr->parentEntryPtr; menuPtr->menuRefPtr->menuPtr = NULL; if (TkFreeMenuReferences(menuPtr->menuRefPtr)) { menuPtr->menuRefPtr = NULL; } for (; cascadePtr != NULL; cascadePtr = nextCascadePtr) { nextCascadePtr = cascadePtr->nextCascadePtr; if (menuPtr->masterMenuPtr != menuPtr) { Tcl_Obj *menuNamePtr = Tcl_NewStringObj("-menu", -1); parentMasterMenuPtr = cascadePtr->menuPtr->masterMenuPtr; parentMasterEntryPtr = parentMasterMenuPtr->entries[cascadePtr->index]; newObjv[0] = menuNamePtr; newObjv[1] = parentMasterEntryPtr->namePtr; /* * It is possible that the menu info is out of sync, and these * things point to NULL, so verify existence [Bug: 3402] */ if (newObjv[0] && newObjv[1]) { Tcl_IncrRefCount(newObjv[0]); Tcl_IncrRefCount(newObjv[1]); ConfigureMenuEntry(cascadePtr, 2, newObjv); Tcl_DecrRefCount(newObjv[0]); Tcl_DecrRefCount(newObjv[1]); } } else { ConfigureMenuEntry(cascadePtr, 0, NULL); } } if (menuPtr->masterMenuPtr != menuPtr) { for (menuInstancePtr = menuPtr->masterMenuPtr; menuInstancePtr != NULL; menuInstancePtr = menuInstancePtr->nextInstancePtr) { if (menuInstancePtr->nextInstancePtr == menuPtr) { menuInstancePtr->nextInstancePtr = menuInstancePtr->nextInstancePtr->nextInstancePtr; break; } } } else if (menuPtr->nextInstancePtr != NULL) { Tcl_Panic("Attempting to delete master menu when there are still clones."); } /* * Free up all the stuff that requires special handling, then let * Tk_FreeConfigOptions handle all the standard option-related stuff. */ for (i = menuPtr->numEntries; --i >= 0; ) { /* * As each menu entry is deleted from the end of the array of entries, * decrement menuPtr->numEntries. Otherwise, the act of deleting menu * entry i will dereference freed memory attempting to queue a redraw * for menu entries (i+1)...numEntries. */ DestroyMenuEntry((char *) menuPtr->entries[i]); menuPtr->numEntries = i; } if (menuPtr->entries != NULL) { ckfree((char *) menuPtr->entries); } TkMenuFreeDrawOptions(menuPtr); Tk_FreeConfigOptions((char *) menuPtr, menuPtr->optionTablesPtr->menuOptionTable, menuPtr->tkwin); if (menuPtr->tkwin != NULL) { Tk_Window tkwin = menuPtr->tkwin; menuPtr->tkwin = NULL; Tk_DestroyWindow(tkwin); } } /* *---------------------------------------------------------------------- * * TkDestroyMenu -- * * This function is invoked by Tcl_EventuallyFree or Tcl_Release to clean * up the internal structure of a menu at a safe time (when no-one is * using it anymore). If called on a master instance, destroys all of the * slave instances. If called on a non-master instance, just destroys * that instance. * * Results: * None. * * Side effects: * Everything associated with the menu is freed up. * *---------------------------------------------------------------------- */ void TkDestroyMenu( TkMenu *menuPtr) /* Info about menu widget. */ { TkMenu *menuInstancePtr; TkMenuTopLevelList *topLevelListPtr, *nextTopLevelPtr; if (menuPtr->menuFlags & MENU_DELETION_PENDING) { return; } Tcl_Preserve(menuPtr); /* * Now destroy all non-tearoff instances of this menu if this is a parent * menu. Is this loop safe enough? Are there going to be destroy bindings * on child menus which kill the parent? If not, we have to do a slightly * more complex scheme. */ menuPtr->menuFlags |= MENU_DELETION_PENDING; if (menuPtr->menuRefPtr != NULL) { /* * If any toplevel widgets have this menu as their menubar, the * geometry of the window may have to be recalculated. */ topLevelListPtr = menuPtr->menuRefPtr->topLevelListPtr; while (topLevelListPtr != NULL) { nextTopLevelPtr = topLevelListPtr->nextPtr; TkpSetWindowMenuBar(topLevelListPtr->tkwin, NULL); topLevelListPtr = nextTopLevelPtr; } } if (menuPtr->masterMenuPtr == menuPtr) { while (menuPtr->nextInstancePtr != NULL) { menuInstancePtr = menuPtr->nextInstancePtr; menuPtr->nextInstancePtr = menuInstancePtr->nextInstancePtr; if (menuInstancePtr->tkwin != NULL) { Tk_Window tkwin = menuInstancePtr->tkwin; /* * Note: it may be desirable to NULL out the tkwin field of * menuInstancePtr here: * menuInstancePtr->tkwin = NULL; */ Tk_DestroyWindow(tkwin); } } } DestroyMenuInstance(menuPtr); Tcl_Release(menuPtr); } /* *---------------------------------------------------------------------- * * UnhookCascadeEntry -- * * This entry is removed from the list of entries that point to the * cascade menu. This is done in preparation for changing the menu that * this entry points to. * * At the end of this function, the menu entry no longer contains a * reference to a 'TkMenuReferences' structure, and therefore no such * structure contains a reference to this menu entry either. * * Results: * None * * Side effects: * The appropriate lists are modified. * *---------------------------------------------------------------------- */ static void UnhookCascadeEntry( TkMenuEntry *mePtr) /* The cascade entry we are removing from the * cascade list. */ { TkMenuEntry *cascadeEntryPtr; TkMenuEntry *prevCascadePtr; TkMenuReferences *menuRefPtr; menuRefPtr = mePtr->childMenuRefPtr; if (menuRefPtr == NULL) { return; } cascadeEntryPtr = menuRefPtr->parentEntryPtr; if (cascadeEntryPtr == NULL) { TkFreeMenuReferences(menuRefPtr); mePtr->childMenuRefPtr = NULL; return; } /* * Singularly linked list deletion. The two special cases are 1. one * element; 2. The first element is the one we want. */ if (cascadeEntryPtr == mePtr) { if (cascadeEntryPtr->nextCascadePtr == NULL) { /* * This is the last menu entry which points to this menu, so we * need to clear out the list pointer in the cascade itself. */ menuRefPtr->parentEntryPtr = NULL; /* * The original field is set to zero below, after it is freed. */ TkFreeMenuReferences(menuRefPtr); } else { menuRefPtr->parentEntryPtr = cascadeEntryPtr->nextCascadePtr; } mePtr->nextCascadePtr = NULL; } else { for (prevCascadePtr = cascadeEntryPtr, cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr; cascadeEntryPtr != NULL; prevCascadePtr = cascadeEntryPtr, cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) { if (cascadeEntryPtr == mePtr){ prevCascadePtr->nextCascadePtr = cascadeEntryPtr->nextCascadePtr; cascadeEntryPtr->nextCascadePtr = NULL; break; } } mePtr->nextCascadePtr = NULL; } mePtr->childMenuRefPtr = NULL; } /* *---------------------------------------------------------------------- * * DestroyMenuEntry -- * * This function is invoked by Tcl_EventuallyFree or Tcl_Release to clean * up the internal structure of a menu entry at a safe time (when no-one * is using it anymore). * * Results: * None. * * Side effects: * Everything associated with the menu entry is freed. * *---------------------------------------------------------------------- */ static void DestroyMenuEntry( char *memPtr) /* Pointer to entry to be freed. */ { register TkMenuEntry *mePtr = (TkMenuEntry *) memPtr; TkMenu *menuPtr = mePtr->menuPtr; if (menuPtr->postedCascade == mePtr) { /* * Ignore errors while unposting the menu, since it's possible that * the menu has already been deleted and the unpost will generate an * error. */ TkPostSubmenu(menuPtr->interp, menuPtr, NULL); } /* * Free up all the stuff that requires special handling, then let * Tk_FreeConfigOptions handle all the standard option-related stuff. */ if (mePtr->type == CASCADE_ENTRY) { if (menuPtr->masterMenuPtr != menuPtr) { TkMenu *destroyThis = NULL; /* * The menu as a whole is a clone. We must delete the clone of the * cascaded menu for the particular entry we are destroying. */ TkMenuReferences *menuRefPtr = mePtr->childMenuRefPtr; if (menuRefPtr != NULL) { destroyThis = menuRefPtr->menuPtr; /* * But only if it is a clone. What can happen is that we are * in the middle of deleting a menu and this menu pointer has * already been reset to point to the original menu. In that * case we have nothing special to do. */ if ((destroyThis != NULL) && (destroyThis->masterMenuPtr == destroyThis)) { destroyThis = NULL; } } UnhookCascadeEntry(mePtr); if (menuRefPtr != NULL) { if (menuRefPtr->menuPtr == destroyThis) { menuRefPtr->menuPtr = NULL; } if (destroyThis != NULL) { TkDestroyMenu(destroyThis); } } } else { UnhookCascadeEntry(mePtr); } } if (mePtr->image != NULL) { Tk_FreeImage(mePtr->image); } if (mePtr->selectImage != NULL) { Tk_FreeImage(mePtr->selectImage); } if (((mePtr->type == CHECK_BUTTON_ENTRY) || (mePtr->type == RADIO_BUTTON_ENTRY)) && (mePtr->namePtr != NULL)) { char *varName = Tcl_GetString(mePtr->namePtr); Tcl_UntraceVar(menuPtr->interp, varName, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, MenuVarProc, (ClientData) mePtr); } TkpDestroyMenuEntry(mePtr); TkMenuEntryFreeDrawOptions(mePtr); Tk_FreeConfigOptions((char *) mePtr, mePtr->optionTable, menuPtr->tkwin); ckfree((char *) mePtr); } /* *--------------------------------------------------------------------------- * * MenuWorldChanged -- * * This function is called when the world has changed in some way (such * as the fonts in the system changing) and the widget needs to recompute * all its graphics contexts and determine its new geometry. * * Results: * None. * * Side effects: * Menu will be relayed out and redisplayed. * *--------------------------------------------------------------------------- */ static void MenuWorldChanged( ClientData instanceData) /* Information about widget. */ { TkMenu *menuPtr = (TkMenu *) instanceData; int i; TkMenuConfigureDrawOptions(menuPtr); for (i = 0; i < menuPtr->numEntries; i++) { TkMenuConfigureEntryDrawOptions(menuPtr->entries[i], menuPtr->entries[i]->index); TkpConfigureMenuEntry(menuPtr->entries[i]); } TkEventuallyRecomputeMenu(menuPtr); } /* *---------------------------------------------------------------------- * * ConfigureMenu -- * * This function is called to process an argv/argc list, plus the Tk * option database, in order to configure (or reconfigure) a menu widget. * * Results: * The return value is a standard Tcl result. If TCL_ERROR is returned, * then the interp's result contains an error message. * * Side effects: * Configuration information, such as colors, font, etc. get set for * menuPtr; old resources get freed, if there were any. * *---------------------------------------------------------------------- */ static int ConfigureMenu( Tcl_Interp *interp, /* Used for error reporting. */ register TkMenu *menuPtr, /* Information about widget; may or may not * already have values for some fields. */ int objc, /* Number of valid entries in argv. */ Tcl_Obj *CONST objv[]) /* Arguments. */ { int i; TkMenu *menuListPtr, *cleanupPtr; int result; for (menuListPtr = menuPtr->masterMenuPtr; menuListPtr != NULL; menuListPtr = menuListPtr->nextInstancePtr) { menuListPtr->errorStructPtr = (Tk_SavedOptions *) ckalloc(sizeof(Tk_SavedOptions)); result = Tk_SetOptions(interp, (char *) menuListPtr, menuListPtr->optionTablesPtr->menuOptionTable, objc, objv, menuListPtr->tkwin, menuListPtr->errorStructPtr, NULL); if (result != TCL_OK) { for (cleanupPtr = menuPtr->masterMenuPtr; cleanupPtr != menuListPtr; cleanupPtr = cleanupPtr->nextInstancePtr) { Tk_RestoreSavedOptions(cleanupPtr->errorStructPtr); ckfree((char *) cleanupPtr->errorStructPtr); cleanupPtr->errorStructPtr = NULL; } if (menuListPtr->errorStructPtr != NULL) { Tk_RestoreSavedOptions(menuListPtr->errorStructPtr); ckfree((char *) menuListPtr->errorStructPtr); menuListPtr->errorStructPtr = NULL; } return TCL_ERROR; } /* * When a menu is created, the type is in all of the arguments to the * menu command. Let Tk_ConfigureWidget take care of parsing them, and * then set the type after we can look at the type string. Once set, a * menu's type cannot be changed */ if (menuListPtr->menuType == UNKNOWN_TYPE) { Tcl_GetIndexFromObj(NULL, menuListPtr->menuTypePtr, menuTypeStrings, NULL, 0, &menuListPtr->menuType); /* * Configure the new window to be either a pop-up menu or a * tear-off menu. We don't do this for menubars since they are not * toplevel windows. Also, since this gets called before CloneMenu * has a chance to set the menuType field, we have to look at the * menuTypeName field to tell that this is a menu bar. */ if (menuListPtr->menuType == MASTER_MENU) { TkpMakeMenuWindow(menuListPtr->tkwin, 1); } else if (menuListPtr->menuType == TEAROFF_MENU) { TkpMakeMenuWindow(menuListPtr->tkwin, 0); } } /* * Depending on the -tearOff option, make sure that there is or isn't * an initial tear-off entry at the beginning of the menu. */ if (menuListPtr->tearoff) { if ((menuListPtr->numEntries == 0) || (menuListPtr->entries[0]->type != TEAROFF_ENTRY)) { if (MenuNewEntry(menuListPtr, 0, TEAROFF_ENTRY) == NULL) { for (cleanupPtr = menuPtr->masterMenuPtr; cleanupPtr != menuListPtr; cleanupPtr = cleanupPtr->nextInstancePtr) { Tk_RestoreSavedOptions(cleanupPtr->errorStructPtr); ckfree((char *) cleanupPtr->errorStructPtr); cleanupPtr->errorStructPtr = NULL; } if (menuListPtr->errorStructPtr != NULL) { Tk_RestoreSavedOptions(menuListPtr->errorStructPtr); ckfree((char *) menuListPtr->errorStructPtr); menuListPtr->errorStructPtr = NULL; } return TCL_ERROR; } } } else if ((menuListPtr->numEntries > 0) && (menuListPtr->entries[0]->type == TEAROFF_ENTRY)) { int i; Tcl_EventuallyFree((ClientData) menuListPtr->entries[0], DestroyMenuEntry); for (i = 0; i < menuListPtr->numEntries - 1; i++) { menuListPtr->entries[i] = menuListPtr->entries[i + 1]; menuListPtr->entries[i]->index = i; } menuListPtr->numEntries--; if (menuListPtr->numEntries == 0) { ckfree((char *) menuListPtr->entries); menuListPtr->entries = NULL; } } TkMenuConfigureDrawOptions(menuListPtr); /* * After reconfiguring a menu, we need to reconfigure all of the * entries in the menu, since some of the things in the children (such * as graphics contexts) may have to change to reflect changes in the * parent. */ for (i = 0; i < menuListPtr->numEntries; i++) { TkMenuEntry *mePtr; mePtr = menuListPtr->entries[i]; ConfigureMenuEntry(mePtr, 0, NULL); } TkEventuallyRecomputeMenu(menuListPtr); } for (cleanupPtr = menuPtr->masterMenuPtr; cleanupPtr != NULL; cleanupPtr = cleanupPtr->nextInstancePtr) { Tk_FreeSavedOptions(cleanupPtr->errorStructPtr); ckfree((char *) cleanupPtr->errorStructPtr); cleanupPtr->errorStructPtr = NULL; } return TCL_OK; } /* *---------------------------------------------------------------------- * * PostProcessEntry -- * * This is called by ConfigureMenuEntry to do all of the configuration * after Tk_SetOptions is called. This is separate so that error handling * is easier. * * Results: * The return value is a standard Tcl result. If TCL_ERROR is returned, * then the interp's result contains an error message. * * Side effects: * Configuration information such as label and accelerator get set for * mePtr; old resources get freed, if there were any. * *---------------------------------------------------------------------- */ static int PostProcessEntry( TkMenuEntry *mePtr) /* The entry we are configuring. */ { TkMenu *menuPtr = mePtr->menuPtr; int index = mePtr->index; char *name; Tk_Image image; /* * The code below handles special configuration stuff not taken care of by * Tk_ConfigureWidget, such as special processing for defaults, sizing * strings, graphics contexts, etc. */ if (mePtr->labelPtr == NULL) { mePtr->labelLength = 0; } else { Tcl_GetStringFromObj(mePtr->labelPtr, &mePtr->labelLength); } if (mePtr->accelPtr == NULL) { mePtr->accelLength = 0; } else { Tcl_GetStringFromObj(mePtr->accelPtr, &mePtr->accelLength); } /* * If this is a cascade entry, the platform-specific data of the child * menu has to be updated. Also, the links that point to parents and * cascades have to be updated. */ if ((mePtr->type == CASCADE_ENTRY) && (mePtr->namePtr != NULL)) { TkMenuEntry *cascadeEntryPtr; int alreadyThere; TkMenuReferences *menuRefPtr; char *oldHashKey = NULL; /* Initialization only needed to * prevent compiler warning. */ /* * This is a cascade entry. If the menu that the cascade entry is * pointing to has changed, we need to remove this entry from the list * of entries pointing to the old menu, and add a cascade reference to * the list of entries pointing to the new menu. * * BUG: We are not recloning for special case #3 yet. */ name = Tcl_GetString(mePtr->namePtr); if (mePtr->childMenuRefPtr != NULL) { oldHashKey = Tcl_GetHashKey(TkGetMenuHashTable(menuPtr->interp), mePtr->childMenuRefPtr->hashEntryPtr); if (strcmp(oldHashKey, name) != 0) { UnhookCascadeEntry(mePtr); } } if ((mePtr->childMenuRefPtr == NULL) || (strcmp(oldHashKey, name) != 0)) { menuRefPtr = TkCreateMenuReferences(menuPtr->interp, name); mePtr->childMenuRefPtr = menuRefPtr; if (menuRefPtr->parentEntryPtr == NULL) { menuRefPtr->parentEntryPtr = mePtr; } else { alreadyThere = 0; for (cascadeEntryPtr = menuRefPtr->parentEntryPtr; cascadeEntryPtr != NULL; cascadeEntryPtr = cascadeEntryPtr->nextCascadePtr) { if (cascadeEntryPtr == mePtr) { alreadyThere = 1; break; } } /* * Put the item at the front of the list. */ if (!alreadyThere) { mePtr->nextCascadePtr = menuRefPtr->parentEntryPtr; menuRefPtr->parentEntryPtr = mePtr; } } } } if (TkMenuConfigureEntryDrawOptions(mePtr, index) != TCL_OK) { return TCL_ERROR; } if (TkpConfigureMenuEntry(mePtr) != TCL_OK) { return TCL_ERROR; } /* * Get the images for the entry, if there are any. Allocate the new images * before freeing the old ones, so that the reference counts don't go to * zero and cause image data to be discarded. */ if (mePtr->imagePtr != NULL) { char *imageString = Tcl_GetString(mePtr->imagePtr); image = Tk_GetImage(menuPtr->interp, menuPtr->tkwin, imageString, TkMenuImageProc, (ClientData) mePtr); if (image == NULL) { return TCL_ERROR; } } else { image = NULL; } if (mePtr->image != NULL) { Tk_FreeImage(mePtr->image); } mePtr->image = image; if (mePtr->selectImagePtr != NULL) { char *selectImageString = Tcl_GetString(mePtr->selectImagePtr); image = Tk_GetImage(menuPtr->interp, menuPtr->tkwin, selectImageString, TkMenuSelectImageProc, (ClientData) mePtr); if (image == NULL) { return TCL_ERROR; } } else { image = NULL; } if (mePtr->selectImage != NULL) { Tk_FreeImage(mePtr->selectImage); } mePtr->selectImage = image; if ((mePtr->type == CHECK_BUTTON_ENTRY) || (mePtr->type == RADIO_BUTTON_ENTRY)) { Tcl_Obj *valuePtr; char *name; if (mePtr->namePtr == NULL) { if (mePtr->labelPtr == NULL) { mePtr->namePtr = NULL; } else { mePtr->namePtr = Tcl_DuplicateObj(mePtr->labelPtr); Tcl_IncrRefCount(mePtr->namePtr); } } if (mePtr->onValuePtr == NULL) { if (mePtr->labelPtr == NULL) { mePtr->onValuePtr = NULL; } else { mePtr->onValuePtr = Tcl_DuplicateObj(mePtr->labelPtr); Tcl_IncrRefCount(mePtr->onValuePtr); } } /* * Select the entry if the associated variable has the appropriate * value, initialize the variable if it doesn't exist, then set a * trace on the variable to monitor future changes to its value. */ if (mePtr->namePtr != NULL) { valuePtr = Tcl_ObjGetVar2(menuPtr->interp, mePtr->namePtr, NULL, TCL_GLOBAL_ONLY); } else { valuePtr = NULL; } mePtr->entryFlags &= ~ENTRY_SELECTED; if (valuePtr != NULL) { if (mePtr->onValuePtr != NULL) { char *value = Tcl_GetString(valuePtr); char *onValue = Tcl_GetString(mePtr->onValuePtr); if (strcmp(value, onValue) == 0) { mePtr->entryFlags |= ENTRY_SELECTED; } } } else { if (mePtr->namePtr != NULL) { Tcl_ObjSetVar2(menuPtr->interp, mePtr->namePtr, NULL, (mePtr->type == CHECK_BUTTON_ENTRY) ? mePtr->offValuePtr : Tcl_NewObj(), TCL_GLOBAL_ONLY); } } if (mePtr->namePtr != NULL) { name = Tcl_GetString(mePtr->namePtr); Tcl_TraceVar(menuPtr->interp, name, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, MenuVarProc, (ClientData) mePtr); } } return TCL_OK; } /* *---------------------------------------------------------------------- * * ConfigureMenuEntry -- * * This function is called to process an argv/argc list in order to * configure (or reconfigure) one entry in a menu. * * Results: * The return value is a standard Tcl result. If TCL_ERROR is returned, * then the interp's result contains an error message. * * Side effects: * Configuration information such as label and accelerator get set for * mePtr; old resources get freed, if there were any. * *---------------------------------------------------------------------- */ static int ConfigureMenuEntry( register TkMenuEntry *mePtr,/* Information about menu entry; may or may * not already have values for some fields. */ int objc, /* Number of valid entries in argv. */ Tcl_Obj *CONST objv[]) /* Arguments. */ { TkMenu *menuPtr = mePtr->menuPtr; Tk_SavedOptions errorStruct; int result; /* * If this entry is a check button or radio button, then remove its old * trace function. */ if ((mePtr->namePtr != NULL) && ((mePtr->type == CHECK_BUTTON_ENTRY) || (mePtr->type == RADIO_BUTTON_ENTRY))) { char *name = Tcl_GetString(mePtr->namePtr); Tcl_UntraceVar(menuPtr->interp, name, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, MenuVarProc, (ClientData) mePtr); } result = TCL_OK; if (menuPtr->tkwin != NULL) { if (Tk_SetOptions(menuPtr->interp, (char *) mePtr, mePtr->optionTable, objc, objv, menuPtr->tkwin, &errorStruct, NULL) != TCL_OK) { return TCL_ERROR; } result = PostProcessEntry(mePtr); if (result != TCL_OK) { Tk_RestoreSavedOptions(&errorStruct); PostProcessEntry(mePtr); } Tk_FreeSavedOptions(&errorStruct); } TkEventuallyRecomputeMenu(menuPtr); return result; } /* *---------------------------------------------------------------------- * * ConfigureMenuCloneEntries -- * * Calls ConfigureMenuEntry for each menu in the clone chain. * * Results: * The return value is a standard Tcl result. If TCL_ERROR is returned, * then the interp's result contains an error message. * * Side effects: * Configuration information such as label and accelerator get set for * mePtr; old resources get freed, if there were any. * *---------------------------------------------------------------------- */ static int ConfigureMenuCloneEntries( Tcl_Interp *interp, /* Used for error reporting. */ TkMenu *menuPtr, /* Information about whole menu. */ int index, /* Index of mePtr within menuPtr's entries. */ int objc, /* Number of valid entries in argv. */ Tcl_Obj *CONST objv[]) /* Arguments. */ { TkMenuEntry *mePtr; TkMenu *menuListPtr; int cascadeEntryChanged = 0; TkMenuReferences *oldCascadeMenuRefPtr, *cascadeMenuRefPtr = NULL; Tcl_Obj *oldCascadePtr = NULL; char *newCascadeName; /* * Cascades are kind of tricky here. This is special case #3 in the * comment at the top of this file. Basically, if a menu is the master * menu of a clone chain, and has an entry with a cascade menu, the clones * of the menu will point to clones of the cascade menu. We have to * destroy the clones of the cascades, clone the new cascade menu, and * configure the entry to point to the new clone. */ mePtr = menuPtr->masterMenuPtr->entries[index]; if (mePtr->type == CASCADE_ENTRY) { oldCascadePtr = mePtr->namePtr; if (oldCascadePtr != NULL) { Tcl_IncrRefCount(oldCascadePtr); } } if (ConfigureMenuEntry(mePtr, objc, objv) != TCL_OK) { return TCL_ERROR; } if (mePtr->type == CASCADE_ENTRY) { char *oldCascadeName; if (mePtr->namePtr != NULL) { newCascadeName = Tcl_GetString(mePtr->namePtr); } else { newCascadeName = NULL; } if ((oldCascadePtr == NULL) && (mePtr->namePtr == NULL)) { cascadeEntryChanged = 0; } else if (((oldCascadePtr == NULL) && (mePtr->namePtr != NULL)) || ((oldCascadePtr != NULL) && (mePtr->namePtr == NULL))) { cascadeEntryChanged = 1; } else { oldCascadeName = Tcl_GetString(oldCascadePtr); cascadeEntryChanged = (strcmp(oldCascadeName, newCascadeName) != 0); } if (oldCascadePtr != NULL) { Tcl_DecrRefCount(oldCascadePtr); } } if (cascadeEntryChanged) { if (mePtr->namePtr != NULL) { newCascadeName = Tcl_GetString(mePtr->namePtr); cascadeMenuRefPtr = TkFindMenuReferences(menuPtr->interp, newCascadeName); } } for (menuListPtr = menuPtr->masterMenuPtr->nextInstancePtr; menuListPtr != NULL; menuListPtr = menuListPtr->nextInstancePtr) { mePtr = menuListPtr->entries[index]; if (cascadeEntryChanged && (mePtr->namePtr != NULL)) { oldCascadeMenuRefPtr = TkFindMenuReferencesObj(menuPtr->interp, mePtr->namePtr); if ((oldCascadeMenuRefPtr != NULL) && (oldCascadeMenuRefPtr->menuPtr != NULL)) { RecursivelyDeleteMenu(oldCascadeMenuRefPtr->menuPtr); } } if (ConfigureMenuEntry(mePtr, objc, objv) != TCL_OK) { return TCL_ERROR; } if (cascadeEntryChanged && (mePtr->namePtr != NULL)) { if (cascadeMenuRefPtr->menuPtr != NULL) { Tcl_Obj *newObjv[2]; Tcl_Obj *newCloneNamePtr; Tcl_Obj *pathNamePtr = Tcl_NewStringObj( Tk_PathName(menuListPtr->tkwin), -1); Tcl_Obj *normalPtr = Tcl_NewStringObj("normal", -1); Tcl_Obj *menuObjPtr = Tcl_NewStringObj("-menu", -1); Tcl_IncrRefCount(pathNamePtr); newCloneNamePtr = TkNewMenuName(menuPtr->interp, pathNamePtr, cascadeMenuRefPtr->menuPtr); Tcl_IncrRefCount(newCloneNamePtr); Tcl_IncrRefCount(normalPtr); CloneMenu(cascadeMenuRefPtr->menuPtr, newCloneNamePtr, normalPtr); newObjv[0] = menuObjPtr; newObjv[1] = newCloneNamePtr; Tcl_IncrRefCount(menuObjPtr); ConfigureMenuEntry(mePtr, 2, newObjv); Tcl_DecrRefCount(newCloneNamePtr); Tcl_DecrRefCount(pathNamePtr); Tcl_DecrRefCount(normalPtr); Tcl_DecrRefCount(menuObjPtr); } } } return TCL_OK; } /* *-------------------------------------------------------------- * * TkGetMenuIndex -- * * Parse a textual index into a menu and return the numerical index of * the indicated entry. * * Results: * A standard Tcl result. If all went well, then *indexPtr is filled in * with the entry index corresponding to string (ranges from -1 to the * number of entries in the menu minus one). Otherwise an error message * is left in the interp's result. * * Side effects: * None. * *-------------------------------------------------------------- */ int TkGetMenuIndex( Tcl_Interp *interp, /* For error messages. */ TkMenu *menuPtr, /* Menu for which the index is being * specified. */ Tcl_Obj *objPtr, /* Specification of an entry in menu. See * manual entry for valid .*/ int lastOK, /* Non-zero means its OK to return index just * *after* last entry. */ int *indexPtr) /* Where to store converted index. */ { int i; char *string = Tcl_GetString(objPtr); if ((string[0] == 'a') && (strcmp(string, "active") == 0)) { *indexPtr = menuPtr->active; goto success; } if (((string[0] == 'l') && (strcmp(string, "last") == 0)) || ((string[0] == 'e') && (strcmp(string, "end") == 0))) { *indexPtr = menuPtr->numEntries - ((lastOK) ? 0 : 1); goto success; } if ((string[0] == 'n') && (strcmp(string, "none") == 0)) { *indexPtr = -1; goto success; } if (string[0] == '@') { if (GetIndexFromCoords(interp, menuPtr, string, indexPtr) == TCL_OK) { goto success; } } if (isdigit(UCHAR(string[0]))) { if (Tcl_GetInt(interp, string, &i) == TCL_OK) { if (i >= menuPtr->numEntries) { if (lastOK) { i = menuPtr->numEntries; } else { i = menuPtr->numEntries-1; } } else if (i < 0) { i = -1; } *indexPtr = i; goto success; } Tcl_SetResult(interp, NULL, TCL_STATIC); } for (i = 0; i < menuPtr->numEntries; i++) { Tcl_Obj *labelPtr = menuPtr->entries[i]->labelPtr; char *label = (labelPtr == NULL) ? NULL : Tcl_GetString(labelPtr); if ((label != NULL) && (Tcl_StringMatch(label, string))) { *indexPtr = i; goto success; } } Tcl_AppendResult(interp, "bad menu entry index \"", string, "\"", NULL); return TCL_ERROR; success: return TCL_OK; } /* *---------------------------------------------------------------------- * * MenuCmdDeletedProc -- * * This function is invoked when a widget command is deleted. If the * widget isn't already in the process of being destroyed, this command * destroys it. * * Results: * None. * * Side effects: * The widget is destroyed. * *---------------------------------------------------------------------- */ static void MenuCmdDeletedProc( ClientData clientData) /* Pointer to widget record for widget. */ { TkMenu *menuPtr = (TkMenu *) clientData; Tk_Window tkwin = menuPtr->tkwin; /* * This function could be invoked either because the window was destroyed * and the command was then deleted (in which case tkwin is NULL) or * because the command was deleted, and then this function destroys the * widget. */ if (tkwin != NULL) { /* * Note: it may be desirable to NULL out the tkwin field of menuPtr * here: * menuPtr->tkwin = NULL; */ Tk_DestroyWindow(tkwin); } } /* *---------------------------------------------------------------------- * * MenuNewEntry -- * * This function allocates and initializes a new menu entry. * * Results: * The return value is a pointer to a new menu entry structure, which has * been malloc-ed, initialized, and entered into the entry array for the * menu. * * Side effects: * Storage gets allocated. * *---------------------------------------------------------------------- */ static TkMenuEntry * MenuNewEntry( TkMenu *menuPtr, /* Menu that will hold the new entry. */ int index, /* Where in the menu the new entry is to * go. */ int type) /* The type of the new entry. */ { TkMenuEntry *mePtr; TkMenuEntry **newEntries; int i; /* * Create a new array of entries with an empty slot for the new entry. */ newEntries = (TkMenuEntry **) ckalloc((unsigned) ((menuPtr->numEntries+1)*sizeof(TkMenuEntry *))); for (i = 0; i < index; i++) { newEntries[i] = menuPtr->entries[i]; } for (; i < menuPtr->numEntries; i++) { newEntries[i+1] = menuPtr->entries[i]; newEntries[i+1]->index = i + 1; } if (menuPtr->numEntries != 0) { ckfree((char *) menuPtr->entries); } menuPtr->entries = newEntries; menuPtr->numEntries++; mePtr = (TkMenuEntry *) ckalloc(sizeof(TkMenuEntry)); menuPtr->entries[index] = mePtr; mePtr->type = type; mePtr->optionTable = menuPtr->optionTablesPtr->entryOptionTables[type]; mePtr->menuPtr = menuPtr; mePtr->labelPtr = NULL; mePtr->labelLength = 0; mePtr->underline = -1; mePtr->bitmapPtr = NULL; mePtr->imagePtr = NULL; mePtr->image = NULL; mePtr->selectImagePtr = NULL; mePtr->selectImage = NULL; mePtr->accelPtr = NULL; mePtr->accelLength = 0; mePtr->state = ENTRY_DISABLED; mePtr->borderPtr = NULL; mePtr->fgPtr = NULL; mePtr->activeBorderPtr = NULL; mePtr->activeFgPtr = NULL; mePtr->fontPtr = NULL; mePtr->indicatorOn = 0; mePtr->indicatorFgPtr = NULL; mePtr->columnBreak = 0; mePtr->hideMargin = 0; mePtr->commandPtr = NULL; mePtr->namePtr = NULL; mePtr->childMenuRefPtr = NULL; mePtr->onValuePtr = NULL; mePtr->offValuePtr = NULL; mePtr->entryFlags = 0; mePtr->index = index; mePtr->nextCascadePtr = NULL; if (Tk_InitOptions(menuPtr->interp, (char *) mePtr, mePtr->optionTable, menuPtr->tkwin) != TCL_OK) { ckfree((char *) mePtr); return NULL; } TkMenuInitializeEntryDrawingFields(mePtr); if (TkpMenuNewEntry(mePtr) != TCL_OK) { Tk_FreeConfigOptions((char *) mePtr, mePtr->optionTable, menuPtr->tkwin); ckfree((char *) mePtr); return NULL; } return mePtr; } /* *---------------------------------------------------------------------- * * MenuAddOrInsert -- * * This function does all of the work of the "add" and "insert" widget * commands, allowing the code for these to be shared. * * Results: * A standard Tcl return value. * * Side effects: * A new menu entry is created in menuPtr. * *---------------------------------------------------------------------- */ static int MenuAddOrInsert( Tcl_Interp *interp, /* Used for error reporting. */ TkMenu *menuPtr, /* Widget in which to create new entry. */ Tcl_Obj *indexPtr, /* Object describing index at which to insert. * NULL means insert at end. */ int objc, /* Number of elements in objv. */ Tcl_Obj *CONST objv[]) /* Arguments to command: first arg is type of * entry, others are config options. */ { int type, index; TkMenuEntry *mePtr; TkMenu *menuListPtr; if (indexPtr != NULL) { if (TkGetMenuIndex(interp, menuPtr, indexPtr, 1, &index) != TCL_OK) { return TCL_ERROR; } } else { index = menuPtr->numEntries; } if (index < 0) { char *indexString = Tcl_GetString(indexPtr); Tcl_AppendResult(interp, "bad index \"", indexString, "\"", NULL); return TCL_ERROR; } if (menuPtr->tearoff && (index == 0)) { index = 1; } /* * Figure out the type of the new entry. */ if (Tcl_GetIndexFromObj(interp, objv[0], menuEntryTypeStrings, "menu entry type", 0, &type) != TCL_OK) { return TCL_ERROR; } /* * Now we have to add an entry for every instance related to this menu. */ for (menuListPtr = menuPtr->masterMenuPtr; menuListPtr != NULL; menuListPtr = menuListPtr->nextInstancePtr) { mePtr = MenuNewEntry(menuListPtr, index, type); if (mePtr == NULL) { return TCL_ERROR; } if (ConfigureMenuEntry(mePtr, objc - 1, objv + 1) != TCL_OK) { TkMenu *errorMenuPtr; int i; for (errorMenuPtr = menuPtr->masterMenuPtr; errorMenuPtr != NULL; errorMenuPtr = errorMenuPtr->nextInstancePtr) { Tcl_EventuallyFree((ClientData) errorMenuPtr->entries[index], DestroyMenuEntry); for (i = index; i < errorMenuPtr->numEntries - 1; i++) { errorMenuPtr->entries[i] = errorMenuPtr->entries[i + 1]; errorMenuPtr->entries[i]->index = i; } errorMenuPtr->numEntries--; if (errorMenuPtr->numEntries == 0) { ckfree((char *) errorMenuPtr->entries); errorMenuPtr->entries = NULL; } if (errorMenuPtr == menuListPtr) { break; } } return TCL_ERROR; } /* * If a menu has cascades, then every instance of the menu has to have * its own parallel cascade structure. So adding an entry to a menu * with clones means that the menu that the entry points to has to be * cloned for every clone the master menu has. This is special case #2 * in the comment at the top of this file. */ if ((menuPtr != menuListPtr) && (type == CASCADE_ENTRY)) { if ((mePtr->namePtr != NULL) && (mePtr->childMenuRefPtr != NULL) && (mePtr->childMenuRefPtr->menuPtr != NULL)) { TkMenu *cascadeMenuPtr = mePtr->childMenuRefPtr->menuPtr->masterMenuPtr; Tcl_Obj *newCascadePtr, *newObjv[2]; Tcl_Obj *menuNamePtr = Tcl_NewStringObj("-menu", -1); Tcl_Obj *windowNamePtr = Tcl_NewStringObj(Tk_PathName(menuListPtr->tkwin), -1); Tcl_Obj *normalPtr = Tcl_NewStringObj("normal", -1); TkMenuReferences *menuRefPtr; Tcl_IncrRefCount(windowNamePtr); newCascadePtr = TkNewMenuName(menuListPtr->interp, windowNamePtr, cascadeMenuPtr); Tcl_IncrRefCount(newCascadePtr); Tcl_IncrRefCount(normalPtr); CloneMenu(cascadeMenuPtr, newCascadePtr, normalPtr); menuRefPtr = TkFindMenuReferencesObj(menuListPtr->interp, newCascadePtr); if (menuRefPtr == NULL) { Tcl_Panic("CloneMenu failed inside of MenuAddOrInsert."); } newObjv[0] = menuNamePtr; newObjv[1] = newCascadePtr; Tcl_IncrRefCount(menuNamePtr); Tcl_IncrRefCount(newCascadePtr); ConfigureMenuEntry(mePtr, 2, newObjv); Tcl_DecrRefCount(newCascadePtr); Tcl_DecrRefCount(menuNamePtr); Tcl_DecrRefCount(windowNamePtr); Tcl_DecrRefCount(normalPtr); } } } return TCL_OK; } /* *-------------------------------------------------------------- * * MenuVarProc -- * * This function is invoked when someone changes the state variable * associated with a radiobutton or checkbutton menu entry. The entry's * selected state is set to match the value of the variable. * * Results: * NULL is always returned. * * Side effects: * The menu entry may become selected or deselected. * *-------------------------------------------------------------- */ static char * MenuVarProc( ClientData clientData, /* Information about menu entry. */ Tcl_Interp *interp, /* Interpreter containing variable. */ CONST char *name1, /* First part of variable's name. */ CONST char *name2, /* Second part of variable's name. */ int flags) /* Describes what just happened. */ { TkMenuEntry *mePtr = (TkMenuEntry *) clientData; TkMenu *menuPtr; CONST char *value; char *name; char *onValue; if (flags & TCL_INTERP_DESTROYED) { /* * Do nothing if the interpreter is going away. */ return NULL; } menuPtr = mePtr->menuPtr; name = Tcl_GetString(mePtr->namePtr); /* * If the variable is being unset, then re-establish the trace. */ if (flags & TCL_TRACE_UNSETS) { mePtr->entryFlags &= ~ENTRY_SELECTED; if (flags & TCL_TRACE_DESTROYED) { Tcl_TraceVar(interp, name, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS, MenuVarProc, clientData); } TkpConfigureMenuEntry(mePtr); TkEventuallyRedrawMenu(menuPtr, NULL); return NULL; } /* * Use the value of the variable to update the selected status of the menu * entry. */ value = Tcl_GetVar(interp, name, TCL_GLOBAL_ONLY); if (value == NULL) { value = ""; } if (mePtr->onValuePtr != NULL) { onValue = Tcl_GetString(mePtr->onValuePtr); if (strcmp(value, onValue) == 0) { if (mePtr->entryFlags & ENTRY_SELECTED) { return NULL; } mePtr->entryFlags |= ENTRY_SELECTED; } else if (mePtr->entryFlags & ENTRY_SELECTED) { mePtr->entryFlags &= ~ENTRY_SELECTED; } else { return NULL; } } else { return NULL; } TkpConfigureMenuEntry(mePtr); TkEventuallyRedrawMenu(menuPtr, mePtr); return NULL; } /* *---------------------------------------------------------------------- * * TkActivateMenuEntry -- * * This function is invoked to make a particular menu entry the active * one, deactivating any other entry that might currently be active. * * Results: * The return value is a standard Tcl result (errors can occur while * posting and unposting submenus). * * Side effects: * Menu entries get redisplayed, and the active entry changes. Submenus * may get posted and unposted. * *---------------------------------------------------------------------- */ int TkActivateMenuEntry( register TkMenu *menuPtr, /* Menu in which to activate. */ int index) /* Index of entry to activate, or -1 to * deactivate all entries. */ { register TkMenuEntry *mePtr; int result = TCL_OK; if (menuPtr->active >= 0) { mePtr = menuPtr->entries[menuPtr->active]; /* * Don't change the state unless it's currently active (state might * already have been changed to disabled). */ if (mePtr->state == ENTRY_ACTIVE) { mePtr->state = ENTRY_NORMAL; } TkEventuallyRedrawMenu(menuPtr, menuPtr->entries[menuPtr->active]); } menuPtr->active = index; if (index >= 0) { mePtr = menuPtr->entries[index]; mePtr->state = ENTRY_ACTIVE; TkEventuallyRedrawMenu(menuPtr, mePtr); } return result; } /* *---------------------------------------------------------------------- * * TkPostCommand -- * * Execute the postcommand for the given menu. * * Results: * The return value is a standard Tcl result (errors can occur while the * postcommands are being processed). * * Side effects: * Since commands can get executed while this routine is being executed, * the entire world can change. * *---------------------------------------------------------------------- */ int TkPostCommand( TkMenu *menuPtr) { int result; /* * If there is a command for the menu, execute it. This may change the * size of the menu, so be sure to recompute the menu's geometry if * needed. */ if (menuPtr->postCommandPtr != NULL) { Tcl_Obj *postCommandPtr = menuPtr->postCommandPtr; Tcl_IncrRefCount(postCommandPtr); result = Tcl_EvalObjEx(menuPtr->interp, postCommandPtr, TCL_EVAL_GLOBAL); Tcl_DecrRefCount(postCommandPtr); if (result != TCL_OK) { return result; } TkRecomputeMenu(menuPtr); } return TCL_OK; } /* *-------------------------------------------------------------- * * CloneMenu -- * * Creates a child copy of the menu. It will be inserted into the menu's * instance chain. All attributes and entry attributes will be * duplicated. * * Results: * A standard Tcl result. * * Side effects: * Allocates storage. After the menu is created, any configuration done * with this menu or any related one will be reflected in all of them. * *-------------------------------------------------------------- */ static int CloneMenu( TkMenu *menuPtr, /* The menu we are going to clone. */ Tcl_Obj *newMenuNamePtr, /* The name to give the new menu. */ Tcl_Obj *newMenuTypePtr) /* What kind of menu is this, a normal menu a * menubar, or a tearoff? */ { int returnResult; int menuType, i; TkMenuReferences *menuRefPtr; Tcl_Obj *menuDupCommandArray[4]; if (newMenuTypePtr == NULL) { menuType = MASTER_MENU; } else { if (Tcl_GetIndexFromObj(menuPtr->interp, newMenuTypePtr, menuTypeStrings, "menu type", 0, &menuType) != TCL_OK) { return TCL_ERROR; } } menuDupCommandArray[0] = Tcl_NewStringObj("tk::MenuDup", -1); menuDupCommandArray[1] = Tcl_NewStringObj(Tk_PathName(menuPtr->tkwin), -1); menuDupCommandArray[2] = newMenuNamePtr; if (newMenuTypePtr == NULL) { menuDupCommandArray[3] = Tcl_NewStringObj("normal", -1); } else { menuDupCommandArray[3] = newMenuTypePtr; } for (i = 0; i < 4; i++) { Tcl_IncrRefCount(menuDupCommandArray[i]); } Tcl_Preserve((ClientData) menuPtr); returnResult = Tcl_EvalObjv(menuPtr->interp, 4, menuDupCommandArray, 0); for (i = 0; i < 4; i++) { Tcl_DecrRefCount(menuDupCommandArray[i]); } /* * Make sure the tcl command actually created the clone. */ if ((returnResult == TCL_OK) && ((menuRefPtr = TkFindMenuReferencesObj(menuPtr->interp, newMenuNamePtr)) != NULL) && (menuPtr->numEntries == menuRefPtr->menuPtr->numEntries)) { TkMenu *newMenuPtr = menuRefPtr->menuPtr; Tcl_Obj *newObjv[3]; int i, numElements; /* * Now put this newly created menu into the parent menu's instance * chain. */ if (menuPtr->nextInstancePtr == NULL) { menuPtr->nextInstancePtr = newMenuPtr; newMenuPtr->masterMenuPtr = menuPtr->masterMenuPtr; } else { TkMenu *masterMenuPtr; masterMenuPtr = menuPtr->masterMenuPtr; newMenuPtr->nextInstancePtr = masterMenuPtr->nextInstancePtr; masterMenuPtr->nextInstancePtr = newMenuPtr; newMenuPtr->masterMenuPtr = masterMenuPtr; } /* * Add the master menu's window to the bind tags for this window after * this window's tag. This is so the user can bind to either this * clone (which may not be easy to do) or the entire menu clone * structure. */ newObjv[0] = Tcl_NewStringObj("bindtags", -1); newObjv[1] = Tcl_NewStringObj(Tk_PathName(newMenuPtr->tkwin), -1); Tcl_IncrRefCount(newObjv[0]); Tcl_IncrRefCount(newObjv[1]); if (Tk_BindtagsObjCmd((ClientData)newMenuPtr->tkwin, newMenuPtr->interp, 2, newObjv) == TCL_OK) { char *windowName; Tcl_Obj *bindingsPtr = Tcl_DuplicateObj(Tcl_GetObjResult(newMenuPtr->interp)); Tcl_Obj *elementPtr; Tcl_IncrRefCount(bindingsPtr); Tcl_ListObjLength(newMenuPtr->interp, bindingsPtr, &numElements); for (i = 0; i < numElements; i++) { Tcl_ListObjIndex(newMenuPtr->interp, bindingsPtr, i, &elementPtr); windowName = Tcl_GetString(elementPtr); if (strcmp(windowName, Tk_PathName(newMenuPtr->tkwin)) == 0) { Tcl_Obj *newElementPtr = Tcl_NewStringObj( Tk_PathName(newMenuPtr->masterMenuPtr->tkwin), -1); /* * The newElementPtr will have its refCount incremented * here, so we don't need to worry about it any more. */ Tcl_ListObjReplace(menuPtr->interp, bindingsPtr, i + 1, 0, 1, &newElementPtr); newObjv[2] = bindingsPtr; Tk_BindtagsObjCmd((ClientData)newMenuPtr->tkwin, menuPtr->interp, 3, newObjv); break; } } Tcl_DecrRefCount(bindingsPtr); } Tcl_DecrRefCount(newObjv[0]); Tcl_DecrRefCount(newObjv[1]); Tcl_ResetResult(menuPtr->interp); /* * Clone all of the cascade menus that this menu points to. */ for (i = 0; i < menuPtr->numEntries; i++) { TkMenuReferences *cascadeRefPtr; TkMenu *oldCascadePtr; if ((menuPtr->entries[i]->type == CASCADE_ENTRY) && (menuPtr->entries[i]->namePtr != NULL)) { cascadeRefPtr = TkFindMenuReferencesObj(menuPtr->interp, menuPtr->entries[i]->namePtr); if ((cascadeRefPtr != NULL) && (cascadeRefPtr->menuPtr)) { Tcl_Obj *windowNamePtr = Tcl_NewStringObj(Tk_PathName(newMenuPtr->tkwin), -1); Tcl_Obj *newCascadePtr; oldCascadePtr = cascadeRefPtr->menuPtr; Tcl_IncrRefCount(windowNamePtr); newCascadePtr = TkNewMenuName(menuPtr->interp, windowNamePtr, oldCascadePtr); Tcl_IncrRefCount(newCascadePtr); CloneMenu(oldCascadePtr, newCascadePtr, NULL); newObjv[0] = Tcl_NewStringObj("-menu", -1); newObjv[1] = newCascadePtr; Tcl_IncrRefCount(newObjv[0]); ConfigureMenuEntry(newMenuPtr->entries[i], 2, newObjv); Tcl_DecrRefCount(newObjv[0]); Tcl_DecrRefCount(newCascadePtr); Tcl_DecrRefCount(windowNamePtr); } } } returnResult = TCL_OK; } else { returnResult = TCL_ERROR; } Tcl_Release((ClientData) menuPtr); return returnResult; } /* *---------------------------------------------------------------------- * * MenuDoXPosition -- * * Given arguments from an option command line, returns the X position. * * Results: * Returns TCL_OK or TCL_Error * * Side effects: * xPosition is set to the X-position of the menu entry. * *---------------------------------------------------------------------- */ static int MenuDoXPosition( Tcl_Interp *interp, TkMenu *menuPtr, Tcl_Obj *objPtr) { int index; TkRecomputeMenu(menuPtr); if (TkGetMenuIndex(interp, menuPtr, objPtr, 0, &index) != TCL_OK) { return TCL_ERROR; } Tcl_ResetResult(interp); if (index < 0) { Tcl_SetObjResult(interp, Tcl_NewIntObj(0)); } else { Tcl_SetObjResult(interp, Tcl_NewIntObj(menuPtr->entries[index]->x)); } return TCL_OK; } /* *---------------------------------------------------------------------- * * MenuDoYPosition -- * * Given arguments from an option command line, returns the Y position. * * Results: * Returns TCL_OK or TCL_Error * * Side effects: * yPosition is set to the Y-position of the menu entry. * *---------------------------------------------------------------------- */ static int MenuDoYPosition( Tcl_Interp *interp, TkMenu *menuPtr, Tcl_Obj *objPtr) { int index; TkRecomputeMenu(menuPtr); if (TkGetMenuIndex(interp, menuPtr, objPtr, 0, &index) != TCL_OK) { goto error; } Tcl_ResetResult(interp); if (index < 0) { Tcl_SetObjResult(interp, Tcl_NewIntObj(0)); } else { Tcl_SetObjResult(interp, Tcl_NewIntObj(menuPtr->entries[index]->y)); } return TCL_OK; error: return TCL_ERROR; } /* *---------------------------------------------------------------------- * * GetIndexFromCoords -- * * Given a string of the form "@int", return the menu item corresponding * to int. * * Results: * If int is a valid number, *indexPtr will be the number of the * menuentry that is the correct height. If int is invaled, *indexPtr * will be unchanged. Returns appropriate Tcl error number. * * Side effects: * If int is invalid, interp's result will set to NULL. * *---------------------------------------------------------------------- */ static int GetIndexFromCoords( Tcl_Interp *interp, /* Interpreter of menu. */ TkMenu *menuPtr, /* The menu we are searching. */ char *string, /* The @string we are parsing. */ int *indexPtr) /* The index of the item that matches. */ { int x, y, i; char *p, *end; TkRecomputeMenu(menuPtr); p = string + 1; y = strtol(p, &end, 0); if (end == p) { goto error; } if (*end == ',') { x = y; p = end + 1; y = strtol(p, &end, 0); if (end == p) { goto error; } } else { Tk_GetPixelsFromObj(interp, menuPtr->tkwin, menuPtr->borderWidthPtr, &x); } for (i = 0; i < menuPtr->numEntries; i++) { if ((x >= menuPtr->entries[i]->x) && (y >= menuPtr->entries[i]->y) && (x < (menuPtr->entries[i]->x + menuPtr->entries[i]->width)) && (y < (menuPtr->entries[i]->y + menuPtr->entries[i]->height))) { break; } } if (i >= menuPtr->numEntries) { /* i = menuPtr->numEntries - 1; */ i = -1; } *indexPtr = i; return TCL_OK; error: Tcl_SetResult(interp, NULL, TCL_STATIC); return TCL_ERROR; } /* *---------------------------------------------------------------------- * * RecursivelyDeleteMenu -- * * Deletes a menu and any cascades underneath it. Used for deleting * instances when a menu is no longer being used as a menubar, for * instance. * * Results: * None. * * Side effects: * Destroys the menu and all cascade menus underneath it. * *---------------------------------------------------------------------- */ static void RecursivelyDeleteMenu( TkMenu *menuPtr) /* The menubar instance we are deleting. */ { int i; TkMenuEntry *mePtr; /* * It is not 100% clear that this preserve/release pair is required, but * we have added them for safety in this very complex code. */ Tcl_Preserve(menuPtr); for (i = 0; i < menuPtr->numEntries; i++) { mePtr = menuPtr->entries[i]; if ((mePtr->type == CASCADE_ENTRY) && (mePtr->childMenuRefPtr != NULL) && (mePtr->childMenuRefPtr->menuPtr != NULL)) { RecursivelyDeleteMenu(mePtr->childMenuRefPtr->menuPtr); } } if (menuPtr->tkwin != NULL) { Tk_DestroyWindow(menuPtr->tkwin); } Tcl_Release(menuPtr); } /* *---------------------------------------------------------------------- * * TkNewMenuName -- * * Makes a new unique name for a cloned menu. Will be a child of oldName. * * Results: * Returns a char * which has been allocated; caller must free. * * Side effects: * Memory is allocated. * *---------------------------------------------------------------------- */ Tcl_Obj * TkNewMenuName( Tcl_Interp *interp, /* The interp the new name has to live in.*/ Tcl_Obj *parentPtr, /* The prefix path of the new name. */ TkMenu *menuPtr) /* The menu we are cloning. */ { Tcl_Obj *resultPtr = NULL; /* Initialization needed only to prevent * compiler warning. */ Tcl_Obj *childPtr; char *destString; int i; int doDot; Tcl_CmdInfo cmdInfo; Tcl_HashTable *nameTablePtr = NULL; TkWindow *winPtr = (TkWindow *) menuPtr->tkwin; char *parentName = Tcl_GetString(parentPtr); if (winPtr->mainPtr != NULL) { nameTablePtr = &(winPtr->mainPtr->nameTable); } doDot = parentName[strlen(parentName) - 1] != '.'; childPtr = Tcl_NewStringObj(Tk_PathName(menuPtr->tkwin), -1); for (destString = Tcl_GetString(childPtr); *destString != '\0'; destString++) { if (*destString == '.') { *destString = '#'; } } for (i = 0; ; i++) { if (i == 0) { resultPtr = Tcl_DuplicateObj(parentPtr); if (doDot) { Tcl_AppendToObj(resultPtr, ".", -1); } Tcl_AppendObjToObj(resultPtr, childPtr); } else { Tcl_Obj *intPtr; Tcl_DecrRefCount(resultPtr); resultPtr = Tcl_DuplicateObj(parentPtr); if (doDot) { Tcl_AppendToObj(resultPtr, ".", -1); } Tcl_AppendObjToObj(resultPtr, childPtr); intPtr = Tcl_NewIntObj(i); Tcl_AppendObjToObj(resultPtr, intPtr); Tcl_DecrRefCount(intPtr); } destString = Tcl_GetString(resultPtr); if ((Tcl_GetCommandInfo(interp, destString, &cmdInfo) == 0) && ((nameTablePtr == NULL) || (Tcl_FindHashEntry(nameTablePtr, destString) == NULL))) { break; } } Tcl_DecrRefCount(childPtr); return resultPtr; } /* *---------------------------------------------------------------------- * * TkSetWindowMenuBar -- * * Associates a menu with a window. Called by ConfigureFrame in in * response to a "-menu .foo" configuration option for a top level. * * Results: * None. * * Side effects: * The old menu clones for the menubar are thrown away, and a handler is * set up to allocate the new ones. * *---------------------------------------------------------------------- */ void TkSetWindowMenuBar( Tcl_Interp *interp, /* The interpreter the toplevel lives in. */ Tk_Window tkwin, /* The toplevel window. */ char *oldMenuName, /* The name of the menubar previously set in * this toplevel. NULL means no menu was set * previously. */ char *menuName) /* The name of the new menubar that the * toplevel needs to be set to. NULL means * that their is no menu now. */ { TkMenuTopLevelList *topLevelListPtr, *prevTopLevelPtr; TkMenu *menuPtr; TkMenuReferences *menuRefPtr; /* * Destroy the menubar instances of the old menu. Take this window out of * the old menu's top level reference list. */ if (oldMenuName != NULL) { menuRefPtr = TkFindMenuReferences(interp, oldMenuName); if (menuRefPtr != NULL) { /* * Find the menubar instance that is to be removed. Destroy it and * all of the cascades underneath it. */ if (menuRefPtr->menuPtr != NULL) { TkMenu *instancePtr; menuPtr = menuRefPtr->menuPtr; for (instancePtr = menuPtr->masterMenuPtr; instancePtr != NULL; instancePtr = instancePtr->nextInstancePtr) { if (instancePtr->menuType == MENUBAR && instancePtr->parentTopLevelPtr == tkwin) { RecursivelyDeleteMenu(instancePtr); break; } } } /* * Now we need to remove this toplevel from the list of toplevels * that reference this menu. */ topLevelListPtr = menuRefPtr->topLevelListPtr; prevTopLevelPtr = NULL; while ((topLevelListPtr != NULL) && (topLevelListPtr->tkwin != tkwin)) { prevTopLevelPtr = topLevelListPtr; topLevelListPtr = topLevelListPtr->nextPtr; } /* * Now we have found the toplevel reference that matches the * tkwin; remove this reference from the list. */ if (topLevelListPtr != NULL) { if (prevTopLevelPtr == NULL) { menuRefPtr->topLevelListPtr = menuRefPtr->topLevelListPtr->nextPtr; } else { prevTopLevelPtr->nextPtr = topLevelListPtr->nextPtr; } ckfree((char *) topLevelListPtr); TkFreeMenuReferences(menuRefPtr); } } } /* * Now, add the clone references for the new menu. */ if (menuName != NULL && menuName[0] != 0) { TkMenu *menuBarPtr = NULL; menuRefPtr = TkCreateMenuReferences(interp, menuName); menuPtr = menuRefPtr->menuPtr; if (menuPtr != NULL) { Tcl_Obj *cloneMenuPtr; TkMenuReferences *cloneMenuRefPtr; Tcl_Obj *newObjv[4]; Tcl_Obj *windowNamePtr = Tcl_NewStringObj(Tk_PathName(tkwin), -1); Tcl_Obj *menubarPtr = Tcl_NewStringObj("menubar", -1); /* * Clone the menu and all of the cascades underneath it. */ Tcl_IncrRefCount(windowNamePtr); cloneMenuPtr = TkNewMenuName(interp, windowNamePtr, menuPtr); Tcl_IncrRefCount(cloneMenuPtr); Tcl_IncrRefCount(menubarPtr); CloneMenu(menuPtr, cloneMenuPtr, menubarPtr); cloneMenuRefPtr = TkFindMenuReferencesObj(interp, cloneMenuPtr); if ((cloneMenuRefPtr != NULL) && (cloneMenuRefPtr->menuPtr != NULL)) { Tcl_Obj *cursorPtr = Tcl_NewStringObj("-cursor", -1); Tcl_Obj *nullPtr = Tcl_NewObj(); cloneMenuRefPtr->menuPtr->parentTopLevelPtr = tkwin; menuBarPtr = cloneMenuRefPtr->menuPtr; newObjv[0] = cursorPtr; newObjv[1] = nullPtr; Tcl_IncrRefCount(cursorPtr); Tcl_IncrRefCount(nullPtr); ConfigureMenu(menuPtr->interp, cloneMenuRefPtr->menuPtr, 2, newObjv); Tcl_DecrRefCount(cursorPtr); Tcl_DecrRefCount(nullPtr); } TkpSetWindowMenuBar(tkwin, menuBarPtr); Tcl_DecrRefCount(cloneMenuPtr); Tcl_DecrRefCount(menubarPtr); Tcl_DecrRefCount(windowNamePtr); } else { TkpSetWindowMenuBar(tkwin, NULL); } /* * Add this window to the menu's list of windows that refer to this * menu. */ topLevelListPtr = (TkMenuTopLevelList *) ckalloc(sizeof(TkMenuTopLevelList)); topLevelListPtr->tkwin = tkwin; topLevelListPtr->nextPtr = menuRefPtr->topLevelListPtr; menuRefPtr->topLevelListPtr = topLevelListPtr; } else { TkpSetWindowMenuBar(tkwin, NULL); } TkpSetMainMenubar(interp, tkwin, menuName); } /* *---------------------------------------------------------------------- * * DestroyMenuHashTable -- * * Called when an interp is deleted and a menu hash table has been set in * it. * * Results: * None. * * Side effects: * The hash table is destroyed. * *---------------------------------------------------------------------- */ static void DestroyMenuHashTable( ClientData clientData, /* The menu hash table we are destroying. */ Tcl_Interp *interp) /* The interpreter we are destroying. */ { Tcl_DeleteHashTable((Tcl_HashTable *) clientData); ckfree((char *) clientData); } /* *---------------------------------------------------------------------- * * TkGetMenuHashTable -- * * For a given interp, give back the menu hash table that goes with it. * If the hash table does not exist, it is created. * * Results: * Returns a hash table pointer. * * Side effects: * A new hash table is created if there were no table in the interp * originally. * *---------------------------------------------------------------------- */ Tcl_HashTable * TkGetMenuHashTable( Tcl_Interp *interp) /* The interp we need the hash table in.*/ { Tcl_HashTable *menuTablePtr; menuTablePtr = (Tcl_HashTable *) Tcl_GetAssocData(interp, MENU_HASH_KEY, NULL); if (menuTablePtr == NULL) { menuTablePtr = (Tcl_HashTable *) ckalloc(sizeof(Tcl_HashTable)); Tcl_InitHashTable(menuTablePtr, TCL_STRING_KEYS); Tcl_SetAssocData(interp, MENU_HASH_KEY, DestroyMenuHashTable, (ClientData) menuTablePtr); } return menuTablePtr; } /* *---------------------------------------------------------------------- * * TkCreateMenuReferences -- * * Given a pathname, gives back a pointer to a TkMenuReferences * structure. If a reference is not already in the hash table, one is * created. * * Results: * Returns a pointer to a menu reference structure. Should not be freed * by calller; when a field of the reference is cleared, * TkFreeMenuReferences should be called. * * Side effects: * A new hash table entry is created if there were no references to the * menu originally. * *---------------------------------------------------------------------- */ TkMenuReferences * TkCreateMenuReferences( Tcl_Interp *interp, char *pathName) /* The path of the menu widget. */ { Tcl_HashEntry *hashEntryPtr; TkMenuReferences *menuRefPtr; int newEntry; Tcl_HashTable *menuTablePtr = TkGetMenuHashTable(interp); hashEntryPtr = Tcl_CreateHashEntry(menuTablePtr, pathName, &newEntry); if (newEntry) { menuRefPtr = (TkMenuReferences *) ckalloc(sizeof(TkMenuReferences)); menuRefPtr->menuPtr = NULL; menuRefPtr->topLevelListPtr = NULL; menuRefPtr->parentEntryPtr = NULL; menuRefPtr->hashEntryPtr = hashEntryPtr; Tcl_SetHashValue(hashEntryPtr, (char *) menuRefPtr); } else { menuRefPtr = (TkMenuReferences *) Tcl_GetHashValue(hashEntryPtr); } return menuRefPtr; } /* *---------------------------------------------------------------------- * * TkFindMenuReferences -- * * Given a pathname, gives back a pointer to the TkMenuReferences * structure. * * Results: * Returns a pointer to a menu reference structure. Should not be freed * by calller; when a field of the reference is cleared, * TkFreeMenuReferences should be called. Returns NULL if no reference * with this pathname exists. * * Side effects: * None. * *---------------------------------------------------------------------- */ TkMenuReferences * TkFindMenuReferences( Tcl_Interp *interp, /* The interp the menu is living in. */ char *pathName) /* The path of the menu widget. */ { Tcl_HashEntry *hashEntryPtr; TkMenuReferences *menuRefPtr = NULL; Tcl_HashTable *menuTablePtr; menuTablePtr = TkGetMenuHashTable(interp); hashEntryPtr = Tcl_FindHashEntry(menuTablePtr, pathName); if (hashEntryPtr != NULL) { menuRefPtr = (TkMenuReferences *) Tcl_GetHashValue(hashEntryPtr); } return menuRefPtr; } /* *---------------------------------------------------------------------- * * TkFindMenuReferencesObj -- * * Given a pathname, gives back a pointer to the TkMenuReferences * structure. * * Results: * Returns a pointer to a menu reference structure. Should not be freed * by calller; when a field of the reference is cleared, * TkFreeMenuReferences should be called. Returns NULL if no reference * with this pathname exists. * * Side effects: * None. * *---------------------------------------------------------------------- */ TkMenuReferences * TkFindMenuReferencesObj( Tcl_Interp *interp, /* The interp the menu is living in. */ Tcl_Obj *objPtr) /* The path of the menu widget. */ { char *pathName = Tcl_GetString(objPtr); return TkFindMenuReferences(interp, pathName); } /* *---------------------------------------------------------------------- * * TkFreeMenuReferences -- * * This is called after one of the fields in a menu reference is cleared. * It cleans up the ref if it is now empty. * * Results: * Returns 1 if the references structure was freed, and 0 otherwise. * * Side effects: * If this is the last field to be cleared, the menu ref is taken out of * the hash table. * *---------------------------------------------------------------------- */ int TkFreeMenuReferences( TkMenuReferences *menuRefPtr) /* The menu reference to free. */ { if ((menuRefPtr->menuPtr == NULL) && (menuRefPtr->parentEntryPtr == NULL) && (menuRefPtr->topLevelListPtr == NULL)) { Tcl_DeleteHashEntry(menuRefPtr->hashEntryPtr); ckfree((char *) menuRefPtr); return 1; } return 0; } /* *---------------------------------------------------------------------- * * DeleteMenuCloneEntries -- * * For every clone in this clone chain, delete the menu entries given by * the parameters. * * Results: * None. * * Side effects: * The appropriate entries are deleted from all clones of this menu. * *---------------------------------------------------------------------- */ static void DeleteMenuCloneEntries( TkMenu *menuPtr, /* The menu the command was issued with. */ int first, /* The zero-based first entry in the set of * entries to delete. */ int last) /* The zero-based last entry. */ { TkMenu *menuListPtr; int numDeleted, i, j; numDeleted = last + 1 - first; for (menuListPtr = menuPtr->masterMenuPtr; menuListPtr != NULL; menuListPtr = menuListPtr->nextInstancePtr) { for (i = last; i >= first; i--) { Tcl_EventuallyFree((ClientData) menuListPtr->entries[i], DestroyMenuEntry); } for (i = last + 1; i < menuListPtr->numEntries; i++) { j = i - numDeleted; menuListPtr->entries[j] = menuListPtr->entries[i]; menuListPtr->entries[j]->index = j; } menuListPtr->numEntries -= numDeleted; if (menuListPtr->numEntries == 0) { ckfree((char *) menuListPtr->entries); menuListPtr->entries = NULL; } if ((menuListPtr->active >= first) && (menuListPtr->active <= last)) { menuListPtr->active = -1; } else if (menuListPtr->active > last) { menuListPtr->active -= numDeleted; } TkEventuallyRecomputeMenu(menuListPtr); } } /* *---------------------------------------------------------------------- * * TkMenuCleanup -- * * Resets menusInitialized to allow Tk to be finalized and reused without * the DLL being unloaded. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void TkMenuCleanup( ClientData unused) { menusInitialized = 0; } /* *---------------------------------------------------------------------- * * TkMenuInit -- * * Sets up the hash tables and the variables used by the menu package. * * Results: * None. * * Side effects: * lastMenuID gets initialized, and the parent hash and the command hash * are allocated. * *---------------------------------------------------------------------- */ void TkMenuInit(void) { ThreadSpecificData *tsdPtr = (ThreadSpecificData *) Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData)); if (!menusInitialized) { Tcl_MutexLock(&menuMutex); if (!menusInitialized) { TkpMenuInit(); menusInitialized = 1; } /* * Make sure we cleanup on finalize. */ TkCreateExitHandler((Tcl_ExitProc *) TkMenuCleanup, NULL); Tcl_MutexUnlock(&menuMutex); } if (!tsdPtr->menusInitialized) { TkpMenuThreadInit(); tsdPtr->menusInitialized = 1; } } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */