boa-constructor / Editor.py

   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
#----------------------------------------------------------------------
# Name:        Editor.py
# Purpose:
#
# Author:      Riaan Booysen
#
# Created:     1999
# RCS-ID:      $Id$
# Copyright:   (c) 1999, 2000 Riaan Booysen
# Licence:     GPL
#----------------------------------------------------------------------
#Boa:Frame:EditorFrame

# The focus of change
# the center of creation
# Alchemy

from wxPython.wx import *
from wxPython.stc import *

import sys, string, time
import Preferences, About, Help
from os import path
import Utils, Browse

print 'importing Views.EditorViews'
from Views.EditorViews import *
print 'importing Views.AppViews'
from Views.AppViews import AppView, AppFindResults, AppModuleDocView, AppTimeTrackView
from Views.AppViews import AppREADME_TIFView, AppTODO_TIFView, AppBUGS_TIFView, AppCHANGES_TIFView
print 'importing Views.DesignerViews'
from Views.Designer import DesignerView
from Views.DataView import DataView
print 'importing Views.UMLViews'
from Views.OGLViews import UMLView, ImportsView
print 'importing Views.SourceViews'
from Views.PySourceView import PythonSourceView
from Views.SourceViews import HTMLSourceView, XMLSourceView, TextView, CPPSourceView, HPPSourceView, PythonDisView
print 'importing ZopeViews'
from Views.ZopeViews import ZopeHTMLView, ZopeUndoView, ZopeSecurityView
print 'importing Explorers'
from Explorers.CVSExplorer import CVSConflictsView
from Explorers import Explorer
from ZopeLib import ImageViewer

print 'importing Models'
from EditorModels import *
from PrefsKeys import keyDefs
import ShellEditor, PaletteStore, ErrorStack
from Preferences import IS, wxFileDialog, flatTools
from EditorHelper import *
from ModRunner import EVT_EXEC_FINISH

# Models available on the 'New' palette page
PaletteStore.paletteLists['New'].extend(['wxApp', 'wxFrame', 'wxDialog',
    'wxMiniFrame', 'wxMDIParentFrame', 'wxMDIChildFrame', 'Module', 'Package',
    'Setup', 'Text'])

if Utils.IsComEnabled():
    PaletteStore.paletteLists['New'].append('MakePy Dialog')

# Views associated with a model, default views and additional views
defAppModelViews = (AppView, PythonSourceView)
adtAppModelViews = (AppModuleDocView, ToDoView, ImportsView, CVSConflictsView,
                    AppTimeTrackView, AppREADME_TIFView, AppCHANGES_TIFView,
                    AppTODO_TIFView, AppBUGS_TIFView)

defModModelViews = (PythonSourceView, ExploreView)
adtModModelViews = (HierarchyView, ModuleDocView, ToDoView, UMLView,
                    CVSConflictsView, PythonDisView)

defBaseFrameModelViews = (PythonSourceView, ExploreView)
adtBaseFrameModelViews = (HierarchyView, ModuleDocView, ToDoView, UMLView,
                          CVSConflictsView, PythonDisView)

defPackageModelViews = (PackageView, PythonSourceView)
adtPackageModelViews = (CVSConflictsView,)

defTextModelViews = (TextView,)
adtTextModelViews = ()

defHTMLFileModelViews = (HTMLSourceView,)
adtHTMLFileModelViews = (HTMLFileView,)

defXMLFileModelViews = (XMLSourceView,)
try:
    from Views.XMLView import XMLTreeView
    adtXMLFileModelViews = (XMLTreeView,)
except ImportError:
    adtXMLFileModelViews = ()

defZopeDocModelViews = (HTMLSourceView,)
adtZopeDocModelViews = (ZopeHTMLView,)

defCPPModelViews = (CPPSourceView, HPPSourceView)
adtCPPModelViews = (CVSConflictsView,)

defSetupModelViews = (PythonSourceView, )
adtSetupModelViews = ()

(mmFile, mmEdit, mmViews, mmWindows, mmHelp) = range(5)

[wxID_EDITORFRAME, wxID_PAGECHANGED,
] = map(lambda _init_ctrls: wxNewId(), range(2))

class EditorFrame(wxFrame):
    """ Source code editor and Mode/View controller"""

    openBmp = 'Images/Editor/Open.bmp'
    backBmp = 'Images/Shared/Previous.bmp'
    forwBmp = 'Images/Shared/Next.bmp'
    helpBmp = 'Images/Shared/Help.bmp'

    def _init_utils(self):
        pass

    def _init_ctrls(self, prnt):
        wxFrame.__init__(self, size = (-1, -1), id = wxID_EDITORFRAME, title = 'Editor', parent = prnt, name = '', style = wxDEFAULT_FRAME_STYLE | wxCLIP_CHILDREN, pos = (-1, -1))

    def __init__(self, parent, id, inspector, newMenu, componentPalette, app):
        self._init_ctrls(parent)
        self._init_utils()
        self.SetDimensions(Preferences.inspWidth + Preferences.windowManagerSide*2,
              Preferences.paletteHeight + Preferences.windowManagerTop + \
              Preferences.windowManagerBottom, Preferences.edWidth,
              Preferences.bottomHeight)
        EVT_CLOSE(self, self.OnCloseWindow)

        if wxPlatform == '__WXMSW__':
            self.SetIcon(IS.load('Images/Icons/Editor.ico'))

        self.app = app
        self.palette = parent
        self.modules = {}
        self.inspector = inspector
        self.compPalette = componentPalette
        self.debugger = None
        self.browser = Browse.Browser()

        self.statusBar = EditorStatusBar(self)
        self.SetStatusBar(self.statusBar)

        # 16 (FxdWdth), 32 (lft), 64 (rght), 128 (btm)
        self.tabs = wxNotebook(self, wxID_PAGECHANGED, style = wxCLIP_CHILDREN)#, style = wxTC_MULTILINE)
        EVT_NOTEBOOK_PAGE_CHANGED(self.tabs, wxID_PAGECHANGED, self.OnPageChange)

        self.modelImageList = wxImageList(16, 16)

        # Build imagelist of all models
        print 'Editor (loading images)'
        orderedModList = []
        for mod in modelReg.values(): orderedModList.append((mod.imgIdx, mod))
        orderedModList.sort()
        for mod in orderedModList:
            self.modelImageList.Add(IS.load('Images/Modules/'+mod[1].bitmap))

        self.modelImageList.Add(IS.load('Images/Modules/Folder_s.bmp'))
        self.modelImageList.Add(IS.load('Images/Modules/Folder_green_s.bmp'))
        self.modelImageList.Add(IS.load('Images/Modules/Folder_cyan_s.bmp'))
##        self.modelImageList.Add(IS.load('Images/Zope/Folder_icon.bmp'))
##        self.modelImageList.Add(IS.load('Images/Zope/ControlPanel_icon.bmp'))
##        self.modelImageList.Add(IS.load('Images/Zope/ProductFolder_icon.bmp'))
##        self.modelImageList.Add(IS.load('Images/Zope/InstalledProduct_icon.bmp'))
##        self.modelImageList.Add(IS.load('Images/Zope/UserFolder_icon.bmp'))
##        self.modelImageList.Add(IS.load('Images/Zope/dtmldoc.bmp'))
##        self.modelImageList.Add(IS.load('Images/Zope/Image_icon.bmp'))
        self.modelImageList.Add(IS.load('Images/Zope/System_obj.bmp'))
        self.modelImageList.Add(IS.load('Images/Zope/Zope_connection.bmp'))
        self.modelImageList.Add(IS.load('Images/Shared/BoaLogo.bmp'))
        self.modelImageList.Add(IS.load('Images/Modules/FolderUp_s.bmp'))
        self.modelImageList.Add(IS.load('Images/Modules/Drive_s.bmp'))
        self.modelImageList.Add(IS.load('Images/Modules/FolderBookmark_s.bmp'))

        # Add Zoa Images
        import ZopeEditorModels
        for metatype, filename in ZopeEditorModels.ZOAImages:
            ZopeEditorModels.ZOAIcons[metatype] = \
                  self.modelImageList.Add(IS.load(filename))

        if wxPlatform == '__WXMSW__':
            self.tabs.SetImageList(self.modelImageList)

        # Shell
        self.shell = self.addShellPage()

        # Explorer
        self.explorer = Explorer.ExplorerSplitter (self.tabs,
          self.modelImageList, '', self)
        self.tabs.AddPage(self.explorer, 'Explorer')
        self.tabs.SetSelection(1)

        # Menus
        self.newMenu = newMenu

        self.blankEditMenu = wxMenu()
        self.blankViewMenu = wxMenu()
        self.helpMenu = wxMenu()
        self.helpMenu.Append(wxID_EDITORHELP, 'Help')
        self.helpMenu.Append(wxID_EDITORHELPGUIDE, 'Getting started guide')
        self.helpMenu.Append(wxID_EDITORHELPTIPS, 'Tips')
        self.helpMenu.AppendSeparator()
        self.helpMenu.Append(wxID_EDITORHELPABOUT, 'About')

        EVT_MENU(self, wxID_EDITORHELP, self.OnHelp)
        EVT_MENU(self, wxID_EDITORHELPABOUT, self.OnHelpAbout)
        EVT_MENU(self, wxID_EDITORHELPGUIDE, self.OnHelpGuide)
        EVT_MENU(self, wxID_EDITORHELPTIPS, self.OnHelpTips)

        EVT_MENU(self, wxID_EDITOROPEN, self.OnOpen)

        # XXX These methods and events should be refactored into controllers
        # XXX that can link to certain models

        EVT_MENU(self, wxID_EDITORSAVE, self.OnSave)
        EVT_MENU(self, wxID_EDITORSAVEAS, self.OnSaveAs)
        EVT_MENU(self, wxID_EDITORCLOSEPAGE, self.OnClosePage)
        EVT_MENU(self, wxID_EDITORRELOAD, self.OnReload)

        EVT_MENU(self, wxID_EDITORREFRESH, self.OnRefresh)
        EVT_MENU(self, wxID_EDITORDESIGNER, self.OnDesigner)
        EVT_MENU(self, wxID_EDITORDEBUG, self.OnDebug)

        EVT_MENU(self, wxID_EDITORSWITCHAPP, self.OnSwitchApp)
        EVT_MENU(self, wxID_EDITORSWITCHSHELL, self.OnSwitchShell)
        EVT_MENU(self, wxID_EDITORSWITCHEXPLORER, self.OnSwitchExplorer)
        EVT_MENU(self, wxID_EDITORSWITCHPALETTE, self.OnSwitchPalette)
        EVT_MENU(self, wxID_EDITORSWITCHINSPECTOR, self.OnSwitchInspector)

        EVT_MENU(self, wxID_EDITORDIFF, self.OnDiff)
        EVT_MENU(self, wxID_EDITORCMPAPPS, self.OnCmpApps)
        EVT_MENU(self, wxID_EDITORPYCHECK, self.OnPyChecker)
        EVT_MENU(self, wxID_EDITORCONFPYCHECK, self.OnConfPyChecker)

        EVT_MENU(self, wxID_EDITORPREVPAGE, self.OnPrevPage)
        EVT_MENU(self, wxID_EDITORNEXTPAGE, self.OnNextPage)

        EVT_MENU(self, wxID_SETUPBUILD, self.OnSetupBuild)
        EVT_MENU(self, wxID_SETUPCLEAN, self.OnSetupClean)
        EVT_MENU(self, wxID_SETUPINSTALL, self.OnSetupInstall)
        EVT_MENU(self, wxID_SETUPSDIST, self.OnSetupSDist)
        EVT_MENU(self, wxID_SETUPBDIST, self.OnSetupBDist)
        EVT_MENU(self, wxID_SETUPBDIST_WININST, self.OnSetupBDist_WinInst)
        EVT_MENU(self, wxID_SETUPPY2EXE, self.OnSetupPy2Exe)

        self.mainMenu = wxMenuBar()
        self.SetMenuBar(self.mainMenu)
        self.mainMenu.Append(wxMenu(), 'File')
#        self.mainMenu.Append(self.blankEditMenu, 'Edit')
        self.mainMenu.Append(wxMenu(), 'Edit')

        # Views menu
        self.viewDefaultIds = {}
        self.viewDefaults = wxMenu()
        self.viewDefaults.AppendMenu(wxNewId(), AppModel.modelIdentifier,
          self.defsMenu(AppModel, adtAppModelViews))
        self.viewDefaults.AppendMenu(wxNewId(), BaseFrameModel.modelIdentifier,
          self.defsMenu(BaseFrameModel, adtBaseFrameModelViews))
        self.viewDefaults.AppendMenu(wxNewId(), ModuleModel.modelIdentifier,
          self.defsMenu(ModuleModel, adtModModelViews))
        self.viewDefaults.AppendMenu(wxNewId(), PackageModel.modelIdentifier,
          self.defsMenu(PackageModel, adtPackageModelViews))
        self.viewDefaults.AppendMenu(wxNewId(), TextModel.modelIdentifier,
          self.defsMenu(TextModel, adtTextModelViews))

        self.blankViewMenu.AppendMenu(wxID_DEFAULTVIEWS, 'Defaults', self.viewDefaults)

        self.mainMenu.Append(wxMenu(), 'Views')
#        self.mainMenu.Append(self.blankViewMenu, 'Views')

        # Windows menu
        self.winMenu = wxMenu()
        self.winMenu.Append(wxID_EDITORSWITCHPALETTE, 'Palette')
        self.winMenu.Append(wxID_EDITORSWITCHINSPECTOR, 'Inspector')
        self.winMenu.Append(-1, '-')
        self.winMenu.Append(wxID_EDITORSWITCHSHELL, 'Shell')
        self.winMenu.Append(wxID_EDITORSWITCHEXPLORER, 'Explorer')
        self.winMenu.Append(-1, '-')
        self.mainMenu.Append(self.winMenu, 'Windows')

        self.mainMenu.Append(self.helpMenu, 'Help')

        self.defaultAdtViews = {}
##        {AppModel: [], BaseFrameModel: [],
##                                ModuleModel: [], PackageModel: [], TextModel: [],
##                                ZopeDocumentModel: [], CPPModel: [],
##                                HTMLFileModel: []}

        # Toolbar
        self.toolBar = EditorToolBar(self, -1)#, style = wxTB_HORIZONTAL|wxNO_BORDER|wxTB_FLAT)#|wxTB_FLAT
        self.SetToolBar(self.toolBar)
        self.setupToolBar(viewIdx = 0)

        tree = self.explorer.tree
        if tree.defaultBookmarkItem:
            ws = tree.getChildNamed(tree.GetRootItem(), 'Bookmarks')
#        self.defaultBookmarkItem = self.getChildNamed(ws, self.boaRoot.entries[1].getDefault())
#            self.getChildNamed(ws, tree.boaRoot.entries[1].getDefault())
            tree.SelectItem(tree.getChildNamed(ws, tree.boaRoot.entries[1].getDefault()))
#            self.explorer.tree.defaultBookmarkItem)

#            print 'Setting default', self.explorer.tree.defaultBookmarkItem
#            self.explorer.tree.SelectItem(self.explorer.tree.defaultBookmarkItem)
#            print 'Set def', self.explorer.tree.GetSelection()

            if self.explorer.list.GetItemCount():
                item = self.explorer.list.GetItem(0)
                item.SetState(wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED)
                self.explorer.list.SetItem(item)

        dt = Utils.BoaFileDropTarget(self)
        self.SetDropTarget(dt)

        self.explorer.list.SetFocus()

        import ErrorStackFrm
        self.erroutFrm = ErrorStackFrm.ErrorStackMF(self, self)

        # Hack to feed BoaFileDialog images
        import FileDlg
        FileDlg.wxBoaFileDialog.modImages = self.modelImageList

        EVT_EXEC_FINISH(self, self.OnExecFinish)

        self.restoreEditorState()

    def defsMenu(self, model, viewClss):
        """ Default menus specifying which views are opened by default when a
            certain type of model is opened.
        """

        menu = wxMenu()
        for view in viewClss:
            wId = wxNewId()
            self.viewDefaultIds[wId] = view, model
            menu.Append(wId, view.viewName, checkable = true)
            menu.Check(wId, false)
            EVT_MENU(self, wId, self.OnDefaultsToggle)
        return menu

    def setupToolBar(self, modelIdx = None, viewIdx = None):
        if not hasattr(self, 'toolBar') or self.palette.destroying:
            return

        self.toolBar.ClearTools()

        accLst = []
        for (ctrlKey, key, code), wId in \
                ( (keyDefs['Inspector'], wxID_EDITORSWITCHINSPECTOR),
                  (keyDefs['Open'], wxID_EDITOROPEN),
                  (keyDefs['PrevPage'], wxID_EDITORPREVPAGE),
                  (keyDefs['NextPage'], wxID_EDITORNEXTPAGE) ):
            accLst.append( (ctrlKey, key, wId) )

        # primary option: open a module
        fileMenu = wxMenu()
        fileMenu.Append(wxID_EDITOROPEN, 'Open', 'Open a module')

        Utils.AddToolButtonBmpObject(self, self.toolBar, IS.load(self.openBmp), 'Open a module', self.OnOpen)
        self.bbId = Utils.AddToolButtonBmpObject(self, self.toolBar, IS.load(self.backBmp), 'Browse back', self.OnBrowseBack)
        self.bfId = Utils.AddToolButtonBmpObject(self, self.toolBar, IS.load(self.forwBmp), 'Browse forward', self.OnBrowseForward)
        actMod = self.getActiveModulePage(modelIdx)
        if actMod:
            activeView = actMod.getActiveView(viewIdx)
            if activeView:
                # File menu
                actMod.model.addTools(self.toolBar)
                accls = actMod.model.addMenus(fileMenu)
                accLst.extend(accls)
                self.mainMenu.Replace(mmFile, fileMenu, 'File').Destroy()
                # Edit menu
                self.toolBar.AddSeparator()
                activeView = actMod.getActiveView(viewIdx)
                activeView.addViewTools(self.toolBar)
                menu, accls = activeView.editorMenu, activeView.accelLst
                menu = Utils.duplicateMenu(menu)
                self.mainMenu.Replace(mmEdit, menu, 'Edit').Destroy()
                accLst.extend(accls)

                # Views menu
                # XXX Should only recalculate when module switches
                actMod.setActiveViewsMenu()

##                menu.AppendSeparator()
##                menu.AppendMenu(wxID_DEFAULTVIEWS, 'Defaults', self.viewDefaults)
##                m = self.mainMenu.GetMenu(mmViews)
##                if m.GetMenuItemCount() > 0:
##                    m.RemoveItem(m.FindItemById(wxID_DEFAULTVIEWS))

                menu = Utils.duplicateMenu(actMod.viewMenu)
                self.mainMenu.Replace(mmViews, menu, 'Views').Destroy()
#                self.mainMenu.Replace(mmViews, actMod.viewMenu, 'Views')
        else:
            if modelIdx == 1:
                self.explorer.addTools(self.toolBar)
                menu = self.explorer.getMenu()
                if menu:
                    self.mainMenu.Replace(mmEdit, Utils.duplicateMenu(menu), 'Edit').Destroy()
                else:
                    self.mainMenu.Replace(mmEdit, Utils.duplicateMenu(self.blankEditMenu), 'Edit').Destroy()
            else:
                self.mainMenu.Replace(mmEdit, Utils.duplicateMenu(self.blankEditMenu), 'Edit').Destroy()
            self.mainMenu.Replace(mmFile, fileMenu, 'File').Destroy()
#            self.mainMenu.Replace(mmEdit, self.blankEditMenu, 'Edit')

##            m = self.mainMenu.GetMenu(mmViews)
##            if m.GetMenuItemCount() > 0:
##                m.RemoveItem(m.FindItemById(wxID_DEFAULTVIEWS))

            self.mainMenu.Replace(mmViews, Utils.duplicateMenu(self.blankViewMenu), 'Views').Destroy()

        # Help button
        self.toolBar.AddSeparator()
        Utils.AddToolButtonBmpObject(self, self.toolBar, IS.load(self.helpBmp), 'Help', self.OnHelp)

        self.toolBar.Realize()

        self.updateBrowserBtns()

        if accLst: self.SetAcceleratorTable(wxAcceleratorTable(accLst))
#        print 'end setup toolbar',

    def updateBrowserBtns(self):
        self.toolBar.EnableTool(self.bbId, self.browser.canBack())
        self.toolBar.EnableTool(self.bfId, self.browser.canForward())

    def addShellPage(self):
        """ Adds the interactive interpreter to the editor """
        if wxPlatform == '__WXGTK__':
            # A panel between the STC and notebook reduces flicker
            shellEdit, dummy = Utils.wxProxyPanel(self.tabs, ShellEditor.ShellEditor, -1)

##            panel = wxPanel(self.tabs, -1, style=wxTAB_TRAVERSAL | wxCLIP_CHILDREN)
##            shellEdit = ShellEditor.ShellEditor(panel, -1)
##            def OnWinSize(evt, win=shellEdit):
##                win.SetSize(evt.GetSize())
##            EVT_SIZE(panel, OnWinSize)
##            self.tabs.AddPage(panel, 'Shell')
        else:
            shellEdit = ShellEditor.ShellEditor(self.tabs, -1)

        self.tabs.AddPage(shellEdit, 'Shell')

        return shellEdit

    def getValidName(self, modelClass, moreUsedNames = None):
        if moreUsedNames is None:
            moreUsedNames = []
        def tryName(modelClass, n):
            return '%s%d%s' %(modelClass.defaultName, n, modelClass.ext)
        n = 1
        #Obfuscated one-liner to check if such a name exists as a basename
        #in a the dict keys of self.module
        while filter(lambda key, name=tryName(modelClass, n): \
          path.basename(key) == name, self.modules.keys() + moreUsedNames):
            n = n + 1

        return tryName(modelClass, n)

    def newFileTransport(self, name, filename):
        from Explorers.FileExplorer import PyFileNode
        return PyFileNode(name, filename, None, -1, None, None,
              properties = {})

    def addModulePage(self, model, moduleName, defViews, views, imgIdx):
        spIdx = self.tabs.GetPageCount()
        modulePage = ModulePage(self.tabs, model, defViews, views, spIdx, self)
        self.modules[moduleName] = modulePage
        # Idx will be same as count after selection
        if wxPlatform == '__WXMSW__':
            self.tabs.AddPage(modulePage.notebook, modulePage.pageName, true, imgIdx)
        elif wxPlatform == '__WXGTK__':
            self.tabs.AddPage(modulePage.notebook, modulePage.pageName)
#        wxYield()

        self.tabs.SetSelection(spIdx)
        modulePage.refresh()

    def getActiveModulePage(self, page = None):
        if page is None: page = self.tabs.GetSelection()
        # this excludes shell
        if page:
            for mod in self.modules.values():
                if mod.tIdx == page:
                    return mod
        # XXX raise on not found ?
        return None

    def activeApp(self):
        actMod = self.getActiveModulePage()
        if actMod and actMod.model.__class__ == AppModel and actMod.model.data <> '':
            return actMod
        else:
            return None

    def addNewTextPage(self):
        name = self.getValidName(TextModel)
        model = TextModel('', name, self, false)
        model.transport = self.newFileTransport('', name)
        self.addModulePage(model, name, defTextModelViews, adtTextModelViews,
          TextModel.imgIdx)
        model.new()

        self.updateTitle()

    def addNewSetupPage(self):
        name = 'setup.py'
        model = SetupModuleModel(defSetup_py, name, self, false)
        model.transport = self.newFileTransport('', name)
        self.addModulePage(model, name, defSetupModelViews, adtSetupModelViews,
          SetupModuleModel.imgIdx)
        model.new()

        self.updateTitle()

    def addNewPackage(self):
        filename, success = self.saveAsDlg('__init__.py')
        if success:
            model = PackageModel('# Package initialisation', filename, self, false)
            model.transport = self.newFileTransport('', filename)
            self.addModulePage(model, model.packageName, defPackageModelViews,
              adtPackageModelViews, PackageModel.imgIdx)
            model.save()
            model.notify()

            self.updateTitle()

    def addNewAppPage(self):
        appName = self.getValidName(AppModel)
        appModel = AppModel('', appName, appName[:-3], self, false, self.modules)
        appModel.transport = self.newFileTransport(appName[:-3], appName)

        self.addModulePage(appModel, appName, defAppModelViews, adtAppModelViews,
          AppModel.imgIdx)

        frmMod = self.addNewFramePage('Frame', appModel)
        frmNme = path.splitext(path.basename(frmMod.filename))[0]
        appModel.new(frmNme)

        self.updateTitle()

    def addNewModulePage(self):
        activeApp = self.activeApp()
        if activeApp:
            activeApp = activeApp.model
            name = self.getValidName(ModuleModel, activeApp.absModulesPaths())
        else:
            name = self.getValidName(ModuleModel)

        model = ModuleModel('', name, self, false, activeApp)
        model.transport = self.newFileTransport('', name)
        self.addModulePage(model, name, defModModelViews, adtModModelViews,
          ModuleModel.imgIdx)
        model.new()
        if activeApp and Preferences.autoAddToApplication:
            activeApp.addModule(model.filename, '')

        self.updateTitle()

    def addNewFramePage(self, modId, app = None):
        FrmMod = modelReg[modId]
        if app:
            activeAppMod = app
            name = self.getValidName(FrmMod, app.absModulesPaths())
        else:
            activeAppMod = self.activeApp()
            if activeAppMod:
                activeAppMod = activeAppMod.model
                name = self.getValidName(FrmMod, activeAppMod.absModulesPaths())
            else:
                name = self.getValidName(FrmMod)

        model = FrmMod('', name, name[:-3], self, false, activeAppMod)
        model.transport = self.newFileTransport('', model.filename)

        activeApp = self.activeApp()

        self.addModulePage(model, name, defBaseFrameModelViews,
          adtBaseFrameModelViews, FrmMod.imgIdx)
        tempComp = FrmMod.companion('', None, None)
        params = tempComp.designTimeSource()
        params['parent'] = 'prnt'
        params['id'] = Utils.windowIdentifier(model.main, '')
        params['title'] = `model.main`

        model.new(params)
        if activeApp and Preferences.autoAddToApplication:
            activeApp.model.addModule(model.filename, '')

        self.updateTitle()

        return model

    def addNewDialog(self, dlgClass, dlgCompanion):
        module = self.getActiveModulePage()
        if module:
            view = module.getActiveView()
            if view and view.viewName == 'Source':
                compn = dlgCompanion('dlg', None)
                view.insertCodeBlock(compn.body())

    def getAppModules(self):
        """ Return a list of all open Application modules """
        apps = []
        for modPage in self.modules.values():
            if modPage.model.modelIdentifier == 'App':
                apps.append(modPage.model)
        return apps

    def openOrGotoModule(self, name, app=None, transport=None):
        if self.modules.has_key(name):
            self.modules[name].focus()
            return self.modules[name].model
        else:
            # Check non case sensitive (fix for breakpoints)
            lst = self.modules.keys()
            assos = {}
            for keyIdx in range(len(lst)):
                assos[path.normcase(path.abspath(lst[keyIdx]))] = lst[keyIdx]

            if assos.has_key(name):
                self.modules[assos[name]].focus()
                return self.modules[assos[name]].model
            else:
                return self.openModule(name, app, transport)

    def openModule(self, filename, app=None, transport=None):
        name = filename
        dirname, name = path.split(filename)
        name, ext = path.splitext(name)

        if not transport:
            from Explorers.FileExplorer import PyFileNode
            transport = PyFileNode(name, filename, None, -1, None, None,
                  properties = {})

        source = transport.load()
        modCls, main = identifyFile(filename, source, true)

        imgIdx = modCls.imgIdx

        if modCls is PackageModel:
            model = PackageModel(source, filename, self, true)
            defViews = defPackageModelViews
            views = adtPackageModelViews
            name = model.packageName
        elif modCls is AppModel:
            model = AppModel(source, filename, '', self, true, self.modules)
            defViews = defAppModelViews
            views = adtAppModelViews
        elif modCls in (FrameModel, DialogModel, MiniFrameModel,
          MDIParentModel, MDIChildModel):
            model = modCls(source, filename, main, self, true, app)
            defViews = defBaseFrameModelViews
            views = adtBaseFrameModelViews
        elif modCls is TextModel:
            model = TextModel(source, filename, self, true)
            defViews = defTextModelViews
            views = adtTextModelViews
        elif modCls is CPPModel:
            model = CPPModel(source, filename, self, true)
            defViews = defCPPModelViews
            views = adtCPPModelViews
        elif modCls is HTMLFileModel:
            model = HTMLFileModel(source, filename, self, true)
            defViews = defHTMLFileModelViews
            views = adtHTMLFileModelViews
        elif modCls is XMLFileModel:
            model = XMLFileModel(source, filename, self, true)
            defViews = defXMLFileModelViews
            views = adtXMLFileModelViews
        elif modCls is ConfigFileModel:
            model = ConfigFileModel(source, filename, self, true)
            defViews = defTextModelViews
            views = adtTextModelViews
        elif modCls is BitmapFileModel:
            model = BitmapFileModel(source, filename, self, true)
            ImageViewer.create(self).showImage(filename, transport)
            return model
        elif modCls is SetupModuleModel:
            model = SetupModuleModel(source, filename, self, true)
            defViews = defSetupModelViews
            views = adtSetupModelViews
        else:
            model = ModuleModel(source, filename, self, true, app)
            defViews = defModModelViews
            views = adtModModelViews

        model.transport = transport
        self.addModulePage(model, filename, defViews, views, model.imgIdx)

        model.notify()

        if wxPlatform != '__WXGTK__':
#            self.tabs.Refresh()
            self.updateTitle()

        return model

    def openOrGotoZopeDocument(self, zopeObj):
        wholename=zopeObj.whole_name()
        if self.modules.has_key(wholename):
            self.modules[wholename].focus()
            return self.modules[wholename].model
        else:
            return self.openZopeDocument(zopeObj,wholename)

    def openZopeDocument(self, zopeObj, wholename):
        if zopeObj.Model:
            model = zopeObj.Model(wholename, '', self, false, zopeObj) #zopeObj.whole_name(), '', self, false, zopeConn, zopeObj
            model.transport = zopeObj
            model.load()

            self.addModulePage(
                model, wholename, zopeObj.defaultViews,
                zopeObj.additionalViews, zopeObj.Model.imgIdx)
            model.notify()

            self.updateTitle()
            return model
        else:
            wxLogWarning('Zope Object %s not supported' % `zopeObj`)

    def showDesigner(self):
        modulePage = self.getActiveModulePage()
        if modulePage:
            model = modulePage.model

            # Just show if already opened
            if model.views.has_key('Designer'):
                model.views['Data'].focus()
                model.views['Designer'].Show(true)
                model.views['Designer'].Raise()
                return

            # update any view modifications
            model.refreshFromViews()

            model.initModule()
            model.readComponents()

            # add or focus data view
            if not model.views.has_key('Data'):
                dataView = DataView(modulePage.notebook, self.inspector,
                  model, self.compPalette)
                dataView.addToNotebook(modulePage.notebook)
                model.views['Data'] = dataView
                dataView.initialize()
            else:
                dataView = model.views['Data']
                dataView.focus()

            modulePage.notebook.SetSelection(modulePage.notebook.GetPageCount()-1)
            dataView.refreshCtrl()

            # add or focus frame designer
            if not model.views.has_key('Designer'):
                designer = DesignerView(self, self.inspector,
                  model, self.compPalette, model.companion, dataView)
                model.views['Designer'] = designer
                designer.refreshCtrl()
            model.views['Designer'].Show(true)

            # Make source read only
            model.views['Source'].disableSource(true)

    def showImportsView(self):
        self.addNewView('Imports', ImportsView)

    def addNewView(self, name, viewClass):
        module = self.getActiveModulePage()
        if module:
            if not module.model.views.has_key(name):
                return module.addView(viewClass, name)
            else:
                return module.model.views[name]
            module.model.views[name].Show(true)

    def openFileDlg(self):
#        return wxFileSelector('Choose a file', '.', '', 'Modules (*.py)|*.py|Text files (*.txt)|*.txt', '.py', wxOPEN)
        dlg = wxFileDialog(self, 'Choose a file', '.', '', 'Modules (*.py)|*.py|Text files (*.txt)|*.txt', wxOPEN)
        try:
            if dlg.ShowModal() == wxID_OK:
                return dlg.GetPath()
        finally:
            dlg.Destroy()
        return ''

    def saveAsDlg(self, filename, filter = '*.py'):
        dir, name = path.split(filename)
        dlg = wxFileDialog(self, 'Save as...', dir, name, filter,
          wxSAVE | wxOVERWRITE_PROMPT)

        try:
            if dlg.ShowModal() == wxID_OK:
                return dlg.GetPath(), true
            else:
                return '', false
        finally:
            dlg.Destroy()

    def closeModule(self, modulePage):
        idx = modulePage.tIdx
        name = modulePage.model.filename
        if self.modules.has_key(name):
            if modulePage.model.views.has_key('Designer'):
                modulePage.model.views['Designer'].close()
            modulePage.model.refreshFromViews()
            if modulePage.model.modified:
                vis = self.IsShown()
                if not vis:
                    self.Show(true)

                dlg = wxMessageDialog(self, 'There are changes, do you want to save?',
                        'Close module', wxYES_NO | wxCANCEL |wxICON_QUESTION)
                try: res = dlg.ShowModal()
                finally: dlg.Destroy()
                if res == wxID_YES:
#                if Utils.yesNoDialog(self, 'Close module', 'There are changes, do you want to save?'):
                    self.saveOrSaveAs()
                    name = modulePage.model.filename
                elif res == wxID_CANCEL:
                    raise 'Cancelled'

                if not vis:
                    self.Show(false)

            self.tabs.RemovePage(idx)
            del self.modules[name]
            modulePage.destroy()
            # notify pages for idx adjustments
            for modPge in self.modules.values():
                modPge.removedPage(idx)

        else: print name, 'not found in OnClose', self.modules

    def saveAs(self, filename):
        """ Brings up a save as file dialog with filename as initial name """
        model = self.modules[filename].model

        newFilename, success = self.saveAsDlg(filename)
        if success:
            # XXX Check for renaming and update models
            model.saveAs(newFilename)
            self.updateModulePage(model, filename)
            self.updateTitle()
        return success

    def updateTitle(self, pageIdx = None):
        """ Updates the title of the Editor to reflect changes in selection,
            filename or model state.
        """

        # XXX Do decorations here
        modulePage = self.getActiveModulePage(pageIdx)
        if modulePage:
            self.SetTitle('Editor - %s - %s' %(modulePage.pageName,
              modulePage.model.filename))
        else:
            self.SetTitle('Editor')

    def updateModulePage(self, model, filename = ''):
        if filename:
            modPge = self.modules[filename]
        else:
            modPge = self.modules[model.filename]
        self.tabs.SetPageText(modPge.tIdx, modPge.updatePageName())
#        self.tabs.Refresh()

    def updateStatusRowCol(self, row, col):
        self.statusBar.row.SetLabel(`row`)
        self.statusBar.col.SetLabel(`col`)

    def clearAllStepPoints(self):
        for mod in self.modules.values():
            if mod.model.views.has_key('Source'):
                mod.model.views['Source'].setStepPos(0)

    def OnOpen(self, event):
        fn = self.openFileDlg()
        if fn: self.openOrGotoModule(fn)

    def saveOrSaveAs(self):
        modulePage = self.getActiveModulePage()
        if modulePage:
            modulePage.saveOrSaveAs()

    def OnSave(self, event):
        modulePage = self.getActiveModulePage()
        modulePage.model.refreshFromViews()
        self.saveOrSaveAs()

    def OnSaveAs(self, event):
        modulePage = self.getActiveModulePage()
        if modulePage:
            modulePage.model.refreshFromViews()
            model = modulePage.model
            oldName = model.filename

            if self.saveAs(oldName) and (oldName != model.filename):
                del self.modules[oldName]
                self.modules[model.filename] = modulePage

    def OnReload(self, event):
        modulePage = self.getActiveModulePage()
        if modulePage:
            modulePage.model.load()

    def OnClosePage(self, event):
        # Replace view's edit menu with editor managed blankEditMenu
        # so editor can free it without fear of mainMenu freeing it
#        self.mainMenu.Replace(mmEdit, self.blankEditMenu, 'Edit')

#        self.mainMenu.Replace(mmEdit, wxMenu(), 'Edit').Destroy()
        # XXX This might cause crash !!!!
        modulePage = self.getActiveModulePage()
        actPge = self.tabs.GetSelection()
        numPgs = self.tabs.GetPageCount()
        if modulePage:
            try:
                self.closeModule(modulePage)
            except 'Cancelled':
                if not event:
                    raise
                else:
                    return

            self.mainMenu.Replace(mmEdit, wxMenu(), 'Edit').Destroy()
            if actPge == numPgs - 1:
                self.tabs.SetSelection(numPgs - 2)
            else:
                self.tabs.SetSelection(actPge)


    def OnRefresh(self, event):
        modulePage = self.getActiveModulePage()
        if modulePage and modulePage.model.views.has_key('Source'):
            modulePage.model.views['Source'].refreshModel()
            self.updateModulePage(modulePage.model)
            self.updateTitle()

    def OnPageChange(self, event):
        sel = event.GetSelection()
        if sel > -1:
            self.updateTitle(sel)
            if hasattr(self, 'toolBar'): self.setupToolBar(sel)
        event.Skip()

    def OnDesigner(self, event):
        self.showDesigner()

    def OnDebug(self, event):
        print self.modules

    def OnCloseWindow(self, event):
        self.Show(false)
        if self.palette.destroying:
            self.persistEditorState()

            # hack to avoid core dump, first setting the notebook to anything but
            # the last page before setting it to the last page allows us to close
            # this window from the palette. Weird?
            self.tabs.SetSelection(0)
            pgeCnt = self.tabs.GetPageCount()
            self.tabs.SetSelection(pgeCnt -1)
            for p in range(pgeCnt):
                try:
                    self.OnClosePage(None)
                except 'Cancelled':
                    self.Show(true)
                    self.palette.destroying = false
                    return

            if self.debugger:
                self.debugger.Close()

            self.palette.editor = None
            self.inspector = None
            self.explorer.destroy()
            self.newMenu.Destroy()#
##            self.mainMenu.Replace(1, self.blankEditMenu, 'Edit')
##            self.mainMenu.Replace(2, self.blankViewMenu, 'View')
            self.mainMenu.Replace(1, wxMenu(), 'Edit').Destroy()
            self.mainMenu.Replace(2, wxMenu(), 'View').Destroy()
            self.mainMenu = None

            self.erroutFrm.Destroy()
            self.erroutFrm = None

            self.shell.destroy()

            self.Destroy()
            event.Skip()

    def OnHelp(self, event):
        Help.showHelp(self, Help.BoaHelpFrame, 'Editor.html')

    def OnHelpGuide(self, event):
        Help.showHelp(self, Help.BoaHelpFrame, 'Guide/index.html')

    def OnHelpTips(self, event):
        Utils.showTip(self, true)

    def OnToggleView(self, event):
        evtId = event.GetId()
        mod = self.getActiveModulePage()
        if mod:
            modVwClss = map(lambda x: x.__class__, mod.model.views.values())
            #Find view class associated with this id
            for viewCls, wId in mod.adtViews:
                if wId == evtId:
                    if self.mainMenu.IsChecked(evtId):
                        #Should be added, but check that it doesn't exist
                        if viewCls not in modVwClss:
                            view = mod.addView(viewCls)
                            view.refreshCtrl()
                            view.focus()
                        else:
                            print 'Add: View already exists'
                    else:
                        #Should be removed, but check that it does exist
                        if viewCls in modVwClss:
                            viewName = viewCls.viewName
                            view = mod.model.views[viewName]
                            view.deleteFromNotebook(mod.default, viewName)

                            self.mainMenu.Check(evtId, false)
                            return
                        else:
                            print 'Remove: View already exists'
                    break
            else:
                print 'Menu Id not found'

    def OnDefaultsToggle(self, event):
        evtId = event.GetId()
        view, model = self.viewDefaultIds[event.GetId()]
        if self.mainMenu.IsChecked(evtId):
            if view not in self.defaultAdtViews.get(model, []):
                self.defaultAdtViews[model].append(view)
        else:
            if view in self.defaultAdtViews.get(model, []):
                self.defaultAdtViews[model].remove(view)


    def OnSwitchedToView(self, event):
        # This is triggered twice, I'd love to know why
        event.Skip()

    def OnSwitchApp(self, event):
        actMod = self.getActiveModulePage()
        if actMod and isinstance(actMod.model, ModuleModel) and actMod.model.app:
            model = self.openOrGotoModule(actMod.model.app.filename)
            model.views['Application'].focus()

    def OnHelpAbout(self, event):
        abt = About.AboutBox(None)
        try:     abt.ShowModal()
        finally: abt.Destroy()

    def OnGotoModulePage(self, event):
        wId = event.GetId()
        for mod in self.modules.values():
            if mod.windowId == wId:
                self.tabs.SetSelection(mod.tIdx)

    def OnSwitchShell(self, event):
        self.tabs.SetSelection(0)

    def OnSwitchExplorer(self, event):
        self.tabs.SetSelection(1)

    def OnSwitchPalette(self, event):
        self.palette.Show(true)
        self.palette.Raise()

    def OnSwitchInspector(self, event):
        self.inspector.Show(true)
        if self.inspector.IsIconized():
            self.inspector.Iconize(false)
        self.inspector.Raise()

    def OnDiff(self, event):
        actMod = self.getActiveModulePage()
        if actMod:
            fn = self.openFileDlg()
            if fn:
                actMod.model.diff(fn)

    def OnPyChecker(self, event):
        actMod = self.getActiveModulePage()
        if actMod:
            cwd = os.path.abspath(os.getcwd())
            newCwd = os.path.dirname(actMod.model.filename)
            os.chdir(newCwd)
            oldErr = sys.stderr
            oldSysPath = sys.path[:]
            try:
                sys.path.append(Preferences.pyPath)
                cmd = '"%s" "%s" %s'%(sys.executable,
                      os.path.join(Preferences.pyPath, 'ExternalLib',
                      'PyChecker', 'checker_custom.py'),
                      os.path.basename(actMod.model.filename))

                from ModRunner import ProcessModuleRunner
                ProcessModuleRunner(self.erroutFrm, actMod.model.app,
                      newCwd).run(cmd, ErrorStack.PyCheckerErrorParser,
                      'PyChecker', 'Warnings', true)
            finally:
                sys.path = oldSysPath
                sys.stderr = oldErr
                os.chdir(cwd)

    def OnConfPyChecker(self, event):
        actMod = self.getActiveModulePage()
        if actMod:
            home = os.environ.get('HOME')
            if home:
                appDir = home
                appConfig = home+'/.pycheckrc'
            else:
                appDir = os.path.dirname(actMod.model.filename)
                appConfig = appDir+'/.pycheckrc'
            if not os.path.exists(appConfig):
                dlg = wxMessageDialog(self, 'The PyChecker configuration file '
                  "can not be found. Copy the default file here?",
                  'Config file not found', wxYES_NO | wxICON_QUESTION)
                try:
                    if dlg.ShowModal() == wxID_YES:
                        import shutil
                        shutil.copyfile(os.path.join(Preferences.pyPath,
                            'ExternalLib', 'PyChecker', 'pycheckrc'), appConfig)
                    else:
                        return
                finally:
                    dlg.Destroy()

            from Explorers.PrefsExplorer import SourceBasedPrefColNode
            SourceBasedPrefColNode('PyChecker', ('*',), appConfig, -1, None).open(self)

    def OnCmpApps(self, event):
        actMod = self.getActiveModulePage()
        if actMod:
            fn = self.openFileDlg()
            if fn:
                actMod.model.compareApp(fn)

    def OnNextPage(self, event):
        pc = self.tabs.GetPageCount()
        idx = self.tabs.GetSelection() + 1
        if idx >= pc: idx = 0
        self.tabs.SetSelection(idx)

    def OnPrevPage(self, event):
        pc = self.tabs.GetPageCount()
        idx = self.tabs.GetSelection() - 1
        if idx < 0: idx = pc - 1
        self.tabs.SetSelection(idx)

#---Code Browsing---------------------------------------------------------------
    def addBrowseMarker(self, marker):
        """ Add marker to browse stack associated with the currently open module
            and view
        """
        modulePage = self.getActiveModulePage()
        if modulePage:
            activeView = modulePage.getActiveView()
            page = Browse.BrowsePage(modulePage, activeView.viewName, marker)
            self.browser.add(page)
            self.updateBrowserBtns()

    def OnBrowseBack(self, event):
        self.browser.back()
        self.updateBrowserBtns()

    def OnBrowseForward(self, event):
        self.browser.forward()
        self.updateBrowserBtns()

#---DistUtils-------------------------------------------------------------------
    def runDistUtilsCmd(self, cmd):
        import ProcessProgressDlg
        cwd = path.abspath(os.getcwd())
        modulePage = self.getActiveModulePage()
        os.chdir(path.dirname(modulePage.model.filename))
        try:
            PD = ProcessProgressDlg.ProcessProgressDlg(self,
              'python setup.py %s'%cmd, 'Running distutil command...', autoClose = false)
            try:
                PD.ShowModal()
            finally:
                PD.Destroy()
        finally:
            os.chdir(cwd)

    def OnSetupBuild(self, event):
        self.runDistUtilsCmd('build')
    def OnSetupClean(self, event):
        self.runDistUtilsCmd('clean')
    def OnSetupInstall(self, event):
        self.runDistUtilsCmd('install')
    def OnSetupSDist(self, event):
        self.runDistUtilsCmd('sdist')
    def OnSetupBDist(self, event):
        self.runDistUtilsCmd('bdist')
    def OnSetupBDist_WinInst(self, event):
        self.runDistUtilsCmd('bdist_wininst')

    def OnSetupPy2Exe(self, event):
        self.runDistUtilsCmd('py2exe')

#---State methods---------------------------------------------------------------
    def restoreEditorState(self):
        # Open previously opened files if necessary
        if Preferences.rememberOpenFiles:
            conf = Utils.createAndReadConfig('Explorer')
            files = eval(conf.get('editor', 'openfiles'))
            apps = []
            for file in files:
                try:
                    print 'Opening in Editor: %s' % os.path.basename(file)
                    for app in apps:
                        if app.hasModule(file): break
                    else:
                        app = None
                    model = self.openModule(file, app)
                    if model.modelIdentifier == 'App':
                        apps.append(model)

                except Exception, error:
                    # Swallow exceptions, ignore non FS modules
                    wxLogError(str(error))

    def persistEditorState(self, ):
        # Save list of open files to config if necessary
        if Preferences.rememberOpenFiles:
            modOrder = []
            for mod, modPage in self.modules.items():
                if modPage.model.savedAs:
                    modOrder.append( (modPage.tIdx, mod) )
            modOrder.sort()

            mods = []
            for idx, mod in modOrder:
                mods.append(mod)

            try:
                conf = Utils.createAndReadConfig('Explorer')
                conf.set('editor', 'openfiles', `mods`)
                conf.write(open(conf.confFile, 'w'))
            except Exception, error:
                wxLogError('Could not save open file list: '+str(error))

    def OnExecFinish(self, event):
        event.runner.init(self.erroutFrm, event.runner.app)
        event.runner.recheck()
        self.statusBar.setHint('Finished execution.')
        #print 'OnExecFinish', event.runner


#-----Toolbar-------------------------------------------------------------------

class MyToolBar(wxToolBar):
    def __init__(self, parent, winid):
        wxToolBar.__init__(self, parent, winid,
          style = wxTB_HORIZONTAL|wxNO_BORDER|flatTools)#wxDOUBLE_BORDER|
        self.toolLst = []
        self.toolCount = 0

    def AddTool(self, id, bitmap, toggleBitmap = wxNullBitmap, shortHelpString = '', isToggle = false):
        from Views.StyledTextCtrls import new_stc
        if new_stc:
            wxToolBar.AddTool(self, id, bitmap, toggleBitmap, isToggle = isToggle,
                shortHelpString = shortHelpString)
        else:
            wxToolBar.AddTool(self, id, bitmap, toggleBitmap, toggle = isToggle,
                shortHelpString = shortHelpString)

        self.toolLst.append(id)
        self.toolCount = self.toolCount + 1

    def AddSeparator(self):
        wxToolBar.AddSeparator(self)
        self.toolLst.append(-1)
        self.toolCount = self.toolCount + 1

    def DeleteTool(self, id):
        wxToolBar.DeleteTool(self, id)
        self.toolLst.remove(id)
        self.toolCount = self.toolCount - 1

    def ClearTools(self):
        posLst = range(self.toolCount)
        posLst.reverse()
        for pos in posLst:
            self.DeleteToolByPos(pos)

        for wid in self.toolLst:
            if wid != -1:
                self.GetParent().Disconnect(wid),
        self.toolLst = []
        self.toolCount = 0

    def GetToolPopupPosition(self, id):
        margins = self.GetToolMargins()
        toolSize = self.GetToolSize()
        xPos = margins.x
        for tId in self.toolLst:
            if tId == id:
                return wxPoint(xPos, margins.y + toolSize.y)

            if tId == -1:
                xPos = xPos + self.GetToolSeparation()
            else:
                xPos = xPos + toolSize.x

        return wxPoint(0, 0)

    def PopupToolMenu(self, toolId, menu):
        self.PopupMenu(menu, self.GetToolPopupPosition(toolId))

##        menu = wxMenu()
##        menu.Append(1, 'asdf asdf')
##        self.toolBar.PopupToolMenu(event.GetId(), menu)

class EditorToolBar(MyToolBar):
    pass

class EditorStatusBar(wxStatusBar):
    """ Displays information about the current view. Also global stats/
        progress bar etc. """
    def __init__(self, parent):
        wxStatusBar.__init__(self, parent, -1, style = wxST_SIZEGRIP)
        self.SetFieldsCount(4)
        self.SetStatusWidths([16, 400, 150, -1])#30, 30,

        self.h = self.GetClientSize().y

#        self.col = wxStaticText(self, -1, '0   ', wxPoint(3, 4))
#        self.row = wxStaticText(self, -1, '0   ', wxPoint(37, 4))
        self.hint = wxStaticText(self, -1, ' ', wxPoint(28, 4),
          wxSize(390, self.h -5), style = wxST_NO_AUTORESIZE | wxALIGN_LEFT)
        self.progress = wxGauge(self, -1, 100,
          pos = wxPoint(422+Preferences.editorProgressFudgePosX, 2),
          size = wxSize(150, self.h -2 + Preferences.editorProgressFudgeSizeY))

    def setHint(self, hint):
        self.hint.SetLabel(hint)
        self.hint.SetSize(wxSize(390, self.h -5))
        self.hint.SetToolTipString(hint)

    def OnEditorNotification(self, event):
        self.setHint(event.message)

#-----Model hoster--------------------------------------------------------------

wxID_MODULEPAGEVIEWCHANGE = wxNewId()

class ModulePage:
    """ Represents a notebook on a page of the top level notebook hosting
        the model instance. """
    def __init__(self, parent, model, defViews, views, idx, editor):
        self.editor = editor
        self.defViews = map(lambda x: (x, wxNewId()), defViews)
        self.adtViews = map(lambda x: (x, wxNewId()), views)
        self.viewIds = []
        self.model = model
        self.parent = parent
        self.notebook = wxNotebook(parent, -1, style = wxWANTS_CHARS | wxCLIP_CHILDREN)
        EVT_NOTEBOOK_PAGE_CHANGED(self.notebook, self.notebook.GetId(), self.OnPageChange)
        self.tIdx = idx
        self.updatePageName()
        self.windowId = wxNewId()
        self.editor.winMenu.Append(self.windowId, self.model.filename)
        EVT_MENU(self.editor, self.windowId, self.editor.OnGotoModulePage)

        cls = model.__class__
#        if not editor.defaultAdtViews.has_key(cls):
#            cls = model.__class__.__bases__[0]

        tot = len(defViews) + len(editor.defaultAdtViews.get(cls, []))
        if tot:
            stepsDone = 50.0
            editor.statusBar.progress.SetValue(int(stepsDone))
            step = (100 - stepsDone) / tot
            for view in defViews:
                self.addView(view)
                stepsDone = stepsDone + step
                editor.statusBar.progress.SetValue(int(stepsDone))

            for view in editor.defaultAdtViews.get(cls, []):
                self.addView(view)
                stepsDone = stepsDone + step
                editor.statusBar.progress.SetValue(int(stepsDone))

        if defViews:
            self.default = defViews[0].viewName
        else:
            self.default = None

        self.viewMenu = self.viewSelectionMenu()

        editor.statusBar.progress.SetValue(0)

    def destroy(self):
        """ Destroy all views, notepad pages and the view notebook."""
        for view, wId in self.defViews + self.adtViews:
            if wId != -1:
                self.model.editor.Disconnect(wId)

        self.editor.winMenu.Delete(self.windowId)
        self.editor.Disconnect(self.windowId)

        self.viewMenu.Destroy()

        for view in self.model.views.values():
            view.close()
        self.notebook.DeleteAllPages()

        self.model.destroy()
        self.notebook.Destroy()

##    def __del__(self):
##        print '__del__', self.__class__.__name__

    def __repr__(self):
        return '<%s: %s, %d>' %(self.__class__.__name__, self.model.defaultName, self.tIdx)

    def updatePageName(self):
        """ Return a name that is decorated with () meaning never been saved
            and/or * meaning model modified ~ meaning view modified. """

        self.pageName = self.model.getPageName()

        if not self.model.savedAs:
            sa1 = '('
            sa2 = ')'
        else: sa1 = sa2 = ''

        if len(self.model.viewsModified):
            vm = '~'
        else: vm = ''

        if self.model.modified: m = '*'
        else: m = ''

        self.pageName = '%s%s%s%s%s%s%s' % (m, vm, sa1, self.pageName, sa2, vm, m)

##        self.pageName = '%s%s%s%s%s%s%s' % (self.model.modified and '*' or '',
##                                            len(self.model.viewsModified) and '~' or '',
##                                            self.model.savedAs and '(' or '',
##                                            self.model.getPageName(),
##                                            self.model.savedAs and ')' or '',
##                                            len(self.model.viewsModified) and '~' or '',
##                                            self.model.modified and '*' or '')

        return self.pageName

### decl getActiveView(self, idx : int) -> EditorView
    def getActiveView(self, idx = None):
        if idx is None: idx = self.notebook.GetSelection()
        if idx == -1: return None
        name = self.notebook.GetPageText(idx)
        if name and name[0] == '~': name = name[1:-1]
        try:
            return self.model.views[name]
        except KeyError:
            return None

### decl viewSelectionMenu(self) -> wxMenu
    def viewSelectionMenu(self):
        menu = wxMenu()
        for view, wId in self.defViews:
            menu.Append(wId, view.viewName)
            EVT_MENU(self.model.editor, wId, self.model.editor.OnSwitchedToView)
        menu.AppendSeparator()
        for view, wId in self.adtViews:
            menu.Append(wId, view.viewName, checkable = view not in self.adtViews)
            EVT_MENU(self.model.editor, wId, self.model.editor.OnToggleView)

        return menu

    def setActiveViewsMenu(self):
        viewClss = map(lambda x: x.__class__, self.model.views.values())
        for view, wId in self.adtViews:
            self.viewMenu.Check(wId, view in viewClss)

    def addView(self, view, viewName = ''):
        """ Add a view to the model and display it as a page in the notebook
            of view instances."""
        if not viewName: viewName = view.viewName
        if wxPlatform == '__WXGTK__':
            panel, self.model.views[viewName] = Utils.wxProxyPanel(self.notebook, view, self.model)
            if view.docked:
                self.model.views[viewName].addToNotebook(self.notebook, viewName,
                        panel=panel)
        else:
            self.model.views[viewName] = apply(view, (self.notebook, self.model))
            if view.docked:
                self.model.views[viewName].addToNotebook(self.notebook, viewName)

        return self.model.views[viewName]

    def refresh(self):
        pass
        # self.notebook.Refresh()

    def focus(self):
        """ Make this model page the currently selected page. """
        self.parent.SetSelection(self.tIdx)

    def removedPage(self, idx):
        """ Called on all ModulePages after a sibling ModulePage deletion.
            Decrements tIdx if bigger than idx. """
        if idx < self.tIdx:
            self.tIdx = self.tIdx - 1

    def saveOrSaveAs(self):
        model = self.model
        if not model.savedAs:
            oldName = model.filename
            if model.editor.saveAs(oldName) and (oldName != model.filename):
                del model.editor.modules[oldName]
                model.editor.modules[model.filename] = self
        else:
            model.save()
            model.editor.updateModulePage(model)
            model.editor.updateTitle()

    def OnPageChange(self, event):
        viewIdx = event.GetSelection()
        if event.GetOldSelection() != viewIdx:
            self.editor.setupToolBar(viewIdx=viewIdx)
            view = self.getActiveView(viewIdx)
            if hasattr(view, 'OnPageActivated'):
                view.OnPageActivated(event)
        event.Skip()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.