forked from capocchi/DEVSimPy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditor.py
More file actions
2859 lines (2349 loc) · 96.9 KB
/
Editor.py
File metadata and controls
2859 lines (2349 loc) · 96.9 KB
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
# -*- coding: utf-8 -*-
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
# Editor.py ---
# --------------------------------
# Copyright (c) 2020
# L. CAPOCCHI (capocchi@univ-corse.fr) & T. Ville
# SPE Lab - SISU Group - University of Corsica
# --------------------------------
# Version 1.0 last modified: 03/15/2020
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#
# GENERAL NOTES AND REMARKS:
#
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#
# GLOBAL VARIABLES AND FUNCTIONS
#
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
import wx
import os
import sys
import keyword
import inspect
import zipfile
import threading
import re
import codecs
import tabnanny
import builtins
import types
import traceback
import collections
from tempfile import gettempdir
from wx import stc
from Decorators import redirectStdout
from Utilities import path_to_module, printOnStatusBar
import ReloadModule
import ZipManager
import gettext
_ = gettext.gettext
# Turn on verbose mode
tabnanny.verbose = 1
if wx.Platform == '__WXMSW__':
faces = dict(times='Times New Roman', mono='Courier New', helv='Arial', other='Comic Sans MS', size=10, size2=8)
elif wx.Platform == '__WXMAC__':
faces = dict(times='Times New Roman', mono='Monaco', helv='Arial', other='Comic Sans MS', size=12, size2=10)
else:
faces = dict(times='Times', mono='Courier', helv='Helvetica', other='new century schoolbook', size=12, size2=10)
wx.SystemSettings_GetColour = wx.SystemSettings.GetColour if wx.VERSION_STRING >= '4.0' else wx.SystemSettings_GetColour
#################################################################
###
### GENERAL FUNCTIONS
###
#################################################################
### NOTE: Editor.py :: isError => check if file is well-formed and if requirements are corrects
def isError(scriptlet):
"""
"""
try:
code = compile(scriptlet, '<string>', 'exec')
exec(code)
except Exception as info:
return info
else:
return False
### NOTE: Editor.py :: getObjectFromString => todo
def getObjectFromString(scriptlet):
"""
"""
assert scriptlet != ''
# Compile the scriptlet.
try:
code = compile(scriptlet, '<string>', 'exec')
except Exception as info:
### Add line number to the error trace
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname,lineno,fn,text = frame
L = list(info.args)
L.append("line %i"%lineno)
info.args = tuple(L)
return info
else:
# Create the new 'temp' module.
temp = types.ModuleType('temp')
sys.modules["temp"] = temp
### there is syntaxe error ?
try:
exec(code, temp.__dict__)
except Exception as info:
### Add line number to the error trace
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname,lineno,fn,text = frame
L = list(info.args)
L.append("line %i"%lineno)
info.args = tuple(L)
return info
else:
classes = inspect.getmembers(temp, callable)
for name, value in classes:
if value.__module__ == "temp":
# Create the instance.
try:
return eval("temp.%s" % name)()
except Exception as info:
### Add line number to the error trace
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname,lineno,fn,text = frame
L = list(info.args)
L.append("line %i"%lineno)
info.args = tuple(L)
return info
### NOTE: Editor.py :: GetEditor => Return the appropriate Editor
def GetEditor(parent, id, title="", obj=None, **kwargs):
""" Factory Editor
@param: parent
@param: id
@param: title
@param: obj
@param: file_type
"""
if "file_type" in list(kwargs.keys()):
file_type = kwargs["file_type"]
if file_type == "test":
editor = TestEditor(parent, id, title)
elif file_type == "block":
editor = BlockEditor(parent, id, title, obj)
else:
editor = GeneralEditor(parent, id, title)
else:
editor = GeneralEditor(parent, id, title)
return editor
#################################################################
###
### GENERAL CLASSES
###
#################################################################
class TestSearchCtrl(wx.SearchCtrl):
maxSearches = 5
def __init__(self, parent, id=-1, value="",
pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
doSearch=None):
style |= wx.TE_PROCESS_ENTER
wx.SearchCtrl.__init__(self, parent, id, value, pos, size, style)
self.Bind(wx.EVT_TEXT_ENTER, self.OnTextEntered)
self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.OnTextEntered)
self.Bind(wx.EVT_MENU_RANGE, self.OnMenuItem, id=1, id2=self.maxSearches)
self.doSearch = doSearch
self.searches = []
def OnTextEntered(self, evt):
text = self.GetValue()
if self.doSearch(text):
self.searches.append(text)
if len(self.searches) > self.maxSearches:
del self.searches[0]
self.SetMenu(self.MakeMenu())
self.SetValue("")
def OnMenuItem(self, evt):
text = self.searches[evt.GetId()-1]
self.doSearch(text)
def MakeMenu(self):
menu = wx.Menu()
item = menu.Append(-1, "Recent Searches")
item.Enable(False)
for idx, txt in enumerate(self.searches):
if txt != "":
menu.Append(1+idx, txt)
return menu
### NOTE: PythonSTC << stc.StyledTextCtrl :: todo
class PythonSTC(stc.StyledTextCtrl):
"""
"""
fold_symbols = 2
### NOTE: PythonSTC:: constructor => __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0)
def __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
"""
"""
stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style)
# Do we want to automatically pop up command completion options?
self.autoComplete = True
self.autoCompleteIncludeMagic = True
self.autoCompleteIncludeSingle = True
self.autoCompleteIncludeDouble = True
self.autoCompleteCaseInsensitive = True
self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive)
self.autoCompleteAutoHide = False
self.AutoCompSetAutoHide(self.autoCompleteAutoHide)
self.AutoCompStops(' .,;:([)]}\'"\\<>%^&+-=*/|`')
self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
self.SetLexer(stc.STC_LEX_PYTHON)
self.SetKeyWords(0, " ".join(keyword.kwlist))
self.SetProperty("fold", "1")
self.SetProperty("tab.timmy.whinge.level", "1")
self.SetMargins(0, 0)
self.SetViewWhiteSpace(False)
self.SetBufferedDraw(False)
self.SetViewEOL(True)
self.SetEOLMode(stc.STC_EOL_CRLF)
if wx.VERSION_STRING < '4.0': self.SetUseAntiAliasing(True)
self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
self.SetEdgeColumn(78)
# 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)
if self.fold_symbols == 0:
# Arrow pointing right for contracted folders, arrow pointing down for expanded
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_ARROWDOWN, "black", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_ARROW, "black", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "black", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "black", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black")
elif self.fold_symbols == 1:
# Plus for contracted folders, minus for expanded
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_MINUS, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_PLUS, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black")
elif self.fold_symbols == 2:
# Like a flattened tree control using circular headers and curved joins
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_CIRCLEMINUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_CIRCLEPLUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNERCURVE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_CIRCLEMINUSCONNECTED, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNERCURVE, "white", "#404040")
elif self.fold_symbols == 3:
# Like a flattened tree control using square headers
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080")
self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
# Make some styles, The lexer defines what each style is used for, we
# just have to define what each style looks like. This set is adapted from
# Scintilla sample property files.
# Global default styles for all languages
self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces)
#self.StyleSetSpec(STC_CODE_ERROR, 'fore:#FF0000,back:#FFFF00,size:%(size)d' % faces)
#self.StyleSetSpec(STC_CODE_SEARCH_RESULT, 'fore:#FFFFFF,back:#FFA500,size:%(size)d' % faces)
self.StyleClearAll() # Reset all to be like the default
# Global default styles for all languages
self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % faces)
self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % faces)
self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % faces)
self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold")
self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
# Python styles
# Default
self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % faces)
# Comments
self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % faces)
# Number
self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % faces)
# String
self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces)
# Single quoted string
self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces)
# Keyword
self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % faces)
# Triple quotes
self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % faces)
# Triple double quotes
self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % faces)
# Class name definition
self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % faces)
# Function or method name definition
self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % faces)
# Operators
self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % faces)
# Identifiers
self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % faces)
# Comment-blocks
self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % faces)
# End of line where string is not closed
self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % faces)
self.SetCaretForeground("BLUE")
# NOTE: PythonSTC :: __str__ => String representation of the class
@classmethod
def __str__(cls):
attrs = [('fold_symbols', 'integer')]
class_name = "PythonSTC"
parent = "stc.StyledTextCtrl"
methods = [
('__init__', 'self, parent, ID, pos, size, style'),
('FoldAll', 'self'),
('Expand', 'self, line, doExpand, force, visLevels, level'),
('OnUpdateUI', 'self, event'),
('OnMarginClick', 'self, event')
]
return "\n--------------------------------------------------\
\n\tClass :\t\t%s\n\n\tInherit from :\t%s\n\n\tAttributes :\t%s\n\n\tMethods :\t%s\n" % (
class_name, parent, '\n\t\t\t'.join([attr + "\t:: " + typ for attr, typ in attrs]),
"\n\t\t\t".join([method + "\tparams :: " + params for method, params in methods])
)
### NOTE: PythonSTC :: OnUpdateUI => Event for update user interface
def OnUpdateUI(self, evt):
# If the auto-complete window is up let it do its thing.
if self.AutoCompActive() or self.CallTipActive():
return
# check for matching braces
braceAtCaret = -1
braceOpposite = -1
charBefore = None
caretPos = self.GetCurrentPos()
if caretPos > 0:
charBefore = self.GetCharAt(caretPos - 1)
styleBefore = self.GetStyleAt(caretPos - 1)
# check before
if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
braceAtCaret = caretPos - 1
# check after
if braceAtCaret < 0:
charAfter = self.GetCharAt(caretPos)
styleAfter = self.GetStyleAt(caretPos)
if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
braceAtCaret = caretPos
if braceAtCaret >= 0:
braceOpposite = self.BraceMatch(braceAtCaret)
if braceAtCaret != -1 and braceOpposite == -1:
self.BraceBadLight(braceAtCaret)
else:
self.BraceHighlight(braceAtCaret, braceOpposite)
### NOTE: PythonSTC :: OnMarginClick => Event for click on margin
def OnMarginClick(self, evt):
# fold and unfold as needed
if evt.GetMargin() == 2:
if evt.GetShift() and evt.GetControl():
self.FoldAll()
else:
lineClicked = self.LineFromPosition(evt.GetPosition())
if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
if evt.GetShift():
self.SetFoldExpanded(lineClicked, True)
self.Expand(lineClicked, True, True, 1)
elif evt.GetControl():
if self.GetFoldExpanded(lineClicked):
self.SetFoldExpanded(lineClicked, False)
self.Expand(lineClicked, False, True, 0)
else:
self.SetFoldExpanded(lineClicked, True)
self.Expand(lineClicked, True, True, 100)
else:
self.ToggleFold(lineClicked)
### NOTE: PythonSTC :: FoldAll => Fold entire code
def FoldAll(self):
lineCount = self.GetLineCount()
expanding = True
# find out if we are folding or unfolding
for lineNum in range(lineCount):
if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
expanding = not self.GetFoldExpanded(lineNum)
break
lineNum = 0
while lineNum < lineCount:
level = self.GetFoldLevel(lineNum)
if level & stc.STC_FOLDLEVELHEADERFLAG and (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
if expanding:
self.SetFoldExpanded(lineNum, True)
lineNum = self.Expand(lineNum, True)
lineNum -= 1
else:
lastChild = self.GetLastChild(lineNum, -1)
self.SetFoldExpanded(lineNum, False)
if lastChild > lineNum:
self.HideLines(lineNum + 1, lastChild)
lineNum += 1
def Paste(self):
# success = False
#do = wx.TextDataObject()
# if wx.TheClipboard.Open():
# success = wx.TheClipboard.GetData(do)
# wx.TheClipboard.Close()
# if success:
# if not self.execplugin('on_paste', self, do.GetText()):
# wx.stc.StyledTextCtrl.Paste(self)
wx.stc.StyledTextCtrl.Paste(self)
def Copy(self):
wx.stc.StyledTextCtrl.Copy(self)
### NOTE: PythonSTC :: Expand => Expand selected line
def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
lastChild = self.GetLastChild(line, level)
line += 1
while line <= lastChild:
if force:
if visLevels > 0:
self.ShowLines(line, line)
else:
self.HideLines(line, line)
else:
if doExpand:
self.ShowLines(line, line)
if level == -1:
level = self.GetFoldLevel(line)
if level & stc.STC_FOLDLEVELHEADERFLAG:
if force:
if visLevels > 1:
self.SetFoldExpanded(line, True)
else:
self.SetFoldExpanded(line, False)
line = self.Expand(line, doExpand, force, visLevels - 1)
else:
if doExpand and self.GetFoldExpanded(line):
line = self.Expand(line, True, force, visLevels - 1)
else:
line = self.Expand(line, False, force, visLevels - 1)
else:
line += 1
return line
###-----------------------------------------------------------------------------
### NOTE: CodeEditor << PythonSTC :: todo
class CodeEditor(PythonSTC):
#### NOTE: CodeEditor :: constructor => __init__(self, parent)
def __init__(self, parent):
""" Constructor
"""
PythonSTC.__init__(self, parent, wx.NewIdRef(), style=wx.BORDER_NONE)
self.SetUpEditor()
self.last_name_saved = ""
# NOTE: CodeEditor :: __str__ => String representation of the class
@classmethod
def __str__(cls):
attrs = [('last_name_saved', 'str')]
class_name = "CodeEditor"
parent = "PythonSTC"
methods = [
('__init__', 'self, parent'),
('GetFilename', 'self'),
('SetFilename', 'self, filename'),
('GetValue', 'self'),
('SetValue', 'self, value'),
('IsModified', 'self'),
('Clear', 'self'),
('SetInsertionPoint', 'self, pos'),
('ShowPosition', 'self, pos'),
('GetLastPosition', 'self'),
('GetPositionFromLine', 'self, line'),
('GetRange', 'self, start, end'),
('GetSelection', 'self'),
('SetSelection', 'self, start, end'),
('SelectLine', 'self, line'),
('SetUpEditor', 'self'),
('RegisterModifiedEvent', 'self, eventHandler')
]
return "\n--------------------------------------------------\
\n\tClass :\t\t%s\n\n\tInherit from :\t%s\n\n\tAttributes :\t%s\n\n\tMethods :\t%s\n" % (
class_name, parent, '\n\t\t\t'.join([attr + "\t:: " + typ for attr, typ in attrs]),
"\n\t\t\t".join([method + "\tparams :: " + params for method, params in methods])
)
### NOTE: CodeEditor :: GetFilename => Get the last name saved
def GetFilename(self):
return self.last_name_saved
### NOTE: CodeEditor :: SetFilename => Set the last name saved
def SetFilename(self, filename):
self.last_name_saved = filename
### NOTE: CodeEditor :: SetValue => Set the text to print in the editor
### Some methods to make it compatible with how the wxTextCtrl is used
def SetValue(self, value):
self.SetText(value)
self.EmptyUndoBuffer()
self.SetSavePoint()
### NOTE: CodeEditor :: GetValue => Get the text printed in the editor
def GetValue(self):
return self.GetText()
### NOTE: CodeEditor :: IsModified => Flag to determine if the text is modified or not
def IsModified(self):
return self.GetModify()
### NOTE: CodeEditor :: Clear => Clear the text
def Clear(self):
self.ClearAll()
### NOTE: CodeEditor :: SetInsertionPoint => Set an anchor for insertion
def SetInsertionPoint(self, pos):
self.SetCurrentPos(pos)
self.SetAnchor(pos)
### NOTE: CodeEditor :: ShowPosition => Go to the line of selected position
def ShowPosition(self, pos):
line = self.LineFromPosition(pos)
# self.EnsureVisible(line)
self.GotoLine(line)
### NOTE: CodeEditor :: GetLastPosition => todo
def GetLastPosition(self):
return self.GetLength()
### NOTE: CodeEditor :: GetPositionFromLine => todo
def GetPositionFromLine(self, line):
return self.PositionFromLine(line)
### NOTE: CodeEditor :: GetRange => Get the text range
def GetRange(self, start, end):
return self.GetTextRange(start, end)
### NOTE: CodeEditor :: GetSelection => Get the selected text
def GetSelection(self):
return self.GetAnchor(), self.GetCurrentPos()
### NOTE: CodeEditor :: SetSelection => Set the selected text
def SetSelection(self, start, end):
self.SetSelectionStart(start)
self.SetSelectionEnd(end)
### NOTE: CodeEditor :: SelectLine => Select the line
def SelectLine(self, line):
start = self.PositionFromLine(line)
end = self.GetLineEndPosition(line)
self.SetSelection(start, end)
### NOTE: CodeEditor :: SetUpEditor => Configure lexer and color
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(True) # 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,size:9')
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:
self.StyleSetSpec(stc.STC_STYLE_DEFAULT, 'fore:#000000,back:#FFFFFF,face:Courier,size:9')
# 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 criterae
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))
### NOTE: CodeEditor :: RegisterModifiedEvent => todo
def RegisterModifiedEvent(self, eventHandler):
"""
"""
self.Bind(wx.stc.EVT_STC_CHANGE, eventHandler)
### EditionFile-----------------------------------------------------
### NOTE: EditionFile << CodeEditor :: Expect EditionFile objects to clearly separate file and notebook attributes
class EditionFile(CodeEditor):
"""
"""
#
def __init__(self, parent, path, code):
""" Constructor
"""
CodeEditor.__init__(self, parent)
# variables
self.modify = False
self.error_flag = False
self.SetFilename(path)
self.SetValue(code)
# NOTE: EditionFile :: __str__ => String representation of the class
@classmethod
def __str__(cls):
attrs = [('modify', 'boolean'), ('error_flag', 'boolean')]
class_name = "EditionFile"
parent = "CodeEditor"
methods = [
('__init__', 'self, parent'),
('ContainError', 'self')
]
return "\n--------------------------------------------------\
\n\tClass :\t\t%s\n\n\tInherit from :\t%s\n\n\tAttributes :\t%s\n\n\tMethods :\t%s\n" % (
class_name, parent, '\n\t\t\t'.join([attr + "\t:: " + typ for attr, typ in attrs]),
"\n\t\t\t".join([method + "\tparams :: " + params for method, params in methods])
)
# NOTE: EditionFile :: ContainError => Getter of the error flag
def ContainError(self):
"""
"""
return self.error_flag
### ----------------------------------------------------------------
### EditionNotebook-------------------------------------------------
### NOTE: EditionNotebook << wx.Notebook :: Notebook for multiple file edition
class EditionNotebook(wx.Notebook):
"""
"""
### NOTE: EditionNotebook :: constructor => __init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
"""
Notebook class that allows overriding and adding methods.
@param parent: parent windows
@param id: id
@param pos: windows position
@param size: windows size
@param style: windows style
@param name: windows name
"""
wx.Notebook.__init__(self, *args, **kwargs)
# local copy
self.parent = args[0]
self.pages = [] # keeps track of pages
# variables
self.force_saving = False
#icon under tab
imgList = wx.ImageList(16, 16)
for img in [os.path.join(ICON_PATH_16_16, 'featureFile.png')]:
imgList.Add(wx.Bitmap(img))
self.AssignImageList(imgList)
### binding
self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.__PageChanged)
self.Show()
# NOTE: EditionNotebook :: __str__ => String representation of the class
@classmethod
def __str__(cls):
attrs = [('parent', 'UNDEFINED'), ('pages', 'list<EditionFile>'), ('force_saving', 'boolean')]
class_name = "EditionNotebook"
parent = "wx.Notebook"
methods = [
('__init__', 'self, parent, ID, pos, size, style'),
('GetPages', 'self'),
('AddEditPage', 'self, title, path'),
('GetPageByName', 'self, name'),
('DoOpenFile', 'self'),
('DoSaveFile', 'self, base_name, code'),
('__PageChanged', 'self, event'),
('OnClosePage', 'self, event'),
('OnKeyDown', 'self, event'),
('OnCut', 'self, event'),
('OnCopy', 'self, event'),
('OnPaste', 'self, event'),
('OnReIndent', 'self, event'),
('OnDelete', 'self, event'),
('OnSelectAll', 'self, event'),
('<static> WriteFile', 'fileName, code, encode'),
('<static> CheckIndent', 'filename')
]
return "\n--------------------------------------------------\
\n\tClass :\t\t%s\n\n\tInherit from :\t%s\n\n\tAttributes :\t%s\n\n\tMethods :\t%s\n" % (
class_name, parent, '\n\t\t\t'.join([attr + "\t:: " + typ for attr, typ in attrs]),
"\n\t\t\t".join([method + "\tparams :: " + params for method, params in methods])
)
### NOTE: EditionNotebook :: GetPages => Get the list of created pages
def GetPages(self):
"""
"""
return self.pages
### NOTE: EditionNotebook :: AddEditPage => Create a new page
def AddEditPage(self, title="", path=""):
"""
Adds a new page for editing to the notebook and keeps track of it.
@type title: string
@param title: Title for a new page
"""
fileCode = ""
### FIXME: try to consider zipfile in zipfile
L = re.findall("(.*\.(amd|cmd))\%s(.*)" % os.sep, path)
if L:
model_path, ext, name = L.pop(0)
if zipfile.is_zipfile(model_path):
importer = zipfile.ZipFile(model_path, "r")
fileInfo = importer.getinfo(name)
fileCode = importer.read(fileInfo)
importer.close()
else:
if os.path.exists(path):
with open(path, 'r') as f:
fileCode = f.read()
else:
### fileCode is path (user work with IOString code, not file object)
fileCode = path
### new page
newPage = EditionFile(self, path, fileCode)
newPage.SetFocus()
### bind the page
newPage.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
newPage.Bind(wx.EVT_CHAR, self.parent.OnChar)
### add page
self.pages.append(newPage)
self.AddPage(newPage, title, imageId=0)
### NOTE: EditionNotebook :: GetPageByName => Return the page with the required name
def GetPageByName(self, name=''):
"""
"""
for i in range(len(self.pages)):
if name == self.GetPageText(i):
return self.GetPage(i)
return None
### NOTE: EditionNotebook :: __PageChanged => Event when page changed
def __PageChanged(self, evt):
"""
"""
try:
canvas = self.GetPage(self.GetSelection())
### allows to activate redo and undo for each page
self.parent.tb.EnableTool(wx.ID_UNDO, len(canvas.stockUndo) != 0)
self.parent.tb.EnableTool(wx.ID_REDO, len(canvas.stockRedo) != 0)
canvas.deselect()
canvas.Refresh()
except Exception:
pass
evt.Skip()
### NOTE: EditionNotebook :: OnClosePage => Event when the close button is clicked
def OnClosePage(self, evt, id):
""" Close current page.
@type evt: event
@param evt: Event Object, None by default
"""
if self.GetPageCount() > 0:
self.pages.remove(self.GetPage(id))
return self.DeletePage(id)
return True
### NOTE: EditionNotebook :: OnKeyDown => Event when key is pressed
def OnKeyDown(self, event):
"""
"""
keycode = event.GetKeyCode()
controlDown = event.CmdDown()
currentPage = self.GetCurrentPage()
if keycode == wx.WXK_UP or keycode == wx.WXK_DOWN:
event.Skip()
elif keycode == 68 and controlDown:
cur_line = currentPage.GetCurrentLine()
shiftDown = event.ShiftDown()
if shiftDown:
indent = currentPage.GetLineIndentPosition(cur_line)
currentPage.Home()
currentPage.DelWordRight()
currentPage.SetCurrentPos(indent)
else:
currentPage.InsertText(currentPage.PositionFromLine(cur_line), "#")
else:
event.Skip()
### NOTE: EditionNotebook :: DoOpenFile => Opening file method
def DoOpenFile(self):
"""
"""
currentPage = self.GetCurrentPage()
wcd = 'All files (*)|*|Editor files (*.py)|*.py'
dir = HOME_PATH
open_dlg = wx.FileDialog(self, message=_('Choose a file'), defaultDir=dir, defaultFile='', wildcard=wcd,
style=wx.OPEN | wx.CHANGE_DIR)
if open_dlg.ShowModal() == wx.ID_OK:
path = open_dlg.GetPath()
try:
with codecs.open(path, 'r', 'utf-8') as f:
text = f.read()
if currentPage.GetLastPosition():
currentPage().Clear()
currentPage().WriteText(text)
currentPage().SetFilename(path)
currentPage.modify = False
except Exception as info:
wx.MessageBox(_('Error opening file:\n%s\n')%str(info),\
"Open file function",\
wx.OK | wx.ICON_ERROR)
open_dlg.Destroy()
### NOTE: EditionNotebook :: DoSaveFile => Saving file method
def DoSaveFile(self, code):
"""
"""