This file is indexed.

/usr/lib/python2.7/dist-packages/PythonCard/tools/oneEditor/tabcodeEditor.py is in python-pythoncard 0.8.2-5.

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
"""
__version__ = "$Revision: 1.15 $"
__date__ = "$Date: 2005/12/29 02:48:25 $"

PythonCard Editor (codeEditor) wiki page
http://wiki.wxpython.org/index.cgi/PythonCardEditor

wxStyledTextCtrl documentation
http://wiki.wxpython.org/index.cgi/wxStyledTextCtrl
"""

from PythonCard import about, configuration, dialog, log, menu, model, resource, util, registry
from PythonCard.templates.dialogs import runOptionsDialog
import codePage

from modules import scriptutils
import os, sys
import wx
from wx import stc
from wx.html import HtmlEasyPrinting
import pprint
from PythonCard import STCStyleEditor

from modules import colorizer
import cStringIO
import webbrowser

NEVER_BLANK = True    # if True, closing last tab causes newFile

# KEA 2004-07-22
# force imports for components used in .rsrc.py file
# so we can do a make standalones with py2exe and bundlebuilder
from PythonCard.components import codeeditor

USERCONFIG = 'user.config.txt'

# KEA 2002-05-03
# this could be more sophisticated
# by using an external source code colorizer
# or Scintillas over lexical analyzer?!
def textToHtml(source):
    """Return text converted to HTML."""
    # KEA 2003-08-07
    # how should we deal with Unicode?
    source = source.encode('iso-8859-1')
    output = cStringIO.StringIO()
    colorizer.Parser(source, output).format(None, None)
    html = output.getvalue()
    return html


# KEA doc handling adapted from python_docs 
# method in IDLE EditorWindow.py

pythoncard_url = util.documentationURL("documentation.html")
shell_url = util.documentationURL("shell.html")

help_url = "http://docs.python.org/"
if sys.platform.startswith("win"):
    fn = os.path.dirname(os.__file__)
    fn = os.path.join(fn, os.pardir, "Doc", "index.html")
    fn = os.path.normpath(fn)
    if os.path.isfile(fn):
        help_url = fn
    del fn
elif sys.platform == 'darwin':
    fn = '/Library/Frameworks/Python.framework/Versions/' + \
        'Current/Resources/Python.app/Contents/Resources/English.lproj/' + \
        'PythonDocumentation/index.html'
    if os.path.exists(fn):
        help_url = "file://" + fn

def getResourceFilename(path):
    path, filename = os.path.split(path)
    base = os.path.splitext(filename)[0]
    resourceFilename = os.path.join(path, base + '.rsrc.py')
    return resourceFilename

# this really needs to know about the structure
# of the file by parsing the classes and methods
# it won't deal with duplicate handler names...
# with just simple matching
def handlerExists(text, componentName, eventName):
    eventText = 'def on_' + componentName + '_' + eventName + '('
    # commands are a special case since the command name
    # does not have to be tied to the component name
    # so that will require special handling by looking
    # at the command attribute of the component
    return text.find(eventText)


class TabCodeEditor(model.Background):
    
    def on_initialize(self, event):
        self.pages = []
        self.currentPageNumber = -1
        self.currentPage = None
        self.currentDocument = None
        self.initSizers()

        # KEA 2002-05-08
        # wxFileHistory isn't wrapped, so use raw wxPython
        # the file history is not actually saved when you quit
        # or shared between windows right now
        # also the file list gets appended to the File menu
        # rather than going in front of the Exit menu
        # I suspect I have to add the Exit menu after the file history
        # which means changing how the menus in resources are loaded
        # so I'll do that later
        self.fileHistory = wx.FileHistory()
        fileMenu = self.GetMenuBar().GetMenu(0)
        self.fileHistory.UseMenu(fileMenu)
        wx.EVT_MENU_RANGE(self, wx.ID_FILE1, wx.ID_FILE9, self.OnFileHistory)

        self.lastStatus = None
        self.lastPos = None
        self.configPath = os.path.join(configuration.homedir, 'tabbedcodeeditor')
        self.loadConfig()
        self.cmdLineArgs = {'debugmenu':False, 'logging':False, 'messagewatcher':False,
                            'namespaceviewer':False, 'propertyeditor':False,
                            'shell':False, 'otherargs':''}
        self.lastFind = {'searchText':'', 'replaceText':'', 'wholeWordsOnly':False, 'caseSensitive':False}
        self.startTitle = self.title
        if len(sys.argv) > 1:
            # accept a file argument on the command-line
            filename = os.path.abspath(sys.argv[1])
            log.info('codeEditor filename: ' + filename)
            if not os.path.exists(filename):
                filename = os.path.abspath(os.path.join(self.application.startingDirectory, sys.argv[1]))
            #print filename
            if os.path.isfile(filename):
                self.openFile(filename)
                # the second argument can be a line number to jump to
                # this is experimental, but a nice feature
                # KEA 2002-05-01
                # gotoLine causes the Mac to segfault
                if (len(sys.argv) > 2):
                    try:
                        line = int(sys.argv[2])
                        self.gotoLine(line)
                    except:
                        pass
            else:
                self.newFile()
        else:
            self.newFile()

        self.printer = HtmlEasyPrinting()

        # KEA 2002-05-08
        # wxSTC defaults will eventually be settable via a dialog
        # and saved in a user config, perhaps compatible with IDLE
        # or Pythonwin
######        self.components.document.SetEdgeColumn(75)

        # KEA 2002-05-08
        # the wxFindReplaceDialog is not wrapped
        # so this is an experiment to see how it works
        wx.EVT_COMMAND_FIND(self, -1, self.OnFind)
        wx.EVT_COMMAND_FIND_NEXT(self, -1, self.OnFind)
        wx.EVT_COMMAND_FIND_REPLACE(self, -1, self.OnFind)
        wx.EVT_COMMAND_FIND_REPLACE_ALL(self, -1, self.OnFind)
        wx.EVT_COMMAND_FIND_CLOSE(self, -1, self.OnFindClose)

        self.visible = True
        self.loadShell()
        
        # hack to get around size event being hooked up
        # after on_initialize is called?
        # that is the only explanation I can think of for needing
        # to do this
        w, h = self.size
        wx.FutureCall(1, self.SetSize, (w, h - 1))
        wx.FutureCall(1, self.SetSize, (w, h))


    def initSizers(self):
        sizer1 = wx.BoxSizer(wx.VERTICAL)
        sizer2 = wx.BoxSizer(wx.HORIZONTAL)

        sizer2.Add(self.components.popComponentNames)
        sizer2.Add(self.components.popComponentEvents)
        sizer2.Add( (10,21) )

        sizer1.Add(sizer2, 0)
        sizer1.Add(self.components.notebook, 1, wx.EXPAND)

        sizer1.Fit(self)
        sizer1.SetSizeHints(self)
        self.panel.SetSizer(sizer1)
        self.panel.SetAutoLayout(1)
        self.panel.Layout()

    def on_idle(self, event):
        if self.currentPageNumber >= 0:
            self.currentPage = self.pages[self.currentPageNumber]
            self.currentDocument = self.pages[self.currentPageNumber].components.document
        else:
            self.currentPage = None
            self.currentDocument = None
        self.updateTitleBar()
        if self.currentPage: self.updateStatusBar()
        # KEA 2003-01-06
        # resource file support
        # if there is an associated resource file then
        # it should be checked periodically to see if it has
        # changed and if so, update our internal resource
        # as well as the component names and events menus
        # the events menu should also be updated as the user
        # edits the text to keep the defined events marked
        # with a +
        # the code below is too CPU intensive to run
        # all the time, so I've commented it out until
        # a better way of updating the event list is found
        ##sel = self.components.popComponentNames.stringSelection
        ##if sel != '':
        ##    self.fillEventNames(sel)


    def updateStatusBar(self):
        if self.currentPage:
            if self.currentPage.documentPath:
                path = self.currentPage.documentPath
            else:
                path = self.resource.strings.untitled
            pos = self.currentDocument.GetCurrentPos()
            newText = "File: %s  |  Line: %d  |  Column: %d" % \
                    (path,
                     self.currentDocument.LineFromPosition(pos) + 1,
                     self.currentDocument.GetColumn(pos) + 1)
            #print "updatestatusbar", self.lastPos, pos, self.lastStatus, newText
            if self.lastStatus != newText:
                self.statusBar.text = newText
                self.lastStatus = newText
                self.currentPage.lastPos = pos
        else:
            self.statusBar.text = "No File"

    def setTitleBar(self, path):
        if not path: path = self.resource.strings.untitled
        self.title = path + " " + self.startTitle
        self.components.notebook.SetPageText(self.currentPageNumber, os.path.split(path)[-1])
        self.updateTitleBar()

    def updateTitleBar(self):
        title = self.title
        pageText = self.components.notebook.GetPageText(self.currentPageNumber)
        if self.currentPage:
            modified = self.currentDocument.GetModify()
        else:
            modified = ''
        if modified and title[0] != '*':
            self.title = '* ' + title + ' *'
            self.components.notebook.SetPageText(self.currentPageNumber, '* ' + pageText + ' *')
            self.panel.Refresh()
        elif not modified and title[0] == '*':
            self.title = title[2:-2]
            self.components.notebook.SetPageText(self.currentPageNumber, pageText[2:-2])
            self.panel.Refresh()

    # these are event handlers bound above
    # since they aren't automatically bound by PythonCard
    # I used the wxPython naming conventions
    # these methods will eventually be converted

    # KEA 2002-05-08
    # this is adapted from the wxPython demo
    def OnFind(self, event):
        map = {
            wx.wxEVT_COMMAND_FIND : "FIND",
            wx.wxEVT_COMMAND_FIND_NEXT : "FIND_NEXT",
            wx.wxEVT_COMMAND_FIND_REPLACE : "REPLACE",
            wx.wxEVT_COMMAND_FIND_REPLACE_ALL : "REPLACE_ALL",
            }
        et = event.GetEventType()

        try:
            evtType = map[et]
        except KeyError:
            evtType = "**Unknown Event Type**"

        self.lastFind['searchText'] = event.GetFindString()
        flags = event.GetFlags()
        self.lastFind['wholeWordsOnly'] = flags & wx.FR_WHOLEWORD != 0
        self.lastFind['caseSensitive'] = flags & wx.FR_MATCHCASE != 0
        
        if et == wx.wxEVT_COMMAND_FIND_REPLACE or et == wx.wxEVT_COMMAND_FIND_REPLACE_ALL:
            replaceTxt = "Replace text: " + event.GetReplaceString()
            self.lastFind['replaceText'] = event.GetReplaceString()
        else:
            replaceTxt = ""

        #print "%s -- Find text: %s  %s  Flags: %d  \n" % (evtType, event.GetFindString(), replaceTxt, event.GetFlags())

        if et == wx.wxEVT_COMMAND_FIND or et == wx.wxEVT_COMMAND_FIND_NEXT:
            self.findNext(self.lastFind['searchText'],
                          self.lastFind['wholeWordsOnly'],
                          self.lastFind['caseSensitive'])
        elif et == wx.wxEVT_COMMAND_FIND_REPLACE:
            # the way Notepad works
            # pressing Replace causes a Find Next
            # if there is no selection
            # if the text that is selected matches
            # the search criteria, then it is replaced
            # and a Find Next occurs
            doc = self.currentDocument
            txt = doc.GetSelectedText()
            sel = doc.GetSelection()
            if self.lastFind['searchText'].lower() == txt.lower():
                # since we don't know criteria for word boundaries
                # let wxSTC do the searching
                doc.SetCurrentPos(doc.GetSelectionStart())
            result = self.findNext(self.lastFind['searchText'],
                                   self.lastFind['wholeWordsOnly'],
                                   self.lastFind['caseSensitive'])
            if result != -1 and sel == doc.GetSelection():
                replaceText = self.lastFind['replaceText']
                doc.ReplaceSelection(replaceText)
                pos = doc.GetCurrentPos()
                doc.SetSelection(pos - len(replaceText), pos)
                result = self.findNext(self.lastFind['searchText'],
                                       self.lastFind['wholeWordsOnly'],
                                       self.lastFind['caseSensitive'])
        elif et == wx.wxEVT_COMMAND_FIND_REPLACE_ALL:
            self.replaceAll(self.lastFind['searchText'],
                            self.lastFind['replaceText'],
                            self.lastFind['wholeWordsOnly'],
                            self.lastFind['caseSensitive'])

    # search/replace from current position
    def replaceAll(self, searchText, replaceText, wholeWordsOnly, caseSensitive):
        # unless there is a built-in method for Replace All
        # we need to brute force this search
        doc = self.currentDocument
        pos = doc.GetCurrentPos()
        sel = doc.GetSelection()
        doc.SetCurrentPos(0)
        # should we handle this replace all operation as a single
        # undoable operation?
        replaced = 0
        while -1 != self.findNext(searchText,
                                  wholeWordsOnly,
                                  caseSensitive):
            doc.ReplaceSelection(replaceText)
            replaced += 1
        self.statusBar.text = self.resource.strings.replaced % replaced
        self.currentPage.lastPos = self.currentDocument.GetCurrentPos()
        if not replaced:
            # restore previous position and selection
            doc.SetSelection(sel[0], sel[1])
            doc.SetCurrentPos(pos)

    def replaceTabs(self):
        """Replace tabs with four spaces."""
        self.replaceAll('\t', '    ', 0, 0)

    def OnFindClose(self, event):
        event.GetDialog().Destroy()

    def OnFileHistory(self, event):
        fileNum = event.GetId() - wx.ID_FILE1
        path = self.fileHistory.GetHistoryFile(fileNum)
        self.openFile(path)

    # back to PythonCard methods

    def loadConfig(self):
        try:
            if not os.path.exists(self.configPath):
                os.mkdir(self.configPath)
            path = os.path.join(self.configPath, USERCONFIG)
            self.config = util.readAndEvalFile(path)
            if self.config != {}:
                if 'position' in self.config:
                    self.position = self.config['position']
                if 'size' in self.config:
                    self.size = self.config['size']
                if 'history' in self.config:
                    history = self.config['history']
                    history.reverse()
                    for h in history:
                        self.fileHistory.AddFileToHistory(h)
                if 'view_white_space' in self.config:
                    self.currentDocument.SetViewWhiteSpace(self.config['view_white_space'])
                    self.menuBar.setChecked('menuViewWhitespace', self.config['view_white_space'])
                if 'indentation_guides' in self.config:
                    self.currentDocument.SetIndentationGuides(self.config['indentation_guides'])
                    self.menuBar.setChecked('menuViewIndentationGuides', self.config['indentation_guides'])
                if 'right_edge_guide' in self.config:
                    self.currentDocument.SetEdgeMode(self.config['right_edge_guide'])
                    self.menuBar.setChecked('menuViewRightEdgeIndicator', self.config['right_edge_guide'])
                if 'view_EOL' in self.config:
                    self.currentDocument.SetViewEOL(self.config['view_EOL'])
                    self.menuBar.setChecked('menuViewEndOfLineMarkers', self.config['view_EOL'])
                if 'line_numbers' in self.config:
                    self.currentDocument.lineNumbersVisible = self.config['line_numbers']
                    self.menuBar.setChecked('menuViewLineNumbers', self.config['line_numbers'])
                if 'folding' in self.config:
                    self.currentDocument.codeFoldingVisible = self.config['folding']
                    self.menuBar.setChecked('menuViewCodeFolding', self.config['folding'])

                if 'macros' in self.config:
                    self.macros = self.config['macros']
                    # should match based on name instead
                    m = self.menuBar.menus[4]
                    rsrc = resource.Resource({'type':'MenuItem', 'name': 'scriptletSep2', 'label':'-'})
                    mi = menu.MenuItem(self, m, rsrc)
                    m.appendMenuItem(mi)
                    for macro in self.macros:
                        #print 'm', macro
                        if macro['key'] == '':
                            key = ''
                        else:
                            key = '\t' + macro['key']
                        rsrc = resource.Resource({'type':'MenuItem',
                            'name': 'menuScriptlet' + macro['label'], 
                            'label': macro['label'] + key,
                            'command':'runMacro'})
                        mi = menu.MenuItem(self, m, rsrc)
                        m.appendMenuItem(mi)

        except:
            self.config = {}

    def saveConfig(self):
        self.config['position'] = self.GetRestoredPosition()
        self.config['size'] = self.GetRestoredSize()
        self.config['view_white_space'] = self.currentDocument.GetViewWhiteSpace()
        self.config['indentation_guides'] = self.currentDocument.GetIndentationGuides()
        self.config['right_edge_guide'] = self.currentDocument.GetEdgeMode()
        self.config['view_EOL'] = self.currentDocument.GetViewEOL()
        self.config['line_numbers'] = self.currentDocument.lineNumbersVisible
        self.config['folding'] = self.currentDocument.codeFoldingVisible
        history = []
        for i in range(self.fileHistory.GetCount()):
            history.append(self.fileHistory.GetHistoryFile(i))
        self.config['history'] = history
        try:
            path = os.path.join(self.configPath, USERCONFIG)
            f = open(path, "w")
            pprint.pprint(self.config, f)
            f.close()
        except:
            pass    # argh

    def saveChanges(self, path):
        # save configuration info in the app directory
        #filename = os.path.basename(self.documentPath)
        if path is None:
            filename = self.resource.strings.untitled
        else:
            filename = path
        msg = self.resource.strings.documentChangedPrompt % filename
        result = dialog.messageDialog(self, msg, self.resource.strings.codeEditor,
                                   wx.ICON_EXCLAMATION | wx.YES_NO | wx.CANCEL)
        return result.returnedString

    def doExit(self):
        for page in self.pages:
            doc = page.components.document
            if doc.GetModify():
                save = self.saveChanges(page.documentPath)
                if save == "Cancel":
                    return False
                elif save == "No":
                    continue
                else:
                    if page.documentPath is None:
                        if not page.saveAsFile(): return False
                    else:
                        page.saveFile(page.documentPath)
                        continue
            else:
                continue
        return True

    def on_close(self, event):
        if self.doExit():
            try:
                # KEA 2004-04-08
                # if an exception occurs during on_initialize
                # then saveConfig could fail because some windows
                # might not exist, so in that situation just exit gracefully
                self.saveConfig()
            except:
                pass
            self.fileHistory = None
            self.printer = None
            event.skip()


    def on_menuFileSave_select(self, event):
        if self.currentPage:
            if self.currentPage.documentPath is None:
                # this a "new" document and needs to go through Save As...
                self.currentPage.saveAsFile()
            else:
                self.currentPage.saveFile(self.currentPage.documentPath)

    def on_menuFileSaveAs_select(self, event):
        if self.currentPage:
            return self.currentPage.saveAsFile()

    def on_menuFileCloseTab_select(self, event):
        # what do we do if there is only one tab?
        if self.currentPage:
            page = self.currentPage
            doc = page.components.document
            # logic borrowed from doExit
            if doc.GetModify():
                save = self.saveChanges(page.documentPath)
                if save == "Cancel":
                    #rint "Cancelled Save"
                    return
                elif save == "No":
                    #rint "Didn't Save"
                    pass
                else:
                    if page.documentPath is None:
                        if not page.saveAsFile(): print "no path, Didn't Save"
                        # this logic was borrowed from doExit
                        # user chose Yes to save on previous dialog but then
                        # cancelled the Save dialog
                        # so don't close the tab
                    else:
                        page.saveFile(page.documentPath)
                        #rint "Saved"
            self.closeTab()

    def closeTab(self):
        self.pageChangedFired = False
        
        del self.pages[self.currentPageNumber]
        self.components.notebook.DeletePage(self.currentPageNumber)
        
        # KEA 2004-10-10
        # workaround pageChanged event not firing on Mac OS X
        # when it gets fixed, this code should be harmless
        if not self.pageChangedFired:
            selection = self.components.notebook.GetSelection()
            #print selection, len(self.pages)
            if selection != -1 and selection <= (len(self.pages) - 1):
                self.currentPageNumber = selection
                self.currentPage = self.pages[selection]
                self.currentDocument = self.currentPage.components.document
                self.currentPage.becomeFocus()
                self.updateStatusBar()
                self.updateTitleBar()
                self.setResourceFile()

        if len(self.pages) == 0:
            if NEVER_BLANK:
                self.newFile()
            else:
                self.currentPageNumber = -1
                self.currentPage = None
                self.currentDocument = None

    def newFile(self):
        win = model.childWindow(self.components.notebook, codePage.CodePage)
        self.components.notebook.AddPage(win, "new ...", True)
        self.pages.append(win)
        wx.CallAfter(win.newFile)
        self.currentPageNumber = len(self.pages) - 1
        wx.CallAfter(self.setResourceFile)
        size = self.pages[-1].size
        wx.CallAfter(self.pages[-1].SetSize, size)

    def openFile(self, path):
        # need a new tab page in notebook if
            # no current page - i.e. blank notebook
            # current page is a open on a file
            # untitled document has been modified
        if (not self.currentPage or 
            self.currentPage.documentPath or
            self.currentDocument.GetModify()):
            
            win = model.childWindow(self.components.notebook, codePage.CodePage)
            self.components.notebook.AddPage(win, "opening ...", True)
            self.pages.append(win)
            self.currentPageNumber = len(self.pages)-1
            size = self.pages[-1].size
            wx.CallAfter(self.pages[-1].SetSize, size)
        else:
            win = self.currentPage
        wx.CallAfter(win.openFile, path)
        wx.CallAfter(self.setResourceFile)


    # KEA 2003-01-06
    # resource file support
    def setResourceFile(self):
        self.components.popComponentNames.items = []
        self.components.popComponentEvents.items = []
        if self.currentPageNumber >= 0:
            self.currentPage = self.pages[self.currentPageNumber]
            self.currentDocument = self.currentPage.components.document
            # KEA self.currentPage is always True, so why the if?
            #if self.currentPage:
            try:
                self.resourceFilename = getResourceFilename(self.currentPage.documentPath)
                self.rsrc = resource.ResourceFile(self.resourceFilename).getResource()
                self.rsrcComponents = {}
                if hasattr(self.rsrc, 'application'):
                    components = self.rsrc.application.backgrounds[0].components
                else:
                    # CustomDialog
                    components = self.rsrc.components
                for c in components:
                    self.rsrcComponents[c.name] = c.type
                items = self.rsrcComponents.keys()
                items.sort()
                self.components.popComponentNames.items = items
                self.components.popComponentNames.visible = True
                self.components.popComponentEvents.visible = False
                return
            except:
                pass
        # no page, or no components on page
        self.components.popComponentNames.visible = False
        self.components.popComponentEvents.visible = False

    def fillEventNames(self, componentName):
        self.components.popComponentEvents.visible = True
        r = registry.Registry.getInstance()
        componentType = self.rsrcComponents[componentName]
        spec = r.components[componentType]._spec
        tmp = spec.getEventNames() + ['command']
        tmp.sort()

        text = self.currentDocument.text
        eventNames = []
        for e in tmp:
            if handlerExists(text, componentName, e) != -1:
                eventNames.append('+ ' + e)
            else:
                eventNames.append('   ' + e)
        # should we try and save and restore the current selection?
        # AGT 2004-10-09 Changing between two components of same type
        # should reset the even selection
##        if self.components.popComponentEvents.items != eventNames:
##            self.components.popComponentEvents.items = eventNames
        self.components.popComponentEvents.items = eventNames


    def on_popComponentNames_select(self, event):
        if self.currentPage:
            self.fillEventNames(event.target.stringSelection)

    def on_popComponentEvents_select(self, event):
        document = self.currentDocument
        componentName = self.components.popComponentNames.stringSelection
        # this is tied to the '   ' and '+ ' used in fillEventNames
        # we just want the event name
        eventName = event.target.stringSelection.split(' ')[-1]
        eventText = 'def on_' + componentName + '_' + eventName + '('
        offset = handlerExists(document.text, componentName, eventName)
        #print eventText, offset
        if offset != -1:
            document.SetSelection(offset, offset)
        else:
            # event handler doesn't exist?
            # so create one at the current selection?
            sel = document.GetSelection()
            start = document.LineFromPosition(sel[0])
            # this could take into account the current indent
            eventText = eventText + 'self, event):\n    pass\n'
            firstChar = document.PositionFromLine(start)
            
            document.BeginUndoAction()
            document.InsertText(firstChar, eventText)
            document.SetCurrentPos(document.PositionFromLine(start))
            document.EndUndoAction()
            
        document.setFocus()

##    # File menu
##    
##    # KEA 2002-05-04
##    # need to decide on UI for multiple windows
##    # New Window, Open in New Window, New, Open, etc.
##    # since we aren't doing MDI
##    # we could have child windows, but what would the organization be?!

    def on_menuFileNew_select(self, event):
        # no need to save current file - just open new tab
        self.newFile()

    def on_menuFileOpen_select(self, event):
        # no need to save current file - just open new tab
        # split this method into several pieces to make it more flexible
        #wildcard = "Python scripts (*.py;*.pyw)|*.py;*.pyw|Text files (*.txt)|*.txt|All files (*.*)|*.*"
        wildcard = self.resource.strings.saveAsWildcard
        result = dialog.openFileDialog(None, self.resource.strings.openFile, '', '', wildcard)
        if result.accepted:
            path = result.paths[0]
            # an error will probably occur here if the text is too large
            # to fit in the wxTextCtrl (TextArea) or the file is actually
            # binary. Not sure what happens with CR/LF versus CR versus LF
            # line endings either
            self.openFile(path)

        
    def on_menuFilePrint_select(self, event):
        source = textToHtml(self.currentDocument.text)
        self.printer.PrintText(source)

    def on_menuFilePrintPreview_select(self, event):
        source = textToHtml(self.currentDocument.text)
        self.printer.PreviewText(source)

    def on_menuFilePageSetup_select(self, event):
        self.printer.PageSetup()


    # Edit menu
    
    def on_menuEditUndo_select(self, event):
        if self.currentPage:
            self.currentPage.on_menuEditUndo_select(event)

    def on_menuEditRedo_select(self, event):
        if self.currentPage:
            self.currentPage.on_menuEditRedo_select(event)

    def on_menuEditCut_select(self, event):
        if self.currentPage:
            self.currentPage.on_menuEditCut_select(event)

    def on_menuEditCopy_select(self, event):
        if self.currentPage:
            self.currentPage.on_menuEditCopy_select(event)

    def on_menuEditPaste_select(self, event):
        if self.currentPage:
            self.currentPage.on_menuEditPaste_select(event)
        
    def on_menuEditClear_select(self, event):
        if self.currentPage:
            self.currentPage.on_menuEditClear_select(event)

    def on_menuEditSelectAll_select(self, event):
        if self.currentPage:
            self.currentPage.on_menuEditSelectAll_select(event)

    def findNext(self, searchText, wholeWordsOnly, caseSensitive):
        if searchText == '':
            return -1

        if not self.currentPage: return -1
        
        doc = self.currentDocument
        current = doc.GetCurrentPos()
        last = doc.GetLength()
        if wx.VERSION >= (2, 3, 3):
            flags = 0
            if caseSensitive:
                flags = flags + stc.STC_FIND_MATCHCASE
            if wholeWordsOnly:
                flags = flags + stc.STC_FIND_WHOLEWORD
            result = doc.FindText(current, last, searchText, flags)
        else:
            result = doc.FindText(current, last, searchText,
                         caseSensitive,
                         wholeWordsOnly)
        if result != -1:
            # update the selection, which also changes the cursor position
            n = len(searchText)
            doc.SetSelection(result, result + n)
        else:
            # should we beep or flash the screen or present an error dialog?
            pass
        return result


    def on_doEditFindReplace_command(self, event):
        if not self.currentPage: return
        data = wx.FindReplaceData()
        flags = data.GetFlags()
        data.SetFindString(self.lastFind['searchText'])
        data.SetReplaceString(self.lastFind['replaceText'])
        if self.lastFind['wholeWordsOnly']:
            flags = flags | wx.FR_WHOLEWORD
        if self.lastFind['caseSensitive']:
            flags = flags | wx.FR_MATCHCASE
        data.SetFlags(flags)
        dlg = wx.FindReplaceDialog(self, data, "Find & Replace", wx.FR_REPLACEDIALOG)
        dlg.data = data  # save a reference to it...
        # KEA 2004-04-18
        # can't use visible attribute
        # probably need to create a wrapper for FindReplaceDialog
        # to make it more like PythonCard
        #dlg.visible = True
        dlg.Show()

    def on_doEditReplaceTabs_command(self, event):
        self.replaceTabs()
        
    def on_doEditFind_command(self, event):
        # keep track of the last find and preload
        # the search text and radio buttons
        lastFind = self.lastFind

        result = dialog.findDialog(self, lastFind['searchText'],
                                lastFind['wholeWordsOnly'],
                                lastFind['caseSensitive'])

        if result.accepted:
            lastFind['searchText'] = result.searchText
            lastFind['wholeWordsOnly'] = result.wholeWordsOnly
            lastFind['caseSensitive'] = result.caseSensitive

            self.findNext(lastFind['searchText'],
                          lastFind['wholeWordsOnly'],
                          lastFind['caseSensitive'])

    def on_doEditFindNext_command(self, event):
        self.findNext(self.lastFind['searchText'],
                      self.lastFind['wholeWordsOnly'],
                      self.lastFind['caseSensitive'])
        
    def gotoLine(self, lineNumber):
        try:
            # GotoLine is zero based, but we ask the user
            # for a line number starting at 1
            self.currentDocument.GotoLine(lineNumber - 1)
        except:
            pass
        
    def on_doEditGoTo_command(self, event):
        result = dialog.textEntryDialog(self, self.resource.strings.gotoLineNumber, self.resource.strings.gotoLine, '')
        # this version doesn't alert the user if the line number is out-of-range
        # it just fails quietly
        if result.accepted:
            try:
                self.gotoLine(int(result.text))
            except:
                pass

    def on_indentRegion_command(self, event):
        if self.currentDocument:
            self.currentDocument.CmdKeyExecute(stc.STC_CMD_TAB)

    def on_dedentRegion_command(self, event):
        if self.currentDocument:
            self.currentDocument.CmdKeyExecute(stc.STC_CMD_BACKTAB)

    def on_commentRegion_command(self, event):
        if self.currentDocument:
            # need to do the equivelant of the IDLE
            # comment_region_event in AutoIndent.py
            doc = self.currentDocument
            sel = doc.GetSelection()
            start = doc.LineFromPosition(sel[0])
            end = doc.LineFromPosition(sel[1])
            if end > start and doc.GetColumn(sel[1]) == 0:
                end = end - 1
    
            doc.BeginUndoAction()
            for lineNumber in range(start, end + 1):
                firstChar = doc.PositionFromLine(lineNumber)
                doc.InsertText(firstChar, '##')
            doc.SetCurrentPos(doc.PositionFromLine(start))
            doc.SetAnchor(doc.GetLineEndPosition(end))
            doc.EndUndoAction()

    def on_uncommentRegion_command(self, event):
        if self.currentDocument:
            # need to do the equivelant of the IDLE
            # uncomment_region_event in AutoIndent.py
            doc = self.currentDocument
            sel = doc.GetSelection()
            start = doc.LineFromPosition(sel[0])
            end = doc.LineFromPosition(sel[1])
            if end > start and doc.GetColumn(sel[1]) == 0:
                end = end - 1
    
            doc.BeginUndoAction()
            for lineNumber in range(start, end + 1):
                firstChar = doc.PositionFromLine(lineNumber)
                if chr(doc.GetCharAt(firstChar)) == '#':
                    if chr(doc.GetCharAt(firstChar + 1)) == '#':
                        # line starts with ##
                        doc.SetCurrentPos(firstChar + 2)
                    else:
                        # line starts with #
                        doc.SetCurrentPos(firstChar + 1)
                    doc.DelLineLeft()
    
            doc.SetCurrentPos(doc.PositionFromLine(start))
            doc.SetAnchor(doc.GetLineEndPosition(end))
            doc.EndUndoAction()


    # View menu
    
    # These are treated as "global" commands - apply to all existing pages
    def on_menuViewWhitespace_select(self, event):
        tBool = event.IsChecked()
        for page in self.pages:
            page.components.document.SetViewWhiteSpace(tBool)

    def on_menuViewIndentationGuides_select(self, event):
        tBool = event.IsChecked()
        for page in self.pages:
            page.components.document.SetIndentationGuides(tBool)
        
    def on_menuViewRightEdgeIndicator_select(self, event):
        if event.IsChecked():
            for page in self.pages:
                page.components.document.SetEdgeMode(stc.STC_EDGE_LINE)
                #self.components.document.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
        else:
            for page in self.pages:
                page.document.SetEdgeMode(stc.STC_EDGE_NONE)

    def on_menuViewEndOfLineMarkers_select(self, event):
        tBool = event.IsChecked()
        for page in self.pages:
            page.components.document.SetViewEOL(tBool)

    def on_menuViewFixedFont_select(self, event):
        pass

    def on_menuViewLineNumbers_select(self, event):
        tBool = event.IsChecked()
        for page in self.pages:
            page.components.document.lineNumbersVisible = tBool

    def on_menuViewCodeFolding_select(self, event):
        tBool = event.IsChecked()
        for page in self.pages:
            page.components.document.codeFoldingVisible = tBool

    # Format menu

    def on_doSetStyles_command(self, event):
        config = configuration.getStyleConfigPath()
        if config is None:
            return

        cwd = os.curdir
        os.chdir(os.path.dirname(config))
        dlg = STCStyleEditor.STCStyleEditDlg(self, 
            'Python', 'python',
            #'HTML', 'html',
            #'XML', 'xml',
            #'C++', 'cpp',  
            #'Text', 'text',  
            #'Properties', 'prop',  
            config)
        try: dlg.ShowModal()
        finally: dlg.Destroy()
        os.chdir(cwd)
        self.setDefaultStyles()

    def on_menuFormatWrap_select(self, event):
        tBool = event.IsChecked()
        for page in self.pages:
            page.components.document.SetWrapMode(tBool)


    def wordCount(self, text):
        chars = len(text)
        words = len(text.split())
        # this doesn't always match the getNumberOfLines() method
        # so this should probably be changed
        lines = len(util.normalizeEOL(text).split('\n'))
        return chars, words, lines

    # Help menu
    
    def on_doHelpAbout_command(self, event):
        # once we have generic dialogs going, put a more interesting
        # About box here
        if self.currentPage.documentPath is None:
            filename = self.resource.strings.untitled
        else:
            filename = os.path.basename(self.currentPage.documentPath)
        countString = "%d " + self.resource.strings.chars + \
            ", %d " + self.resource.strings.words + \
            ", %d " + self.resource.strings.lines
        dialog.messageDialog(self,
                             self.resource.strings.sample + "\n\n" + \
                             self.resource.strings.document + ": %s\n" % filename + \
                             countString \
                             % self.wordCount(self.currentDocument.text),
                             self.resource.strings.about,
                             wx.ICON_INFORMATION | wx.OK)

    def on_doHelpAboutPythonCard_command(self, event):
        about.aboutPythonCardDialog(self)

    def on_menuScriptletShell_select(self, event):
        self.loadShell()

        if self.application.shell is not None:
            self.application.shellFrame.visible = not self.application.shellFrame.visible

    def on_menuScriptletNamespace_select(self, event):
        self.loadNamespace()

        if self.application.namespace is not None:
            self.application.namespaceFrame.visible = not self.application.namespaceFrame.visible

    def on_menuScriptletSaveUserConfiguration_select(self, event):
        configuration.saveUserConfiguration(self.application)
        
    def on_menuShellChangeDirectory_select(self, event):
        try:
            if self.currentPage.documentPath:
                path = os.path.dirname(self.currentPage.documentPath)
            else:
                path = ''
            result = dialog.directoryDialog(self, 'Choose a directory', path)
            if result.accepted:
                path = result.path
                os.chdir(path)
                self.application.shell.run('os.getcwd()')
        except:
            pass

    def on_menuScriptletSaveShellSelection_select(self, event):
        if self.application.shell is not None:
            txt = self.application.shell.GetSelectedText()
            lines = []
            for line in txt.splitlines():
                lines.append(self.application.shell.lstripPrompt(line))
            # this is the quick way to convert a list back into a string
            # appending to strings can be slow because it creates a new string
            # each time, so a list is used instead while building up the script
            script = '\n'.join(lines)
            try:
                #wildcard = "Python files (*.py)|*.py|All Files (*.*)|*.*"
                wildcard = self.resource.strings.scriptletWildcard
                scriptletsDir = os.path.join(self.application.applicationDirectory, 'scriptlets')
                result = dialog.saveFileDialog(None, self.resource.strings.saveAs, scriptletsDir, 'scriptlet.py', wildcard)
                if result.accepted:
                    path = result.paths[0]
                    f = open(path, 'w')
                    f.write(script)
                    f.close()
            except:
                pass

    def execScriptlet(self, filename):
        #try:
        command = 'execfile(%r)' % filename
        self.application.shell.run(command=command, prompt=0, verbose=0)
        #except:
        #    pass

    def on_menuScriptletRunScriptlet_select(self, event):
        self.loadShell()

        #curDir = os.getcwd()
        if self.application.shell is not None:
            #wildcard = "Python files (*.py)|*.py|All Files (*.*)|*.*"
            wildcard = self.resource.strings.scriptletWildcard
            # wildcard = '*.py'
            scriptletsDir = os.path.join(self.application.applicationDirectory, 'scriptlets')
            result = dialog.openFileDialog(self, self.resource.strings.openFile, scriptletsDir, '', wildcard)
            if result.accepted:
                filename = result.paths[0]
                self.execScriptlet(filename)
        #os.chdir(curDir)

    """
>>> mb = bg.menuBar
>>> m = mb.menus[4]
>>> from PythonCard import menu, resource
>>> rsrc = resource.Resource({'type':'MenuItem', 'name': 'scriptletSep2', 'label':'-'})
>>> mi = menu.MenuItem(bg, m, rsrc)
>>> m.appendMenuItem(mi)
>>> rsrc = resource.Resource({'type':'MenuItem', 'name': 'menuScriptletinsertDateAndTime', 'label':'insertDateAndTime\tCtrl+1', 'command':'runMacro'})
>>> mi = menu.MenuItem(bg, m, rsrc)
>>> m.appendMenuItem(mi)

    """
    """
    Need to have a "Macros" dialog that let's the user select a script to
    run, a label for the script which will default to the script name,
    and a hot key. The dialog will prepend menuScriptlet on the front,
    add the item to the menu and store it in the config so it is remembered
    between loads.
    """
    def on_runMacro_command(self, event):
        name = event.target.name[len('menuScriptlet'):]
        #scriptletsDir = os.path.join(self.application.applicationDirectory, 'scriptlets')
        #filename = os.path.join(scriptletsDir, name + '.py')
        for macro in self.macros:
            if macro['label'] == name:
                filename = macro['filename']
                self.execScriptlet(filename)
                break
    

    def on_checkSyntax_command(self, event):
        if self.currentPage.documentPath is None:
            save = self.saveChanges(self.currentPage.documentPath)
            if save == "Cancel" or save == "No":
                # don't do anything, just go back to editing
                # we have to have a file on disk to check
                # if we used StringIO we could simulate a file
                # but I don't know if it is worth it
                pass
            else:
                if self.on_menuFileSaveAs_select(None):
                    scriptutils.CheckFile(self.statusBar, self.currentDocument, self.currentPage.documentPath)
                    self.lastPos = self.currentDocument.GetCurrentPos()
        else:
            if self.currentDocument.GetModify():
                # auto-save
                self.currentPage.saveFile(self.currentPage.documentPath)
            scriptutils.CheckFile(self.statusBar, self.currentDocument, self.currentPage.documentPath)
            self.lastPos = self.currentDocument.GetCurrentPos()
    
    def on_fileRunOptions_command(self, event):
        result = runOptionsDialog.runOptionsDialog(self, self.cmdLineArgs)
        if result.accepted:
            self.cmdLineArgs['debugmenu'] = result.debugmenu
            self.cmdLineArgs['logging'] = result.logging
            self.cmdLineArgs['messagewatcher'] = result.messagewatcher
            self.cmdLineArgs['namespaceviewer'] = result.namespaceviewer
            self.cmdLineArgs['propertyeditor'] = result.propertyeditor
            self.cmdLineArgs['shell'] = result.shell
            self.cmdLineArgs['otherargs'] = result.otherargs


    # script running code
    
    def runScript(self, useInterpreter):
        if self.currentPage.documentPath is None:
            save = self.saveChanges(self.currentPage.documentPath)
            if save == "Cancel" or save == "No":
                # don't do anything, just go back to editing
                return
            else:
                if not self.on_menuFileSaveAs_select(None):
                    # they didn't actually save, just go back
                    # to editing
                    return
        elif self.currentDocument.GetModify():
            # auto-save
            self.currentPage.saveFile(self.currentPage.documentPath)

        # this algorithm, taken from samples.py assumes the rsrc.py file and the main
        # program file have the same basename
        # if that isn't the case then this doesn't work and we need a different solution
        path, filename = os.path.split(self.currentPage.documentPath)
        if wx.Platform == '__WXMAC__':
            filename = self.currentPage.documentPath
        else:
            if ' ' in self.currentPage.documentPath:
                filename = '"' + self.currentPage.documentPath + '"'
            else:
                filename = self.currentPage.documentPath

        # the args should come from a dialog or menu items that are checked/unchecked
        args = util.getCommandLineArgs(self.cmdLineArgs)

        # change to the script directory before attempting to run
        curdir = os.path.dirname(os.path.abspath(os.curdir))
        os.chdir(os.path.dirname(self.currentPage.documentPath))

        if wx.Platform == '__WXMAC__':
            # this is a bad hack to deal with the user starting
            # codeEditor.py from the Finder
            if sys.executable == '/':
                python = '/Applications/Python.app/Contents/MacOS/python'
            else:
                python = sys.executable
        elif wx.Platform == '__WXMSW__':
            # always launch with a console
            python = os.path.join(os.path.dirname(sys.executable), 'python.exe')
        else:
            python = sys.executable
        if ' ' in python:
            pythonQuoted = '"' + python + '"'
        else:
            pythonQuoted = python

        if useInterpreter:
            os.spawnv(os.P_NOWAIT, python, [pythonQuoted, '-i', filename] + args)
        else:
            os.spawnv(os.P_NOWAIT, python, [pythonQuoted, filename] + args)

        os.chdir(curdir)

    def on_fileRun_command(self, event):
        # KEA 2001-12-14
        # we should prompt to save the file if needed
        # or in the case of a new file, do a save as before attempting
        # to do a run
        self.runScript(0)

    def on_fileRunWithInterpreter_command(self, event):
        # KEA 2001-12-14
        # we should prompt to save the file if needed
        # or in the case of a new file, do a save as before attempting
        # to do a run
        self.runScript(1)

    def on_findFiles_command(self, event):
        fn = self.application.applicationDirectory
        fn = os.path.join(fn, os.pardir, "findfiles", "findfiles.py")
        fn = os.path.normpath(fn)
        if not os.path.isfile(fn):
            return

        if wx.Platform == '__WXMAC__':
            filename = fn
        else:
            filename = '"' + fn + '"'

        if wx.Platform == '__WXMAC__':
            # this is a bad hack to deal with the user starting
            # codeEditor.py from the Finder
            if sys.executable == '/':
                python = '/Applications/Python.app/Contents/MacOS/python'
            else:
                python = sys.executable
        elif wx.Platform == '__WXMSW__':
            python = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe')
        else:
            python = sys.executable
        if ' ' in python:
            pythonQuoted = '"' + python + '"'
        else:
            pythonQuoted = python

        os.spawnv(os.P_NOWAIT, python, [pythonQuoted, filename])

    def on_showShellDocumentation_command(self, event):
        global shell_url
        webbrowser.open(shell_url)

    def on_showPythonCardDocumentation_command(self, event):
        global pythoncard_url
        webbrowser.open(pythoncard_url)

    def on_showPythonDocumentation_command(self, event):
        global help_url

        if sys.platform.startswith("win"):
        # KEA 2003-10-15   AGT 2005-12-20
        # BIG hack for Python 2.3 Windows help file or Python 2.4
        # need to decide on a clean way of handling various doc options
            fn = os.path.dirname(os.__file__)
            chmfile = "Python" + sys.version[0] + sys.version[2] + ".chm"
            fn = os.path.join(fn, os.pardir, "Doc", chmfile)
            fn = os.path.normpath(fn)
            if os.path.isfile(fn):
                os.startfile(fn)
        else:
            webbrowser.open(help_url)

    def on_notebook_pageChanging(self, event):
        #rint "pageChanging - oldSelection: %d, selection: %d" % (event.oldSelection, event.selection)
        event.skip()

    def on_notebook_pageChanged(self, event):
        self.pageChangedFired = True
        #rint "pageChanged  - oldSelection: %d, selection: %d" % (event.oldSelection, event.selection)
        if event.selection <= len(self.pages)-1:
            self.currentPageNumber = event.selection
            self.currentPage = self.pages[event.selection]
            self.currentDocument = self.currentPage.components.document
            self.currentPage.becomeFocus()
            self.updateStatusBar()
            self.updateTitleBar()
            self.setResourceFile()
            wx.CallAfter(self.currentPage.SetFocus)
        event.skip()
            

# KEA 2004-08-18
# I'll probably move this functionality into model.Application
# and just call a macOpenFile method in the current background
class MyApplication(model.Application):
    # support drag and drop on the application icon on the Mac
    def MacOpenFile(self, filename):
        # code to load filename goes here
        self.backgrounds[0].openFile(filename)


if __name__ == '__main__':
    app = MyApplication(TabCodeEditor)
    app.MainLoop()