-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathMain.py
4030 lines (3251 loc) · 147 KB
/
Main.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
#!/usr/bin/env python
#----------------------------------------------------------------------------
# Name: Main.py
# Purpose: Testing lots of stuff, controls, window types, etc.
#
# Author: Robin Dunn
#
# Created: A long time ago, in a galaxy far, far away...
# RCS-ID: $Id: Main.py 71772 2012-06-14 22:37:10Z RD $
# Copyright: (c) 1999 by Total Control Software
# Licence: wxWindows license
# Tags: phoenix-port
#----------------------------------------------------------------------------
# TODO List:
# * UI design more professional (is the new version more professional?)
# * Update main overview
# =====================
# = EXTERNAL Packages =
# =====================
# In order to let a package (like AGW) be included in the wxPython demo,
# the package owner should create a sub-directory of the wxPython demo folder
# in which all the package's demos should live. In addition, the sub-folder
# should contain a Python file called __demo__.py which, when imported, should
# contain the following methods:
#
# * GetDemoBitmap: returns the bitmap to be used in the wxPython demo tree control
# in a PyEmbeddedImage format;
# * GetRecentAdditions: returns a list of demos which will be displayed under the
# "Recent Additions/Updates" tree item. This list should be a subset (or the full
# set) of the package's demos;
# * GetDemos: returns a tuple. The first item of the tuple is the package's name
# as will be displayed in the wxPython demo tree, right after the "Custom Controls"
# item. The second element of the tuple is the list of demos for the external package.
# * GetOverview: returns a wx.html-ready representation of the package's documentation.
#
# Please see the __demo__.py file in the demo/agw/ folder for an example.
# Last updated: Andrea Gavana, 20 Oct 2008, 18.00 GMT
#-Imports-------------------------------------------------------------------
#--Python Imports.
import os
import sys
if sys.version_info[0] == 2:
print('Running Python 2')
PYTHON2 = True
PYTHON3 = False
elif sys.version_info[0] == 3:
print('Running Python 3')
PYTHON2 = False
PYTHON3 = True
import time
import traceback
import types
import imp
try:
import cPickle as pickle
except ImportError as exc:#py3
import pickle
try:
from cStringIO import StringIO
except ImportError as exc:#py3
from io import StringIO
import re
try:
import urllib2 as urllib
except ImportError as exc:#py3
import urllib
import shutil
from threading import Thread
# Fixing the old bird...
import py_compile # Compile files before executing them to look for syntax errors/etc.
import subprocess # Launch individual demos.
import site # Locate the wx.pth file in the site-packages directory.
try:
import six
except ImportError:
traceback.print_exc()
try:
import wx.lib.six as six
except ImportError as exc:
raise exc
#--wxPython Imports.
### try:
### import wxversion
### wxversion.select('3.0.3-msw-phoenix') # Used to force wxPython version
### except ImportError:
### traceback.print_exc()
try:
import wx
# print(wx.version())
except ImportError:
import tkinter_error
msg = ('You must install wxPython, which can be downloaded at\n'
'http://wxpython.org/')
tkinter_error.tkinter_error(msg)
exit()
import wx.adv
import wx.lib.agw.aui as aui
import wx.html
import wx.lib
from wx.lib.msgpanel import MessagePanel
from wx.adv import TaskBarIcon as TaskBarIcon
from wx.adv import SplashScreen as SplashScreen
import wx.lib.mixins.inspection
import wx.lib.mixins.listctrl as listmix
import wx.lib.wxpTag
if not hasattr(wx, 'ID_HELP_CONTENTS'):
# Used for overview wxp online link buttons.
wx.ID_HELP_CONTENTS = wx.NewId()
#--Local Imports.
import version
# from main_globals import _demoPngsList, _treeList
from ExceptionHookDialog import ExceptionHookDialog, ExceptionStrDialog
#- Override sys.excepthook ----------------------------
# Place this bit of code in your app if you want to overide sys.excepthook.
# Otherwise sys.excepthook defaults to sys.stderr
def custom_excepthook(excType, excValue, excTrace):
excInfo=(excType, excValue, excTrace)
ExceptionHookDialog(excInfo=excInfo).ShowModal()
## sys.excepthook = sys.stderr # Standard procedure
# Our ExceptionHookDialog will be called every time there is an error
# while the demo is actually running.
# This includes extended demos with TestPanels.
# Ex: Sometimes a demo will need to launch a frame(ex: show a "example" button)
# and the error might not have been caught in py_compiling and was
# ran into in the frames __init__ or somewhere after.
# We want to know right away where the error occured so it can be fixed. :)
sys.excepthook = custom_excepthook
#-Debugging-----------------------------------------------------------------
DEBUG = False
def debugPrint():
print("\n=Debug" + "="*54)
## wx.Trap()
print("wx.version() = %s" %(wx.version()))
print("wx.VERSION_STRING = %s" %(wx.VERSION_STRING))
print("pid = %s" %(os.getpid()))
print(sys.version_info)
print("sys.platform = %s" %(sys.platform))
import platform
if sys.platform.startswith('win'):
win32_ver = platform.win32_ver()
print('Microsoft Windows %s %s %s %s' %(win32_ver[0], win32_ver[1], win32_ver[2], win32_ver[3]))
elif sys.platform.startswith('linux'):
linux_dist = platform.linux_distribution()
print('%s %s %s' %(linux_dist[0], linux_dist[1], linux_dist[2]))
elif sys.platform.startswith('darwin'):
mac_ver = platform.mac_ver()
print('Macintosh %s %s %s' %(mac_ver[0], mac_ver[1], mac_ver[2]))
print("sys.argv = %s" %(sys.argv))
print("="*60)
if PYTHON2:
raw_input("Press Enter To Continue...")
elif PYTHON3:
input("Press Enter To Continue...")
if DEBUG:
debugPrint()
elif len(sys.argv) > 1:
for i in range(1, len(sys.argv)):
arg = sys.argv[i]
if "-d" or "-debug" in arg:
debugPrint()
break
#-Globals-------------------------------------------------------------------
gAppDir = os.path.dirname(os.path.abspath(sys.argv[0]))
# print(site.getsitepackages())
# for path in site.getsitepackages():
# if 'site-packages' in path or 'dist-packages' in path: # Windows, Unix
# sitePackagesDir = path
# break
#
# if os.path.exists(sitePackagesDir + os.sep + 'wx.pth'):
# # print(site.getsitepackages())
# # returned on windows ['C:\\Python27', 'C:\\Python27\\lib\\site-packages']
# ('site-packages', 'dist-packages')
# wx_pth_Path = sitePackagesDir + os.sep + 'wx.pth'
# fileIsOpen = open(wx_pth_Path, 'r')
# wx_pth_Path_Contents = fileIsOpen.read()
# fileIsOpen.close()
# else:
# wx_pth_Path = 'wx.pth could not be located'
# print(wx_pth_Path)
# print(site.getsitepackages())
# wx_pth_Path_Contents = 'wx.pth could not be located'
# We won't import the images module yet, but we'll assign it to this
# global when we do.
images = None
RUN_AS_PORTABLE_APP = True
try:
PORTABLE_PATH = os.path.dirname(os.path.abspath(__file__))
except Exception as exc:
PORTABLE_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
USE_CUSTOMTREECTRL = False
DEFAULT_PERSPECTIVE = "Default Perspective"
_styleTable = '<h3>Window %s</h3>\n' \
'<p>This class supports the following window %s:\n' \
'<p><table bgcolor=\"#ffffff\" border cols=1>'
_eventTable = '<h3>Events</h3>\n' \
'<p>Events emitted by this class:\n' \
'<p><table bgcolor=\"#ffffff\" border cols=1>'
_appearanceTable = '<h3>Appearance</h3>\n' \
'<p>Control appearance on various platform:\n' \
'<p><table bgcolor=\"#ffffff\" cellspacing=20>'
_styleHeaders = ["Style Name", "Description"]
_eventHeaders = ["Event Name", "Description"]
_headerTable = '<td><b>%s</b></td>'
_styleTag = '<td><tt>%s</tt></td>'
_eventTag = '<td><i>%s</i></td>'
_hexValues = '<td><font color="%s"> %s </font></td>'
_description = '<td>%s</td>'
_imageTag = '<td align=center valign=middle><a href="%s"><img src="%s" alt="%s"></a></td>'
_platformTag = '<td align=center><b>%s</b></td>'
_onlineURLS = ["http://www.wxwidgets.org/",
"http://wxpython.org/",
"http://www.python.org/"]
_trunkURL = "http://docs.wxwidgets.org/trunk/"
_docsURL = _trunkURL + "classwx%s.html"
_platformNames = ["wxMSW", "wxGTK", "wxMac"]
_importList = ["wx.aui", "wx.calendar", "wx.html", "wx.media", "wx.wizard",
"wx.combo", "wx.animate", "wx.gizmos", "wx.glcanvas", "wx.grid",
"wx.richtext", "wx.stc"]
_dirWX = dir(wx)
for mod in _importList:
try:
module = __import__(mod)
except ImportError as exc:
continue
_codePagePositions = {}
# Define a translation function.
_ = wx.GetTranslation
def imp_load_source_from_filePath(filePath):
mod_name, file_ext = os.path.splitext(os.path.split(filePath)[-1])
if file_ext.lower() in ('.py', '.pyw'):
py_mod = imp.load_source(mod_name, filePath)
return py_mod
#------------------------------------------------------------------------------
def ReplaceCapitals(string):
"""
Replaces the capital letter in a string with an underscore plus the
corresponding lowercase character.
**Parameters:**
* `string`: the string to be analyzed.
"""
newString = ""
for char in string:
if char.isupper():
newString += "_%s"%char.lower()
else:
newString += char
return newString
def RemoveHTMLTags(data):
"""
Removes all the HTML tags from a string.
**Parameters:**
* `data`: the string to be analyzed.
"""
p = re.compile(r'<[^<]*?>')
return p.sub('', data)
def FormatDocs(keyword, values, num):
names = values.keys()
names = sorted(values.keys())
headers = (num == 2 and [_eventHeaders] or [_styleHeaders])[0]
table = (num == 2 and [_eventTable] or [_styleTable])[0]
if num == 3:
text = "<br>" + table%(keyword.lower(), keyword.lower()) + "\n<tr>\n"
else:
text = "<br>" + table
for indx in range(2):
text += _headerTable%headers[indx]
text += "\n</tr>\n"
for name in names:
text += "<tr>\n"
description = values[name].strip()
pythonValue = name.replace("wx", "wx.")
if num == 3:
colour = "#ff0000"
value = "Unavailable"
cutValue = pythonValue[3:]
if cutValue in _dirWX:
try:
val = eval(pythonValue)
value = "%s"%hex(val)
colour = "#0000ff"
except AttributeError as exc:
value = "Unavailable"
else:
for packages in _importList:
if cutValue in dir(eval(packages)):
val = eval("%s.%s"%(packages, cutValue))
value = "%s"%hex(val)
colour = "#0000ff"
pythonValue = "%s.%s"%(packages, cutValue)
break
text += _styleTag%pythonValue + "\n"
else:
text += _eventTag%pythonValue + "\n"
text += _description%FormatDescription(description) + "\n"
text += "</tr>\n"
text += "\n</table>\n\n<p>"
return text
def FormatDescription(description):
"""
Formats a wxWidgets C++ description in a more wxPython-based way.
**Parameters:**
* `description`: the string description to be formatted.
"""
description = description.replace("wx", "wx.")
description = description.replace("EVT_COMMAND", "wxEVT_COMMAND")
description = description.replace("wx.Widgets", "wxWidgets")
return description
def FormatImages(appearance):
text = "<p><br>" + _appearanceTable
for indx in range(2):
text += "\n<tr>\n"
for key in _platformNames:
if indx == 0:
src = appearance[key]
alt = key + "Appearance"
text += _imageTag%(src, src, alt)
else:
text += _platformTag%key
text += "</tr>\n"
text += "\n</table>\n\n<p>"
return text
def FindWindowStyles(text, originalText, widgetName):
"""
Finds the windows styles and events in the input text.
**Parameters:**
* `text`: the wxWidgets C++ docs for a particular widget/event, stripped
of all HTML tags;
* `originalText`: the wxWidgets C++ docs for a particular widget/event, with
all HTML tags.
"""
winStyles, winEvents, winExtra, winAppearance = {}, {}, {}, {}
inStyle = inExtra = inEvent = False
for line in text:
if "following styles:" in line:
inStyle = True
continue
elif "Event macros" in line:
inEvent = True
continue
if "following extra styles:" in line:
inExtra = True
continue
if "Appearance:" in line:
winAppearance = FindImages(originalText, widgetName)
continue
elif not line.strip():
inStyle = inEvent = inExtra = False
continue
if inStyle:
start = line.index(':')
windowStyle = line[0:start]
styleDescription = line[start+1:]
winStyles[windowStyle] = styleDescription
elif inEvent:
start = line.index(':')
eventName = line[0:start]
eventDescription = line[start+1:]
winEvents[eventName] = eventDescription
elif inExtra:
start = line.index(':')
styleName = line[0:start]
styleDescription = line[start+1:]
winExtra[styleName] = styleDescription
return winStyles, winEvents, winExtra, winAppearance
def FindImages(text, widgetName):
"""
When the wxWidgets docs contain a/the control appearance (a screenshot of the
control), this method will try and download the images.
**Parameters:**
* `text`: the wxWidgets C++ docs for a particular widget/event, with
all HTML tags.
"""
winAppearance = {}
start = text.find("class='appearance'")
if start < 0:
return winAppearance
imagesDir = GetDocImagesDir()
end = start + text.find("</table>")
text = text[start:end]
split = text.split()
for indx, items in enumerate(split):
if "src=" in items:
possibleImage = items.replace("src=", "").strip()
possibleImage = possibleImage.replace("'", "")
f = urllib.urlopen(_trunkURL + possibleImage)
stream = f.read()
elif "alt=" in items:
plat = items.replace("alt=", "").replace("'", "").strip()
path = os.path.join(imagesDir, plat, widgetName + ".png")
if not os.path.isfile(path):
image = wx.Image(StringIO.StringIO(stream))
image.SaveFile(path, wx.BITMAP_TYPE_PNG)
winAppearance[plat] = path
return winAppearance
#------------------------------------------------------------------------------
# Set up a thread that will scan the wxWidgets docs for window styles,
# events and widgets screenshots
class InternetThread(Thread):
""" Worker thread class to attempt connection to the internet. """
def __init__(self, notifyWindow, selectedClass):
Thread.__init__(self)
self.notifyWindow = notifyWindow
self.selectedClass = selectedClass
self.keepRunning = True
self.setDaemon(True)
self.start()
def run(self):
""" Run the worker thread. """
# This is the code executing in the new thread. Simulation of
# a long process as a simple urllib2/urllib call
try:
url = _docsURL % ReplaceCapitals(self.selectedClass)
fid = urllib.urlopen(url)
originalText = fid.read()
text = RemoveHTMLTags(originalText).split("\n")
data = FindWindowStyles(text, originalText, self.selectedClass)
if not self.keepRunning:
return
wx.CallAfter(self.notifyWindow.LoadDocumentation, data)
except (IOError, urllib.HTTPError) as exc:
# Unable to get to the internet
t, v = sys.exc_info()[:2]
message = traceback.format_exception_only(t, v)
wx.CallAfter(self.notifyWindow.StopDownload, message)
except Exception as exc:
# Some other strange error...
t, v = sys.exc_info()[:2]
message = traceback.format_exception_only(t, v)
wx.CallAfter(self.notifyWindow.StopDownload, message)
#------------------------------------------------------------------------------
# Show how to derive a custom wxLog class
class MyLog(wx.Log):
def __init__(self, textCtrl, logTime=0):
wx.Log.__init__(self)
self.tc = textCtrl
self.logTime = logTime
def DoLogText(self, message):
if self.tc:
self.tc.AppendText(message + '\n')
#------------------------------------------------------------------------------
# A class to be used to display source code in the demo. Try using the
# wxSTC in the StyledTextCtrl_2 sample first, fall back to wxTextCtrl
# if there is an error, such as the stc module not being present.
#
try:
##raise ImportError # for testing the alternate implementation
from wx import stc
from StyledTextCtrl_DemoCode import PythonSTC
class DemoCodeEditor(PythonSTC):
__doc__ = wx.stc.StyledTextCtrl.__doc__
def __init__(self, parent, style=wx.BORDER_NONE):
PythonSTC.__init__(self, parent, -1, style=style)
self.parent = parent
global gSTC
gSTC = self
global gStcConfig
gStcConfig = GetStcConfig()
self.SetUpEditorFromConfig(stcConfig=gStcConfig)
# self.SetUpEditor()
# Some methods to make it compatible with how the wxTextCtrl is used
def SetValue(self, value):
## value = value.decode('iso8859_1')
val = self.GetReadOnly()
self.SetReadOnly(False)
self.SetText(value)
self.EmptyUndoBuffer()
self.SetSavePoint()
self.SetReadOnly(val)
def SetEditable(self, val):
self.SetReadOnly(not val)
def IsModified(self):
return self.GetModify()
def Clear(self):
self.ClearAll()
def SetInsertionPoint(self, pos):
self.SetCurrentPos(pos)
self.SetAnchor(pos)
def ShowPosition(self, pos):
line = self.LineFromPosition(pos)
#self.EnsureVisible(line)
self.GotoLine(line)
def GetLastPosition(self):
return self.GetLength()
def GetPositionFromLine(self, line):
return self.PositionFromLine(line)
def GetRange(self, start, end):
return self.GetTextRange(start, end)
def GetSelection(self):
return self.GetAnchor(), self.GetCurrentPos()
def SetSelection(self, start, end):
self.SetSelectionStart(start)
self.SetSelectionEnd(end)
def SelectLine(self, line):
start = self.PositionFromLine(line)
end = self.GetLineEndPosition(line)
self.SetSelection(start, end)
def SetUpEditor(self):
"""
This method carries out the work of setting up the demo editor.
It's seperate so as not to clutter up the init code.
"""
import keyword
self.SetLexer(stc.STC_LEX_PYTHON)
self.SetKeyWords(0, " ".join(keyword.kwlist))
# Enable folding
self.SetProperty("fold", "1" )
# Highlight tab/space mixing (shouldn't be any)
self.SetProperty("tab.timmy.whinge.level", "1")
# Set left and right margins
self.SetMargins(2,2)
# Set up the numbers in the margin for margin #1
self.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
# Reasonable value for, say, 4-5 digits using a mono font (40 pix)
self.SetMarginWidth(1, 40)
# Indentation and tab stuff
self.SetIndent(4) # Proscribed indent size for wx
self.SetIndentationGuides(True) # Show indent guides
self.SetBackSpaceUnIndents(True)# Backspace unindents rather than delete 1 space
self.SetTabIndents(True) # Tab key indents
self.SetTabWidth(4) # Proscribed tab size for wx
self.SetUseTabs(False) # Use spaces rather than tabs, or
# TabTimmy will complain!
# White space
self.SetViewWhiteSpace(False) # Don't view white space
# EOL: Since we are loading/saving ourselves, and the
# strings will always have \n's in them, set the STC to
# edit them that way.
self.SetEOLMode(wx.stc.STC_EOL_LF)
self.SetViewEOL(False)
# No right-edge mode indicator
self.SetEdgeMode(stc.STC_EDGE_NONE)
# Setup a margin to hold fold markers
self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
self.SetMarginSensitive(2, True)
self.SetMarginWidth(2, 12)
# and now set up the fold markers
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "black")
# Global default style
if wx.Platform == '__WXMSW__':
self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
'fore:#000000,back:#FFFFFF,face:Courier New')
elif wx.Platform == '__WXMAC__':
# TODO: if this looks fine on Linux too, remove the Mac-specific case
# and use this whenever OS != MSW.
self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
'fore:#000000,back:#FFFFFF,face:Monaco')
else:
defsize = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT).GetPointSize()
self.StyleSetSpec(stc.STC_STYLE_DEFAULT,
'fore:#000000,back:#FFFFFF,face:Courier,size:%d'%defsize)
# Clear styles and revert to default.
self.StyleClearAll()
# Following style specs only indicate differences from default.
# The rest remains unchanged.
# Line numbers in margin
self.StyleSetSpec(wx.stc.STC_STYLE_LINENUMBER,'fore:#000000,back:#99A9C2')
# Highlighted brace
self.StyleSetSpec(wx.stc.STC_STYLE_BRACELIGHT,'fore:#00009D,back:#FFFF00')
# Unmatched brace
self.StyleSetSpec(wx.stc.STC_STYLE_BRACEBAD,'fore:#00009D,back:#FF0000')
# Indentation guide
self.StyleSetSpec(wx.stc.STC_STYLE_INDENTGUIDE, "fore:#CDCDCD")
# Python styles
self.StyleSetSpec(wx.stc.STC_P_DEFAULT, 'fore:#000000')
# Comments
self.StyleSetSpec(wx.stc.STC_P_COMMENTLINE, 'fore:#008000,back:#F0FFF0')
self.StyleSetSpec(wx.stc.STC_P_COMMENTBLOCK, 'fore:#008000,back:#F0FFF0')
# Numbers
self.StyleSetSpec(wx.stc.STC_P_NUMBER, 'fore:#008080')
# Strings and characters
self.StyleSetSpec(wx.stc.STC_P_STRING, 'fore:#800080')
self.StyleSetSpec(wx.stc.STC_P_CHARACTER, 'fore:#800080')
# Keywords
self.StyleSetSpec(wx.stc.STC_P_WORD, 'fore:#000080,bold')
# Triple quotes
self.StyleSetSpec(wx.stc.STC_P_TRIPLE, 'fore:#800080,back:#FFFFEA')
self.StyleSetSpec(wx.stc.STC_P_TRIPLEDOUBLE, 'fore:#800080,back:#FFFFEA')
# Class names
self.StyleSetSpec(wx.stc.STC_P_CLASSNAME, 'fore:#0000FF,bold')
# Function names
self.StyleSetSpec(wx.stc.STC_P_DEFNAME, 'fore:#008080,bold')
# Operators
self.StyleSetSpec(wx.stc.STC_P_OPERATOR, 'fore:#800000,bold')
# Identifiers. I leave this as not bold because everything seems
# to be an identifier if it doesn't match the above criteria
self.StyleSetSpec(wx.stc.STC_P_IDENTIFIER, 'fore:#000000')
# Caret color
self.SetCaretForeground("BLUE")
# Selection background
self.SetSelBackground(1, '#66CCFF')
self.SetSelBackground(True, wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
self.SetSelForeground(True, wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT))
def RegisterModifiedEvent(self, eventHandler):
self.Bind(wx.stc.EVT_STC_CHANGE, eventHandler)
except ImportError as exc:
class DemoCodeEditor(wx.TextCtrl):
def __init__(self, parent):
wx.TextCtrl.__init__(self, parent, -1, style=
wx.TE_MULTILINE | wx.HSCROLL | wx.TE_RICH2 | wx.TE_NOHIDESEL)
def RegisterModifiedEvent(self, eventHandler):
self.Bind(wx.EVT_TEXT, eventHandler)
def SetReadOnly(self, flag):
self.SetEditable(not flag)
# NOTE: STC already has this method
def GetText(self):
return self.GetValue()
def GetPositionFromLine(self, line):
return self.XYToPosition(0,line)
def GotoLine(self, line):
pos = self.GetPositionFromLine(line)
self.SetInsertionPoint(pos)
self.ShowPosition(pos)
def SelectLine(self, line):
start = self.GetPositionFromLine(line)
end = start + self.GetLineLength(line)
self.SetSelection(start, end)
#------------------------------------------------------------------------------
# Constants for module versions
modOriginal = 0
modModified = 1
modDefault = modOriginal
#------------------------------------------------------------------------------
class DemoCodePanel(wx.Panel):
"""Panel for the 'Demo Code' tab"""
__doc__ = wx.Panel.__doc__
def __init__(self, parent, mainFrame):
wx.Panel.__init__(self, parent, size=(1,1))
if 'wxMSW' in wx.PlatformInfo:
self.Hide()
self.mainFrame = mainFrame
self.editor = DemoCodeEditor(self)
self.editor.RegisterModifiedEvent(self.OnCodeModified)
self.editorStatusBar = wx.TextCtrl(self, -1, 'Ready to code :)', style=wx.TE_READONLY)
self.btnSave = wx.Button(self, -1, "Save Changes")
self.btnRestore = wx.Button(self, -1, "Delete Modified")
self.btnSave.Enable(False)
self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
self.btnRestore.Bind(wx.EVT_BUTTON, self.OnRestore)
self.radioButtons = { modOriginal: wx.RadioButton(self, -1, "Original", style=wx.RB_GROUP),
modModified: wx.RadioButton(self, -1, "Modified") }
self.controlBox = wx.BoxSizer(wx.HORIZONTAL)
self.controlBox.Add(wx.StaticText(self, -1, "Active Version:"), 0,
wx.RIGHT | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5)
for modID, radioButton in self.radioButtons.items():
self.controlBox.Add(radioButton, 0, wx.EXPAND | wx.RIGHT, 5)
radioButton.modID = modID # makes it easier for the event handler
radioButton.Bind(wx.EVT_RADIOBUTTON, self.OnRadioButton)
self.controlBox.Add(self.btnSave, 0, wx.RIGHT, 5)
self.controlBox.Add(self.btnRestore, 0)
self.box = wx.BoxSizer(wx.VERTICAL)
self.box.Add(self.controlBox, 0, wx.EXPAND)
self.box.Add(wx.StaticLine(self), 0, wx.EXPAND)
self.box.Add(self.editor, 1, wx.EXPAND)
self.box.Add(self.editorStatusBar, 0, wx.EXPAND)
self.box.Fit(self)
self.SetSizer(self.box)
# Loads a demo from a DemoModules object
def LoadDemo(self, demoModules):
self.demoModules = demoModules
if (modDefault == modModified) and demoModules.Exists(modModified):
demoModules.SetActive(modModified)
else:
demoModules.SetActive(modOriginal)
self.radioButtons[demoModules.GetActiveID()].Enable(True)
self.ActiveModuleChanged()
def ActiveModuleChanged(self):
self.LoadDemoSource(self.demoModules.GetSource())
self.UpdateControlState()
self.mainFrame.pnl.Freeze()
self.ReloadDemo()
self.mainFrame.pnl.Thaw()
def LoadDemoSource(self, source):
self.editor.Clear()
self.editor.SetValue(source)
self.JumpToLine(0)
self.btnSave.Enable(False)
def JumpToLine(self, line, highlight=False):
self.editor.GotoLine(line)
self.editor.SetFocus()
if highlight:
self.editor.SelectLine(line)
def UpdateControlState(self):
active = self.demoModules.GetActiveID()
# Update the radio/restore buttons
for moduleID in self.radioButtons:
btn = self.radioButtons[moduleID]
if moduleID == active:
btn.SetValue(True)
else:
btn.SetValue(False)
if self.demoModules.Exists(moduleID):
btn.Enable(True)
if moduleID == modModified:
self.btnRestore.Enable(True)
else:
btn.Enable(False)
if moduleID == modModified:
self.btnRestore.Enable(False)
def OnRadioButton(self, event):
radioSelected = event.GetEventObject()
modSelected = radioSelected.modID
if modSelected != self.demoModules.GetActiveID():
busy = wx.BusyInfo("Reloading demo module...")
self.demoModules.SetActive(modSelected)
self.ActiveModuleChanged()
def ReloadDemo(self):
if self.demoModules.name != __name__:
self.mainFrame.RunModule()
def OnCodeModified(self, event):
self.btnSave.Enable(self.editor.IsModified())
def OnSave(self, event): # NOTE DEV Def for saving in the demo of original files.
fileWrite = open(self.editor.filePath, 'w')
try:
fileWrite.write(u'%s' % self.editor.GetTextUTF8())
except Exception as exc:
fileWrite.write(u'%s' % self.editor.GetText())
fileWrite.close()
print('self.editor.filePath = %s' % self.editor.filePath)
print('Saved')
wx.CallAfter(gMainWin.tree.OnTreeSelChanged)
# wx.CallAfter(gMainWin.LoadDemo, self.editor.filePath)
def zOnSave(self, event):
if self.demoModules.Exists(modModified):
if self.demoModules.GetActiveID() == modOriginal:
overwriteMsg = "You are about to overwrite an already existing modified copy\n" + \
"Do you want to continue?"
dlg = wx.MessageDialog(self, overwriteMsg, "wxPython Demo",
wx.YES_NO | wx.NO_DEFAULT| wx.ICON_EXCLAMATION)
result = dlg.ShowModal()
if result == wx.ID_NO:
return
dlg.Destroy()
self.demoModules.SetActive(modModified)
modifiedFilename = GetModifiedFilename(self.demoModules.name)
# Create the demo directory if one doesn't already exist
if not os.path.exists(GetModifiedDirectory()):
try:
os.makedirs(GetModifiedDirectory())
if not os.path.exists(GetModifiedDirectory()):
wx.LogMessage("BUG: Created demo directory but it still doesn't exist")
raise AssertionError
except Exception as exc:
wx.LogMessage("Error creating demo directory: %s" % GetModifiedDirectory())
return
else:
wx.LogMessage("Created directory for modified demos: %s" % GetModifiedDirectory())
# Save
f = open(modifiedFilename, "wt")
source = self.editor.GetText()
try:
f.write(source)
finally:
f.close()
busy = wx.BusyInfo("Reloading demo module...")
self.demoModules.LoadFromFile(modModified, modifiedFilename)
self.ActiveModuleChanged()
self.mainFrame.SetTreeModified(True)
def OnRestore(self, event): # Handles the "Delete Modified" button
modifiedFilename = GetModifiedFilename(self.demoModules.name)
self.demoModules.Delete(modModified)
os.unlink(modifiedFilename) # Delete the modified copy
busy = wx.BusyInfo("Reloading demo module...")
self.ActiveModuleChanged()
self.mainFrame.SetTreeModified(False)
gMainWin.OnTreeSelChanged() # this should fix deleting a modified file then resaving one right after.
#------------------------------------------------------------------------------
def opj(path):
"""Convert paths to the platform-specific separator"""
st = os.path.normpath(path.replace('/', os.sep))
# HACK: on Linux, a leading / gets lost...
if path.startswith('/'):
st = '/' + st
return st
def GetDataDir():
"""
Return the standard location on this platform for application data