This file is indexed.

/usr/lib/python2.7/dist-packages/wxglade/codegen/cpp_codegen.py is in python-wxglade 0.6.8-2.2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
"""\
C++ code generator

How the code is generated: every time the end of an object is reached during
the parsing of the xml tree, either the function 'add_object' or the function
'add_class' is called: the latter when the object is a toplevel one, the former
when it is not. In the last case, 'add_object' calls the appropriate ``writer''
function for the specific object, found in the 'obj_builders' dict. Such
function accepts one argument, the CodeObject representing the object for
which the code has to be written, and returns 3 lists of strings, representing
the lines to add to the '__init__', '__set_properties' and '__do_layout'
methods of the parent object.

@copyright: 2002-2007 Alberto Griggio <agriggio@users.sourceforge.net>
@copyright: 2012 Carsten Grohmann <mail@carstengrohmann.de>
@license: MIT (see license.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""

import cStringIO
import os
import os.path
import re

from codegen import BaseCodeWriter, \
                    BaseSourceFileContent, \
                    BaseWidgetHandler


class SourceFileContent(BaseSourceFileContent):
    """\
    Keeps info about an existing file that has to be updated, to replace only
    the lines inside a wxGlade block, an to keep the rest of the file as it was

    @ivar event_handlers: List of event handlers for each class
    @ivar header_content: Content of the header file
    @ivar source_content: Content of the source file
    """

    rec_block_start = re.compile(
        r'^(?P<spaces>\s*)'                     # leading spaces
        r'//\s*'                                # comment sign
        r'begin\s+wxGlade:\s*'                  # "begin wxGlade:" statement and tailing spaces
        r'(?P<classname>\w*)'                   # class or function name
        r'::'                                   # separator between class and function / block (non-greedy)
        r'(?P<block>\w+)'                       # function / block name
        r'\s*$'                                 # tailing spaces
        )

    rec_block_end = re.compile(
        r'^\s*'                                 # leading spaces
        r'//\s*'                                # comment sign
        r'end\s+wxGlade'                        # "end exGlade" statement
        r'\s*$'                                 # tailing spaces
        )

    rec_class_end = re.compile(
        r'^\s*};\s*'                            # closing curly brackets
        r'//\s*'                                # comment sign
        r'wxGlade:\s+end\s+class'               # "wxGlade: end class" statement
        r'\s*$'                                 # tailing spaces
        )
    """\
    Regexp to match last line of a class statement
    """

    rec_class_decl = re.compile(
        r'^\s*'                                  # leading spaces
        r'class\s+([a-zA-Z_]\w*)'                # "class <name>" statement
        r'\s*'                                   # tailing spaces
        )
    """\
    Regexp to match class declarations

    This isn't very accurate - doesn't match template classes, nor virtual
    inheritance, but should be enough for most cases
    """

    rec_decl_event_table = re.compile(
        r'^\s*'                                       # leading spaces
        r'DECLARE_EVENT_TABLE\s*\(\s*\)\s*;?'         # declaration of the event table
        r'\s*$'                                       # tailing spaces
        )
    """\
    Regexp to match declaration of event table
    """

    rec_def_event_table = re.compile(
        r'^\s*'                                       # leading spaces
        r'BEGIN_EVENT_TABLE\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)'
        r'\s*$'                                       # tailing spaces
        )
    """\
    Regexp to match event table
    """

    rec_event_handler = re.compile(
        r'^\s*'                                       # leading spaces
        r'(?:virtual\s+)?'
        r'void\s+(?P<handler>[A-Za-z_]+\w*)'          # event handler name
        r'\s*'                                        # optional spaces
        r'\([A-Za-z_:0-9]+\s*&\s*\w*\)\s*;'
        r'\s*'                                        # optional spaces
        r'//\s*wxGlade:\s*<event_handler>'            # wxGlade event handler statement
        r'\s*$'                                       # tailing spaces
        )

    rec_event_handlers_marker = re.compile(
        r'^\s*'                                       # leading spaces
        r'//\s*wxGlade:\s*add\s+'
        r'((?:\w|:)+)\s+event handlers'
        r'\s*$'                                       # tailing spaces
        )
    """\
    Regexp to match wxGlade comment of event handlers
    """

    def __init__(self, name, code_writer):

        # initialise new variables first
        self.header_content = None
        self.source_content = None
        self.event_table_decl = {}
        self.event_table_def = {}
        self.header_extension = code_writer.header_extension
        self.source_extension = code_writer.source_extension

        # call inherited constructor
        BaseSourceFileContent.__init__(self, name, code_writer)

    def build_untouched_content(self):
        BaseSourceFileContent.build_untouched_content(self)
        self._build_untouched(self.name + self.header_extension, True)
        BaseSourceFileContent.build_untouched_content(self)
        self._build_untouched(self.name + self.source_extension, False)

    def _build_untouched(self, filename, is_header):
        prev_was_handler = False
        events_tag_added = False

        inside_block = False
        inside_comment = False
        tmp_in = self._load_file(filename)
        out_lines = []
        for line in tmp_in:
            comment_index = line.find('/*')
            if not inside_comment and comment_index != -1 \
                   and comment_index > line.find('//'):
                inside_comment = True
            if inside_comment:
                end_index = line.find('*/')
                if end_index > comment_index:
                    inside_comment = False
            if not is_header:
                result = None
            else:
                result = self.rec_class_decl.match(line)
            if not inside_comment and not inside_block and result:
##                print ">> class %r" % result.group(1)
                if not self.class_name:
                    # this is the first class declared in the file: insert the
                    # new ones before this
                    out_lines.append('<%swxGlade insert new_classes>' %
                                     self.nonce)
                    self.new_classes_inserted = True
                self.class_name = result.group(1)
                self.class_name = self.format_classname(self.class_name)
                self.classes[self.class_name] = 1  # add the found class to the list
                                              # of classes of this module
                out_lines.append(line)
            elif not inside_block:
                result = self.rec_block_start.match(line)
                if not inside_comment and result:
##                     print ">> block %r %r %r" % (
##                         result.group('spaces'), result.group('classname'), result.group('block'))
                    # replace the lines inside a wxGlade block with a tag that
                    # will be used later by add_class
                    spaces = result.group('spaces')
                    which_class = result.group('classname')
                    which_block = result.group('block')
                    if not which_class:
                        which_class = self.class_name
                    else:
                        which_class = self.format_classname(which_class)
                    self.spaces[which_class] = spaces
                    inside_block = True
                    out_lines.append('<%swxGlade replace %s %s>' % (
                        self.nonce,
                        result.group('classname'),
                        result.group('block')
                        ))
                else:
                    dont_append = False

                    # ALB 2004-12-08 event handling support...
                    if is_header and not inside_comment:
                        result = self.rec_event_handler.match(line)
                        if result:
                            prev_was_handler = True
                            which_handler = result.group('handler')
                            which_class = self.class_name
                            self.event_handlers.setdefault(
                                which_class, {})[which_handler] = 1
                        else:
                            if prev_was_handler:
                                # add extra event handlers here...
                                out_lines.append('<%swxGlade event_handlers %s>'
                                                 % (self.nonce, self.class_name)
                                        )
                                prev_was_handler = False
                                events_tag_added = True
                            elif not events_tag_added and \
                                     self.is_end_of_class(line):
                                out_lines.append(
                                    '<%swxGlade event_handlers %s>' % \
                                        (self.nonce, self.class_name)
                                        )
                            # now try to see if we already have a
                            # DECLARE_EVENT_TABLE
                            result = self.rec_decl_event_table.match(line)
                            if result:
                                self.event_table_decl[self.class_name] = True
                    elif not inside_comment:
                        result = self.rec_event_handlers_marker.match(line)
                        if result:
                            out_lines.append('<%swxGlade add %s event '
                                             'handlers>' % \
                                             (self.nonce, result.group(1)))
                            dont_append = True
                        result = self.rec_def_event_table.match(line)
                        if result:
                            which_class = result.group(1)
                            self.event_table_def[which_class] = True
                    # ----------------------------------------

                    if not dont_append:
                        out_lines.append(line)
            else:
                # ignore all the lines inside a wxGlade block
                if self.rec_block_end.match(line):
                    inside_block = False
        if is_header and not self.new_classes_inserted:
            # if we are here, the previous ``version'' of the file did not
            # contain any class, so we must add the new_classes tag at the
            # end of the file
            out_lines.append('<%swxGlade insert new_classes>' % self.nonce)
        # set the ``persistent'' content of the file
        if is_header:
            self.header_content = "".join(out_lines)
        else:
            self.source_content = "".join(out_lines)

    def is_end_of_class(self, line):
        """\
        Return True if the line is the last line of a class

        Not really, but for wxglade-generated code it should work...
        """
        return self.rec_class_end.match(line)

# end of class SourceFileContent


class WidgetHandler(BaseWidgetHandler):
    """\
    Interface the various code generators for the widgets must implement
    """

    constructor = []
    """\
    ``signature'' of the widget's constructor
    """

    extra_headers = []
    """\
    If not None, list of extra header file, in the form
    <header.h> or "header.h"
    """

    def __init__(self):
        BaseWidgetHandler.__init__(self)
        self.constructor = []
        self.extra_headers = []

    def get_ids_code(self, obj):
        """\
        Handler for the code of the ids enum of toplevel objects.
        Returns a list of strings containing the code to generate.
        Usually the default implementation is ok (i.e. there are no
        extra lines to add)
        """
        return []

# end of class WidgetHandler


class CPPCodeWriter(BaseCodeWriter):
    """\
    Code writer class for writing C++ code out of the designed GUI elements

    @ivar source_extension: Extension of the source file
    @type source_extension: String

    @ivar header_extension: Extension of the header file
    @type header_extension: String

    @ivar last_generated_id: Last generated Id number (wxNewId() is not
                             used yet)
    @type last_generated_id: Integer

    @cvar tmpl_init_gettext: Template for inclusion of i18n headers and
                             defining APP_CATALOG constant
    @type tmpl_init_gettext: None or string

    @see: L{BaseCodeWriter}
    """

    default_extensions = ['cpp', 'cc', 'C', 'cxx', 'c++',
                          'h', 'hh', 'hpp', 'H', 'hxx', ]
    language = "C++"

    code_statements = {
        'backgroundcolour': "%(objname)sSetBackgroundColour(%(value)s);\n",
        'disabled':         "%(objname)sEnable(0);\n",
        'extraproperties':  "%(objname)sSet%(propname)s(%(value)s);\n",
        'focused':          "%(objname)sSetFocus();\n",
        'foregroundcolour': "%(objname)sSetForegroundColour(%(value)s);\n",
        'hidden':           "%(objname)sHide();\n",
        'setfont':          "%(objname)sSetFont(wxFont(%(size)s, %(family)s, "
                            "%(style)s, %(weight)s, %(underlined)s, wxT(%(face)s)));\n",
        'tooltip':          "%(objname)sSetToolTip(%(tooltip)s);\n",
        'wxcolour':         "wxColour(%(value)s)",
        'wxsystemcolour':   "wxSystemSettings::GetColour(%(value)s)",
        }

    class_separator = '::'
    comment_sign = '//'

    global_property_writers = {
        'font':            BaseCodeWriter.FontPropertyHandler,
        'events':          BaseCodeWriter.EventsPropertyHandler,
        'extraproperties': BaseCodeWriter.ExtraPropertiesPropertyHandler,
        }

    language_note = \
        '// Example for compiling a single file project under Linux using g++:\n' \
        '//  g++ MyApp.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp\n' \
        '//\n' \
        '// Example for compiling a multi file project under Linux using g++:\n' \
        '//  g++ main.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp Dialog1.cpp Frame1.cpp\n' \
        '//\n'

    last_generated_id = 1000

    output_name = None
    """\
    If not None, name (without extension) of the file to write into

    @type: String
    """

    output_header = None
    """\
    Temporary storage of header file for writing into

    @type: StringIO
    """

    output_file = None
    """\
    Temporary storage of source file for writing into

    @type: StringIO
    """

    shebang = '// -*- C++ -*-\n//\n'

    tmpl_cfunc_end = '}\n\n'

    tmpl_name_do_layout = 'do_layout'
    tmpl_name_set_properties = 'set_properties'

    tmpl_sizeritem = '%s->Add(%s, %s, %s, %s);\n'

    tmpl_ctor_call_layout = '\n' \
                            '%(tab)sset_properties();\n' \
                            '%(tab)sdo_layout();\n'

    tmpl_func_do_layout = '\n' \
                          'void %(klass)s::do_layout()\n{\n' \
                          '%(content)s' \
                          '}\n\n'

    tmpl_func_set_properties = '\n' \
                          'void %(klass)s::set_properties()\n{\n' \
                          '%(content)s' \
                          '}\n\n'

    tmpl_appfile = """\
%(overwrite)s\
%(header_lines)s\
#include "%(top_win_class)s.h"

"""

    tmpl_init_gettext = """\
#include "wx/intl.h"

#ifndef APP_CATALOG
#define APP_CATALOG "%(name)s"  // replace with the appropriate catalog name
#endif

"""

    tmpl_detailed = """\

class %(klass)s: public wxApp {
public:
%(tab)sbool OnInit();
};

IMPLEMENT_APP(%(klass)s)

bool %(klass)s::OnInit()
{
%(tab)swxInitAllImageHandlers();
%(tab)s%(top_win_class)s* %(top_win)s = new %(top_win_class)s(NULL, wxID_ANY, wxEmptyString);
%(tab)sSetTopWindow(%(top_win)s);
%(tab)s%(top_win)s->Show();
%(tab)sreturn true;
}"""

    tmpl_gettext_detailed = """\

class %(klass)s: public wxApp {
public:
%(tab)sbool OnInit();
protected:
%(tab)swxLocale m_locale;  // locale we'll be using
};

IMPLEMENT_APP(%(klass)s)

bool %(klass)s::OnInit()
{
%(tab)sm_locale.Init();
#ifdef APP_LOCALE_DIR
%(tab)sm_locale.AddCatalogLookupPathPrefix(wxT(APP_LOCALE_DIR));
#endif
%(tab)sm_locale.AddCatalog(wxT(APP_CATALOG));

%(tab)swxInitAllImageHandlers();
%(tab)s%(top_win_class)s* %(top_win)s = new %(top_win_class)s(NULL, wxID_ANY, wxEmptyString);
%(tab)sSetTopWindow(%(top_win)s);
%(tab)s%(top_win)s->Show();
%(tab)sreturn true;
}"""

    tmpl_simple = """\

class MyApp: public wxApp {
public:
%(tab)sbool OnInit();
};

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
%(tab)swxInitAllImageHandlers();
%(tab)s%(top_win_class)s* %(top_win)s = new %(top_win_class)s(NULL, wxID_ANY, wxEmptyString);
%(tab)sSetTopWindow(%(top_win)s);
%(tab)s%(top_win)s->Show();
%(tab)sreturn true;
}"""

    tmpl_gettext_simple = """\

class MyApp: public wxApp {
public:
%(tab)sbool OnInit();
protected:
%(tab)swxLocale m_locale;  // locale we'll be using
};

IMPLEMENT_APP(MyApp)

bool MyApp::OnInit()
{
%(tab)sm_locale.Init();
#ifdef APP_LOCALE_DIR
%(tab)sm_locale.AddCatalogLookupPathPrefix(wxT(APP_LOCALE_DIR));
#endif
%(tab)sm_locale.AddCatalog(wxT(APP_CATALOG));

%(tab)swxInitAllImageHandlers();
%(tab)s%(top_win_class)s* %(top_win)s = new %(top_win_class)s(NULL, wxID_ANY, wxEmptyString);
%(tab)sSetTopWindow(%(top_win)s);
%(tab)s%(top_win)s->Show();
%(tab)sreturn true;
}"""


    class ClassLines(BaseCodeWriter.ClassLines):
        """\
        Stores the lines of C++ code for a custom class

        @ivar ids:             Ids declared in the source (to use for Event
                               handling): these are grouped together into a
                               public enum in the custom class
        @ivar sub_objs:        List of 2-tuples (type, name) of the sub-objects
                               which are attributes of the toplevel object
        @ivar extra_code_h:    Extra header code to output
        @ivar extra_code_cpp:  Extra source code to output
        """
        def __init__(self):
            BaseCodeWriter.ClassLines.__init__(self)
            self.ids = []
            self.sub_objs = []
            self.extra_code_h = []
            self.extra_code_cpp = []
            self.dependencies = []     # List not dictionary

    # end of class ClassLines

    def initialize(self, app_attrs):
        """\
        Writer initialization function.

        @keyword path: Output path for the generated code (a file if multi_files is
                       False, a dir otherwise)
        @keyword option: If True, generate a separate file for each custom class
        """
        # initialise parent class
        BaseCodeWriter.initialize(self, app_attrs)

        self.app_filename = 'main.cpp'

        out_path = app_attrs['path']

        self.last_generated_id = 1000

        # Extensions based on Project options when set
        self.source_extension = app_attrs.get('source_extension', '.cpp')
        self.header_extension = app_attrs.get('header_extension', '.h')

        self.header_lines = [
            '#include <wx/wx.h>\n',
            '#include <wx/image.h>\n',
            ]

        # include i18n / gettext
        if self._use_gettext:
            self.header_lines.append(
                self.tmpl_init_gettext % {'name': self.app_name}
                )

        # extra lines to generate (see the 'extracode' property of top-level
        # widgets)
        self._current_extra_code_h = []
        self._current_extra_code_cpp = []

        if self.multiple_files:
            self.previous_source = None
            if not os.path.isdir(out_path):
                raise IOError("'path' must be a directory when generating"\
                                      " multiple output files")
            self.out_dir = out_path
        else:
            name = os.path.splitext(out_path)[0]
            self.output_name = name
            if not self._overwrite and self._file_exists(name + self.header_extension):
                # the file exists, we must keep all the lines not inside a wxGlade
                # block. NOTE: this may cause troubles if out_path is not a valid
                # source file, so be careful!
                self.previous_source = SourceFileContent(name, self)
            else:
                # if the file doesn't exist, create it and write the ``intro''
                self.previous_source = None
                self.output_header = cStringIO.StringIO()
                self.output_file = cStringIO.StringIO()

                # isolation directives
                oh = os.path.basename(name + self.header_extension).upper().replace(
                    '.', '_')
                self.output_header.write('#ifndef %s\n#define %s\n' % (oh, oh))
                self.output_header.write('\n')

                for line in self.header_lines:
                    self.output_header.write(line)
                self.output_header.write('\n')

                # now, write the tags to store dependencies and extra code
                self.output_header.write('<%swxGlade replace  dependencies>' % self.nonce)
                self.output_header.write('\n<%swxGlade replace  extracode>' % self.nonce)

                self.output_header.write('\n')

                self.output_file.write('#include "%s%s"\n\n' % \
                                    (os.path.basename(name), self.header_extension))
                self.output_file.write('<%swxGlade replace  extracode>\n\n' % self.nonce)

    def finalize(self):
        if self.previous_source:
            # insert all the new custom classes inside the old file
            tag = '<%swxGlade insert new_classes>' % self.nonce
            if self.previous_source.new_classes:
                code = "".join([c[0] for c in self.previous_source.new_classes])
            else:
                code = ""
            header_content = self.previous_source.header_content.replace(tag, code)
            extra_source = "".join([c[1] for c in self.previous_source.new_classes])
            source_content = self.previous_source.source_content

            # extra code (see the 'extracode' property of top-level widgets)
            tag = '<%swxGlade replace  extracode>' % self.nonce
            code = self._tagcontent(
                '::extracode',
                self._current_extra_code_h
                )
            header_content = header_content.replace(tag, code)
            code = self._tagcontent(
                '::extracode',
                self._current_extra_code_cpp
                )
            source_content = source_content.replace(tag, code)
            # --------------------------------------------------------------

            # now remove all the remaining <123415wxGlade ...> tags from the
            # source: this may happen if we're not generating multiple files,
            # and one of the container class names is changed
            tags = re.findall(
                '(<%swxGlade replace ([a-zA-Z_]*\w*) (\w+)>)' % self.nonce,
                header_content
                )
            for tag in tags:
                if tag[2] == 'dependencies':
                    #print 'writing dependencies'
                    deps = []
                    for code in self.classes.itervalues():
                        deps.extend(code.dependencies)
                    lines = self._format_dependencies(deps)
                elif tag[2] == 'methods':
                    lines = '%svoid set_properties();\n%svoid do_layout();\n' \
                            % (self.tabs(1), self.tabs(1))
                else:
                    lines = '// content of this block (%s) not found: ' \
                            'did you rename this class?\n' % tag[2]
                header_content = header_content.replace(tag[0], lines)

            # remove all the remaining <123415wxGlade ...> tags in source file
            source_content = self._content_notfound(
                source_content,
                )

            # ALB 2004-12-08
            tags = re.findall('<%swxGlade event_handlers \w+>' % self.nonce,
                              header_content)
            for tag in tags:
                header_content = header_content.replace(tag, "")
            tags = re.findall('<%swxGlade add \w+ event_handlers>' % self.nonce,
                              source_content)
            for tag in tags:
                source_content = source_content.replace(tag, "")

            # write the new file contents to disk
            self.save_file(
                self.previous_source.name + self.header_extension,
                header_content,
                content_only=True
                )
            if extra_source:
                extra_source = '\n\n' + extra_source
            self.save_file(
                self.previous_source.name + self.source_extension,
                source_content + extra_source,
                content_only=True
                )

        elif not self.multiple_files:
            oh = os.path.basename(self.output_name).upper() + '_H'
            self.output_header.write('\n#endif // %s\n' % oh)
            # write the list of include files
            header_content = self.output_header.getvalue()
            source_content = self.output_file.getvalue()
            tags = re.findall('<%swxGlade replace  dependencies>' %
                              self.nonce, header_content)
            deps = []
            for code in self.classes.itervalues():
                deps.extend(code.dependencies)
            code = self._format_dependencies(deps)
            header_content = header_content.replace(
                '<%swxGlade replace  dependencies>' % self.nonce, code)

            # extra code (see the 'extracode' property of top-level widgets)
            tag = '<%swxGlade replace  extracode>' % self.nonce
            code = self._tagcontent('::extracode', self._current_extra_code_h)
            header_content = header_content.replace(tag, code)
            code = self._tagcontent('::extracode', self._current_extra_code_cpp)
            source_content = source_content.replace(tag, code)
            # --------------------------------------------------------------

            self.save_file(
                self.output_name + self.header_extension,
                header_content,
                self._app_added
                )
            self.save_file(
                self.output_name + self.source_extension,
                source_content,
                self._app_added
                )

    def add_class(self, code_obj):
        if self.classes.has_key(code_obj.klass) and \
           self.classes[code_obj.klass].done:
            return  # the code has already been generated

        if self.multiple_files:
            # let's see if the file to generate exists, and in this case
            # create a SourceFileContent instance
            filename = os.path.join(self.out_dir,
                                    code_obj.klass.replace('::', '_') +
                                    self.header_extension)
            if self._overwrite or not self._file_exists(filename):
                prev_src = None
            else:
                prev_src = SourceFileContent(
                    os.path.join(self.out_dir, code_obj.klass),
                    self,
                    )
        else:
            # in this case, previous_source is the SourceFileContent instance
            # that keeps info about the single file to generate
            prev_src = self.previous_source

        try:
            builder = self.obj_builders[code_obj.base]
            mycn = getattr(builder, 'cn', self.cn)
            mycn_f = getattr(builder, 'cn_f', self.cn_f)
        except KeyError:
            print code_obj
            raise  # this is an error, let the exception be raised

        if prev_src and prev_src.classes.has_key(code_obj.klass):
            is_new = False
        else:
            # this class wasn't in the previous version of the source (if any)
            is_new = True

        header_buffer = []
        source_buffer = []
        hwrite = header_buffer.append
        swrite = source_buffer.append

        if not self.classes.has_key(code_obj.klass):
            # if the class body was empty, create an empty ClassLines
            self.classes[code_obj.klass] = self.ClassLines()

        # collect all event handlers
        event_handlers = self.classes[code_obj.klass].event_handlers
        if hasattr(builder, 'get_events'):
            for id, event, handler in builder.get_events(code_obj):
                event_handlers.append((id, mycn(event), handler))

        # try to see if there's some extra code to add to this class
        extra_code = getattr(builder, 'extracode',
                             code_obj.properties.get('extracode', ""))
        if extra_code:
            extra_code = re.sub(r'\\n', '\n', extra_code)
            extra_code = re.split(re.compile(r'^###\s*$', re.M), extra_code, 1)
            self.classes[code_obj.klass].extra_code_h.append(extra_code[0])
            if len(extra_code) > 1:
                self.classes[code_obj.klass].extra_code_cpp.append(extra_code[1])
            if not is_new:
                self.warning(
                    '%s has extra code, but you are not overwriting '
                    'existing sources: please check that the resulting '
                    'code is correct!' % code_obj.name
                    )

        if not self.multiple_files and extra_code:
            if self.classes[code_obj.klass].extra_code_h:
                self._current_extra_code_h.append("".join(
                    self.classes[code_obj.klass].extra_code_h[::-1]))
            if self.classes[code_obj.klass].extra_code_cpp:
                self._current_extra_code_cpp.append("".join(
                    self.classes[code_obj.klass].extra_code_cpp[::-1]))

        default_sign = [('wxWindow*', 'parent'), ('int', 'id')]
        sign = getattr(builder, 'constructor', default_sign)

        defaults = []
        for t in sign:
            if len(t) == 3:
                defaults.append(t[2])
            else:
                defaults.append(None)
        tmp_sign = [t[0] + ' ' + t[1] for t in sign]
        sign_decl2 = ', '.join(tmp_sign)
        for i in range(len(tmp_sign)):
            if defaults[i]:
                tmp_sign[i] += '=%s' % defaults[i]
        sign_decl1 = ', '.join(tmp_sign)
        sign_inst = ', '.join([t[1] for t in sign])

        # custom base classes support
        custom_base = getattr(code_obj, 'custom_base',
                              code_obj.properties.get('custom_base', None))
        if custom_base and not custom_base.strip():
            custom_base = None

        # generate constructor code
        if is_new:
            pass
        elif custom_base:
            # custom base classes set, but "overwrite existing sources" not
            # set. Issue a warning about this
            self.warning(
                '%s has custom base classes, but you are not overwriting '
                'existing sources: please check that the resulting code is '
                'correct!' % code_obj.name
                )

        if is_new:
            # header file
            base = code_obj.base
            if custom_base:
                base = ", public ".join([b.strip() for b in custom_base.split(',')])
            hwrite('\nclass %s: public %s {\n' % (code_obj.klass, base))
            hwrite('public:\n')
            # the first thing to add it the enum of the various ids
            hwrite(self.tabs(1) + '// begin wxGlade: %s::ids\n' % code_obj.klass)
            ids = self.classes[code_obj.klass].ids

            # let's try to see if there are extra ids to add to the enum
            if hasattr(builder, 'get_ids_code'):
                ids.extend(builder.get_ids_code(code_obj))

            if ids:
                hwrite(self.tabs(1) + 'enum {\n')
                ids = (',\n' + self.tabs(2)).join(ids)
                hwrite(self.tabs(2) + ids)
                hwrite('\n' + self.tabs(1) + '};\n')
            hwrite(self.tabs(1) + '// end wxGlade\n\n')
            # constructor prototype
            hwrite(self.tabs(1) + '%s(%s);\n' % (code_obj.klass, sign_decl1))
            hwrite('\nprivate:\n')
            # set_properties and do_layout prototypes
            hwrite(self.tabs(1) + '// begin wxGlade: %s::methods\n' % code_obj.klass)
            hwrite(self.tabs(1) + 'void set_properties();\n')
            hwrite(self.tabs(1) + 'void do_layout();\n')
            hwrite(self.tabs(1) + '// end wxGlade\n')
            # declarations of the attributes
            hwrite('\n')
            hwrite('protected:\n')
            hwrite(self.tabs(1) + '// begin wxGlade: %s::attributes\n' % code_obj.klass)
            for o_type, o_name in self.classes[code_obj.klass].sub_objs:
                hwrite(self.tabs(1) + '%s* %s;\n' % (o_type, o_name))
            hwrite(self.tabs(1) + '// end wxGlade\n')

            # ALB 2004-12-08 event handling
            if event_handlers:
                t = self.tabs(1)
                hwrite('\n' + t + 'DECLARE_EVENT_TABLE();\n')
                hwrite('\npublic:\n')
                already_there = {}
                for tpl in event_handlers:
                    if len(tpl) == 4:
                        win_id, event, handler, evt_type = tpl
                    else:
                        win_id, event, handler = tpl
                        evt_type = 'wxCommandEvent'
                    if handler not in already_there:
                        # Sebastien JEFFROY & Steve MULLER contribution
                        # Adding virtual attribute permits to derivate from the
                        # class generated by wxGlade
                        hwrite(t + 'virtual void %s(%s &event); '
                               '// wxGlade: <event_handler>\n' %
                               (handler, evt_type))
                        already_there[handler] = 1

            hwrite('}; // wxGlade: end class\n\n')

        elif prev_src:
            hwrite(self.tabs(1) + '// begin wxGlade: %s::ids\n' % code_obj.klass)
            ids = self.classes[code_obj.klass].ids

            # let's try to see if there are extra ids to add to the enum
            if hasattr(builder, 'get_ids_code'):
                ids.extend(builder.get_ids_code(code_obj))

            if ids:
                hwrite(self.tabs(1) + 'enum {\n')
                ids = (',\n' + self.tabs(2)).join(ids)
                hwrite(self.tabs(2) + ids)
                hwrite('\n' + self.tabs(1) + '};\n')
            hwrite(self.tabs(1) + '// end wxGlade\n')
            tag = '<%swxGlade replace %s ids>' % (self.nonce, code_obj.klass)
            if prev_src.header_content.find(tag) < 0:
                # no ids tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade ids block not found for %s, ids declarations "
                    "code NOT generated" % code_obj.name
                    )
            else:
                prev_src.header_content = prev_src.header_content.\
                                          replace(tag, "".join(header_buffer))
            header_buffer = [
                self.tabs(1) + '// begin wxGlade: %s::methods\n' % \
                code_obj.klass,
                self.tabs(1) + 'void set_properties();\n',
                self.tabs(1) + 'void do_layout();\n',
                self.tabs(1) + '// end wxGlade\n',
                ]
            tag = '<%swxGlade replace %s methods>' % (self.nonce, code_obj.klass)
            if prev_src.header_content.find(tag) < 0:
                # no methods tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade methods block not found for %s, methods "
                    "declarations code NOT generated" % code_obj.name
                    )
            else:
                prev_src.header_content = prev_src.header_content.\
                                          replace(tag, "".join(header_buffer))
            header_buffer = []
            hwrite = header_buffer.append
            hwrite(self.tabs(1) + '// begin wxGlade: %s::attributes\n' % code_obj.klass)
            for o_type, o_name in self.classes[code_obj.klass].sub_objs:
                hwrite(self.tabs(1) + '%s* %s;\n' % (o_type, o_name))
            hwrite(self.tabs(1) + '// end wxGlade\n')
            tag = '<%swxGlade replace %s attributes>' % (self.nonce, code_obj.klass)
            if prev_src.header_content.find(tag) < 0:
                # no attributes tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade attributes block not found for %s, attributes "
                    "declarations code NOT generated" % code_obj.name
                    )
            else:
                prev_src.header_content = prev_src.header_content.\
                                          replace(tag, "".join(header_buffer))

            header_buffer = []
            hwrite = header_buffer.append
            # ALB 2004-12-08 event handling
            if event_handlers:
                already_there = prev_src.event_handlers.get(code_obj.klass, {})
                t = self.tabs(1)
                for tpl in event_handlers:
                    if len(tpl) == 4:
                        win_id, event, handler, evt_type = tpl
                    else:
                        win_id, event, handler = tpl
                        evt_type = 'wxCommandEvent'
                    if handler not in already_there:
                        # Sebastien JEFFROY & Steve MULLER contribution :
                        # Adding virtual attribute permits to derivate from the
                        # class generated by wxGlade
                        hwrite(t + 'virtual void %s(%s &event); // wxGlade: '
                               '<event_handler>\n' % (handler, evt_type))
                        already_there[handler] = 1
                if code_obj.klass not in prev_src.event_table_def:
                    hwrite('\nprotected:\n')
                    hwrite(self.tabs(1) + 'DECLARE_EVENT_TABLE()\n')
            tag = '<%swxGlade event_handlers %s>' % (self.nonce, code_obj.klass)
            if prev_src.header_content.find(tag) < 0:
                # no attributes tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade events block not found for %s, event table code "
                    "NOT generated" % code_obj.name
                    )
            else:
                prev_src.header_content = prev_src.header_content.\
                                          replace(tag, "".join(header_buffer))

        # source file
        # set the window's style
        prop = code_obj.properties
        style = prop.get("style", None)
        if style:
            sign_inst = sign_inst.replace('style', '%s' % style)

        # constructor
        if is_new:
            base = "%s(%s)" % (code_obj.base, sign_inst)
            if custom_base:
                bases = [b.strip() for b in custom_base.split(',')]
                if bases:
                    base = "%s(%s)" % (bases[0], sign_inst)
                    rest = ", ".join([b + "()" for b in bases[1:]])
                    if rest:
                        base += ", " + rest

            swrite('\n%s::%s(%s):\n%s%s\n{\n' % (code_obj.klass,
                                                 code_obj.klass,
                                                 sign_decl2,
                                                 self.tabs(1),
                                                 base))
        swrite(self.tabs(1) + '// begin wxGlade: %s::%s\n' % (code_obj.klass,
                                                         code_obj.klass))

        tab = self.tabs(1)
        init_lines = self.classes[code_obj.klass].init
        parents_init = self.classes[code_obj.klass].parents_init
        parents_init.reverse()
        for l in parents_init:
            swrite(tab + l)
        for l in init_lines:
            swrite(tab + l)

        # now check if there are extra lines to add to the constructor
        if hasattr(builder, 'get_init_code'):
            for l in builder.get_init_code(code_obj):
                swrite(tab + l)

        swrite(self.tmpl_ctor_call_layout % {
            'tab': tab,
            })

        # end tag
        swrite('%s%s end wxGlade\n' % (tab, self.comment_sign))

        # write class function end statement
        if self.tmpl_cfunc_end and is_new:
            swrite(self.tmpl_cfunc_end % {
                'tab': tab,
                })

        # replace code inside existing constructor block
        if prev_src and not is_new:
            # replace the lines inside the ctor wxGlade block
            # with the new ones
            tag = '<%swxGlade replace %s %s>' % (self.nonce, code_obj.klass,
                                                 code_obj.klass)
            if prev_src.source_content.find(tag) < 0:
                # no constructor tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade %s::%s block not found, relative code NOT "
                    "generated" % (code_obj.klass, code_obj.klass)
                    )
            else:
                prev_src.source_content = prev_src.source_content.\
                                          replace(tag, "".join(source_buffer))
            source_buffer = []
            swrite = source_buffer.append

        # generate code for __set_properties()
        code_lines = self.generate_code_set_properties(
            builder,
            code_obj,
            is_new,
            tab
            )
        source_buffer.extend(code_lines)

        # replace code inside existing __set_properties() function
        if prev_src and not is_new:
            # replace the lines inside the set_properties wxGlade block
            # with the new ones
            tag = '<%swxGlade replace %s set_properties>' % (self.nonce, code_obj.klass)
            if prev_src.source_content.find(tag) < 0:
                # no set_properties tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade %s::set_properties block not found, relative "
                    "code NOT generated" % code_obj.klass
                    )
            else:
                prev_src.source_content = prev_src.source_content.\
                                          replace(tag, "".join(source_buffer))
            source_buffer = []
            swrite = source_buffer.append

        # generate code for __do_layout()
        code_lines = self.generate_code_do_layout(
            builder,
            code_obj,
            is_new,
            tab
            )
        source_buffer.extend(code_lines)

        # replace code inside existing do_layout() function
        if prev_src and not is_new:
            # replace the lines inside the do_layout wxGlade block
            # with the new ones
            tag = '<%swxGlade replace %s %s>' % (self.nonce, code_obj.klass,
                                                 'do_layout')
            if prev_src.source_content.find(tag) < 0:
                # no do_layout tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade do_layout block not found for %s, do_layout "
                    "code NOT generated" % code_obj.name
                    )
            else:
                prev_src.source_content = prev_src.source_content.\
                                          replace(tag, "".join(source_buffer))
            source_buffer = []
            swrite = source_buffer.append

        # generate code for event table
        code_lines = self.generate_code_event_table(
            code_obj,
            is_new,
            tab,
            prev_src,
            event_handlers,
            )
                              
        if prev_src and not is_new:
            tag = '<%swxGlade replace %s event_table>' % (self.nonce, code_obj.klass)
            if prev_src.source_content.find(tag) < 0:
                # no constructor tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade %s::event_table block not found, relative "
                    "code NOT generated" % code_obj.klass
                    )
            else:
                prev_src.source_content = prev_src.source_content.replace(
                    tag,
                    "".join(code_lines),
                    )
        else:
            source_buffer.extend(code_lines)

        # generate code for event handler stubs
        code_lines = self.generate_code_event_handler(
            code_obj,
            is_new,
            tab,
            prev_src,
            event_handlers,
            )

        # replace code inside existing event handlers
        if prev_src and not is_new:
            tag = '<%swxGlade add %s event handlers>' % \
                  (self.nonce, code_obj.klass)
            if prev_src.source_content.find(tag) < 0:
                # no constructor tag found, issue a warning and do nothing
                self.warning(
                    "wxGlade %s event handlers marker not found, relative "
                    "code NOT generated" % code_obj.klass
                    )
            else:
                prev_src.source_content = prev_src.source_content.replace(
                    tag,
                    "".join(code_lines),
                    )
        else:
            source_buffer.extend(code_lines)

        # the code has been generated
        self.classes[code_obj.klass].done = True

        if not self.multiple_files and prev_src:
            # if this is a new class, add its code to the new_classes list of the
            # SourceFileContent instance
            if is_new:
                prev_src.new_classes.append(
                    ("".join(header_buffer), "".join(source_buffer))
                    )
            return

        if self.multiple_files:
            if code_obj.base in self.obj_builders:
                self.classes[code_obj.klass].dependencies.extend(
                    getattr(self.obj_builders[code_obj.base], 'extra_headers', []))
            if prev_src:
                tag = '<%swxGlade insert new_classes>' % self.nonce
                prev_src.header_content = prev_src.header_content.replace(tag, "")

                # insert the module dependencies of this class
                extra_modules = self.classes[code_obj.klass].dependencies
                #print 'extra_modules:', extra_modules, code_obj.base
                # WARNING: there's a double space '  ' between 'replace' and
                # 'dependencies' in the tag below, because there is no class name
                # (see SourceFileContent, line ~147)
                tag = '<%swxGlade replace  dependencies>' % self.nonce
                code = self._format_dependencies(extra_modules)
                prev_src.header_content = prev_src.header_content.\
                                          replace(tag, code)

                # insert the extra code of this class
                extra_code_h = "".join(self.classes[code_obj.klass].extra_code_h[::-1])
                extra_code_cpp = \
                               "".join(self.classes[code_obj.klass].extra_code_cpp[::-1])
                # if there's extra code but we are not overwriting existing
                # sources, warn the user
                if extra_code_h or extra_code_cpp:
                    self.warning(
                        '%s (or one of its chilren) has extra code classes, '
                        'but you are not overwriting existing sources: please '
                        'check that the resulting code is correct!' % \
                        code_obj.name
                        )

                extra_code_h   = self._tagcontent("::extracode", extra_code_h)
                extra_code_cpp = self._tagcontent("::extracode", extra_code_cpp)
                tag = '<%swxGlade replace  extracode>' % self.nonce
                prev_src.header_content = prev_src.header_content.replace(
                    tag, extra_code_h)
                prev_src.source_content = prev_src.source_content.replace(
                    tag, extra_code_cpp)

                # store the new file contents to disk
                name = os.path.join(self.out_dir, code_obj.klass)
                self.save_file(
                    name + self.header_extension,
                    prev_src.header_content,
                    content_only=True
                    )
                self.save_file(
                    name + self.source_extension,
                    prev_src.source_content,
                    content_only=True
                    )

                return

            # create the new source file
            header_file = os.path.join(self.out_dir, code_obj.klass + self.header_extension)
            source_file = os.path.join(self.out_dir, code_obj.klass + self.source_extension)
            hout = cStringIO.StringIO()
            sout = cStringIO.StringIO()

            # header file
            hwrite = hout.write

            # isolation directives
            hn = os.path.basename(header_file).upper().replace('.', '_')
            hwrite('#ifndef %s\n#define %s\n' % (hn, hn))
            hwrite('\n')

            # write the common lines
            for line in self.header_lines:
                hwrite(line)
            hwrite('\n')

            # write the module dependecies for this class
            #extra_headers = classes[code_obj.klass].dependencies
            extra_modules = self.classes[code_obj.klass].dependencies
            code = self._format_dependencies(extra_modules)
            hwrite(code)
            hwrite('\n')

            # insert the extra code of this class
            extra_code_h = "".join(self.classes[code_obj.klass].extra_code_h[::-1])
            extra_code_h = self._tagcontent('::extracode', extra_code_h)
            hwrite(extra_code_h)
            hwrite('\n')

            # write the class body
            for line in header_buffer:
                hwrite(line)
            hwrite('\n#endif // %s\n' % hn)

            # source file
            swrite = sout.write
            # write the common lines
            #for line in self.header_lines:
            #    swrite(line)
            swrite(self.header_lines[0])
            swrite('#include "%s"\n\n' % os.path.basename(header_file))

            # insert the extra code of this class
            extra_code_cpp = "".join(self.classes[code_obj.klass].extra_code_cpp[::-1])
            extra_code_cpp = self._tagcontent('::extracode', extra_code_cpp)
            swrite(extra_code_cpp)
            swrite('\n')

            # write the class implementation
            for line in source_buffer:
                swrite(line)

            # store source to disk
            self.save_file(header_file, hout.getvalue())
            self.save_file(source_file, sout.getvalue())

            hout.close()
            sout.close()

        else:  # not self.multiple_files
            # write the class body onto the single source file
            hwrite = self.output_header.write
            for line in header_buffer:
                hwrite(line)
            swrite = self.output_file.write
            for line in source_buffer:
                swrite(line)

    def add_object(self, top_obj, sub_obj):
        # get top level source code object and the widget builder instance
        klass, builder = self._add_object_init(top_obj, sub_obj)
        if not klass or not builder:
            return

        try:
            init, ids, props, layout = builder.get_code(sub_obj)
        except:
            print sub_obj
            raise  # this shouldn't happen

        if sub_obj.in_windows:  # the object is a wxWindow instance
            if sub_obj.is_container and not sub_obj.is_toplevel:
                init.reverse()
                klass.parents_init.extend(init)
            else:
                klass.init.extend(init)
            if hasattr(builder, 'get_events'):
                klass.event_handlers.extend(builder.get_events(sub_obj))
            elif 'events' in sub_obj.properties:
                id_name, id = self.generate_code_id(sub_obj)
                for event, handler in sub_obj.properties['events'].iteritems():
                    klass.event_handlers.append((id, event, handler))
            # try to see if there's some extra code to add to this class
            extra_code = getattr(builder, 'extracode',
                                 sub_obj.properties.get('extracode', ""))
            if extra_code:
                extra_code = re.sub(r'\\n', '\n', extra_code)
                extra_code = re.split(re.compile(r'^###\s*$', re.M),
                                      extra_code, 1)
                klass.extra_code_h.append(extra_code[0])
                if len(extra_code) > 1:
                    klass.extra_code_cpp.append(extra_code[1])
                # if we are not overwriting existing source, warn the user
                # about the presence of extra code
                if not self.multiple_files and self.previous_source:
                    self.warning(
                        '%s has extra code, but you are not '
                        'overwriting existing sources: please check '
                        'that the resulting code is correct!' % \
                        sub_obj.name
                        )

            klass.ids.extend(ids)
            if sub_obj.klass != 'spacer':
                # attribute is a special property which control whether
                # sub_obj must be accessible as an attribute of top_obj,
                # or as a local variable in the do_layout method
                if self.test_attribute(sub_obj):
                    klass.sub_objs.append((sub_obj.klass, sub_obj.name))
        else:  # the object is a sizer
            # ALB 2004-09-17: workaround (hack) for static box sizers...
            if sub_obj.base == 'wxStaticBoxSizer':
                klass.sub_objs.insert(0, ('wxStaticBox',
                                          '%s_staticbox' % sub_obj.name))
                klass.parents_init.insert(1, init.pop(0))
            if self.test_attribute(sub_obj):
                klass.sub_objs.append((sub_obj.klass, sub_obj.name))
            klass.sizers_init.extend(init)

        klass.props.extend(props)
        klass.layout.extend(layout)
        if self.multiple_files and \
               (sub_obj.is_toplevel and sub_obj.base != sub_obj.klass):
            #print top_obj.name, sub_obj.name
            klass.dependencies.append(sub_obj.klass)
        else:
            if sub_obj.base in self.obj_builders:
                headers = getattr(self.obj_builders[sub_obj.base],
                                  'extra_headers', [])
                klass.dependencies.extend(headers)

    def generate_code_event_handler(self, code_obj, is_new, tab, prev_src, \
                                    event_handlers):
        """\
        Generate the event handler stubs
        
        @param code_obj: Object to generate code for
        @type code_obj:  Instance of L{CodeObject}

        @param is_new: Indicates if previous source code exists
        @type is_new:  Boolean

        @param tab: Indentation of function body
        @type tab:  String
        
        @param prev_src: Previous source code
        @type prev_src: Instance of L{SourceFileContent}
        
        @param event_handlers: List of event handlers
        
        @rtype: List of strings
        @see: L{tmpl_func_event_stub}
        """
        code_lines = []
        swrite = code_lines.append
        
        if not event_handlers:
            return []
            
        tmpl_handler = """
void %(klass)s::%(handler)s(%(evt_type)s &event)
{
%(tab)sevent.Skip();
%(tab)s// notify the user that he hasn't implemented the event handler yet
%(tab)swxLogDebug(wxT("Event handler (%(klass)s::%(handler)s) not implemented yet"));
}
"""
        
        if prev_src:
            already_there = prev_src.event_handlers.get(code_obj.klass, {})
        else:
            already_there = {}
        for tpl in event_handlers:
            if len(tpl) == 4:
                win_id, event, handler, evt_type = tpl
            else:
                win_id, event, handler = tpl
                evt_type = 'wxCommandEvent'
            if handler not in already_there:
                swrite(tmpl_handler % {
                    'evt_type': evt_type,
                    'handler': handler,
                    'klass': code_obj.klass,
                    'tab': tab,
                    })
                already_there[handler] = 1
        if is_new or not prev_src:
            swrite('\n\n')
        swrite('// wxGlade: add %s event handlers\n' % code_obj.klass)
        if is_new or not prev_src:
            swrite('\n')
        
        return code_lines

    def generate_code_event_table(self, code_obj, is_new, tab, prev_src,
                                  event_handlers):
        """\
        Generate code for event table declaration.
        
        @param code_obj: Object to generate code for
        @type code_obj:  Instance of L{CodeObject}

        @param is_new: Indicates if previous source code exists
        @type is_new:  Boolean

        @param tab: Indentation of function body
        @type tab:  String
        
        @param prev_src: Previous source code
        @type prev_src: Instance of L{SourceFileContent}
        
        @param event_handlers: List of event handlers
        
        @rtype: List of strings
        """
        code_lines = []
        swrite = code_lines.append
        
        if not event_handlers:
            return []
            
        if prev_src and code_obj.klass in prev_src.event_table_decl:
            has_event_table = True
        else:
            has_event_table = False
        if is_new or not has_event_table:
            swrite('\nBEGIN_EVENT_TABLE(%s, %s)\n' % \
                  (code_obj.klass, code_obj.base))
        swrite(tab + '// begin wxGlade: %s::event_table\n' % code_obj.klass)
        for tpl in event_handlers:
            win_id, event, handler = tpl[:3]
            swrite(tab + '%s(%s, %s::%s)\n' % \
                   (event, win_id, code_obj.klass, handler))
        swrite(tab + '// end wxGlade\n')
        if is_new or not has_event_table:
            swrite('END_EVENT_TABLE();\n\n')

        return code_lines

    def generate_code_id(self, obj, id=None):
        if id is None:
            id = obj.properties.get('id')
        if not id:
            return '', 'wxID_ANY'
        tokens = id.split('=', 1)
        if len(tokens) == 2:
            name, val = tokens
        else:
            return '', tokens[0]   # we assume name is declared elsewhere
        if not name:
            return '', val
        name = name.strip()
        val = val.strip()
        if val == '?':
            val = 'wxID_HIGHEST + %d' % self.last_generated_id
            self.last_generated_id += 1
        else:
            val = val
        return '%s = %s' % (name, val), name

    def generate_code_size(self, obj):
        objname = self._get_code_name(obj)
        if obj.is_toplevel:
            name2 = 'this'
        else:
            name2 = obj.name
        size = obj.properties.get('size', '').strip()
        use_dialog_units = (size[-1] == 'd')
        if not obj.parent:
            method = 'SetSize'
        else:
            method = 'SetMinSize'
        if use_dialog_units:
            return '%s%s(wxDLG_UNIT(%s, wxSize(%s)));\n' % \
                   (objname, method, name2, size[:-1])
        else:
            return '%s%s(wxSize(%s));\n' % (objname, method, size)

    def get_events_with_type(self, obj, evt_type):
        """\
        Returns the list of event handlers defined for `obj', setting the type
        of the argument of the handlers (i.e. the event parameter) to
        `evt_type'
        """
        ret = []
        if 'events' not in obj.properties:
            return ret
        id_name, id = self.generate_code_id(obj)
        for event, handler in obj.properties['events'].iteritems():
            ret.append((id, event, handler, evt_type))
        return ret

    def quote_str(self, s, translate=True, escape_chars=True):
        if not s:
            return 'wxEmptyString'
        s = s.replace('"', r'\"')
        if escape_chars:
            s = self._quote_str_pattern.sub(self._do_replace, s)
        else:
            s = s.replace('\\', r'\\')  # just quote the backslashes
        if self._use_gettext and translate:
            return '_("%s")' % s
        else:
            return 'wxT("%s")' % s

    def _get_code_name(self, obj):
        if obj.is_toplevel:
            return ''
        else:
            return '%s->' % obj.name

    def _unique(self, sequence):
        """\
        Strips all duplicates from sequence. Works only if items of sequence
        are hashable
        """
        tmp = {}
        for item in sequence:
            tmp[item] = 1
        return tmp.keys()

    def _format_dependencies(self, dependencies):
        """\
        Format the dependecies output

        @param dependencies: List if header files
        @type dependencies:  List of strings

        @return: Changed content
        @rtype:  String

        @see: L{_tagcontent()}
        """
        dep_list = []
        for dependency in self._unique(dependencies):
            if dependency and ('"' != dependency[0] != '<'):
                dep_list.append('#include "%s.h"\n' % dependency)
            else:
                dep_list.append('#include %s\n' % dependency)
        code = self._tagcontent(
            '::dependencies',
            dep_list,
            )
        return code

# end of class CPPCodeWriter

writer = CPPCodeWriter()
"""\
The code writer is an instance of L{CPPCodeWriter}.
"""

language = writer.language
"""\
Language generated by this code generator
"""