-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodeeditor.py
607 lines (459 loc) · 20.3 KB
/
codeeditor.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
import os
import sys
import platform
from PyQt5.QtWidgets import QAction
from PyQt5 import Qsci
from PyQt5.Qsci import QsciScintilla, QsciLexerPython, QsciAPIs
from PyQt5.QtGui import QFont, QFontMetrics, QColor
from PyQt5.Qt import Qt
import re
from runthread import RunThread
from configuration import Configuration
import random
import time
#######################################
class PythonLexer(QsciLexerPython):
def __init__(self):
super().__init__()
def keywords(self, index):
keywords = QsciLexerPython.keywords(self, index) or ''
if index == 1:
return 'self ' + ' super ' + keywords
######################################
class CodeEditor(QsciScintilla):
def __init__(self, parent=None):
super().__init__(parent)
self.filename = None
self.fileBrowser = None
self.mainWindow = parent
self.debugging = False
c = Configuration()
self.pointSize = int(c.getFontSize())
self.tabWidth = int(c.getTab())
# Scrollbars
self.verticalScrollBar().setStyleSheet(
"""border: 20px solid blue;
background-color: darkgreen;
alternate-background-color: #063970;""")
self.horizontalScrollBar().setStyleSheet(
"""border: 20px solid blue;
background-color: darkgreen;
alternate-background-color: #063970;""")
# matched / unmatched brace color ...
self.setMatchedBraceBackgroundColor(QColor('#232323'))
self.setMatchedBraceForegroundColor(QColor('green'))
self.setUnmatchedBraceBackgroundColor(QColor('#063970'))
self.setUnmatchedBraceForegroundColor(QColor('red'))
self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
# edge mode ... line at 79 characters
self.setEdgeColumn(79)
self.setEdgeMode(1)
self.setEdgeColor(QColor('dark green'))
# Set the default font
self.font = QFont()
system = platform.system().lower()
if system == 'windows':
self.font.setFamily('Consolas')
else:
self.font.setFamily('Monospace')
self.font.setFixedPitch(True)
self.font.setPointSize(self.pointSize)
self.setFont(self.font)
self.setMarginsFont(self.font)
# Margin 0 is used for line numbers
fontmetrics = QFontMetrics(self.font)
self.setMarginsFont(self.font)
self.setMarginWidth(0, fontmetrics.width("00000") + 5)
self.setMarginLineNumbers(0, True)
self.setMarginsBackgroundColor(QColor("#063970"))
self.setMarginsForegroundColor(QColor("#063970"))
# Margin 1 for breakpoints
self.setMarginSensitivity(1, True)
self.markerDefine(QsciScintilla.RightArrow, 8)
self.setMarkerBackgroundColor(QColor('#FF0000'), 8)
# variable for breakpoint
self.breakpoint = False
self.breakpointLine = None
# FoldingBox
self.setFoldMarginColors(QColor('dark green'), QColor('dark green'))
# CallTipBox
self.setCallTipsForegroundColor(QColor('#063970'))
self.setCallTipsBackgroundColor(QColor('#282828'))
self.setCallTipsHighlightColor(QColor('#3b5784'))
self.setCallTipsStyle(QsciScintilla.CallTipsContext)
self.setCallTipsPosition(QsciScintilla.CallTipsBelowText)
self.setCallTipsVisible(-1)
# change caret's color
self.SendScintilla(QsciScintilla.SCI_SETCARETFORE, QColor('#98fb98'))
self.setCaretWidth(4)
# tab Width
self.setIndentationsUseTabs(False)
self.setTabWidth(self.tabWidth)
# use bluespaces instead tabs
self.SendScintilla(QsciScintilla.SCI_SETUSETABS, False)
self.setAutoIndent(True)
self.setTabIndents(True)
# BackTab
self.setBackspaceUnindents(True)
# Current line visible with special background color or not :)
#self.setCaretLineVisible(False)
#self.setCaretLineVisible(True)
#self.setCaretLineBackgroundColor(QColor("#020202"))
self.setMinimumSize(300, 300)
# get style
self.style = None
# Call the Color-Function: ...
self.setPythonStyle()
#self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
# Contextmenu
self.setContextMenuPolicy(Qt.ActionsContextMenu)
undoAction = QAction("Undo", self)
undoAction.triggered.connect(self.undoContext)
redoAction = QAction("Redo", self)
redoAction.triggered.connect(self.redoContext)
sepAction1 = QAction("", self)
sepAction1.setSeparator(True)
cutAction = QAction("Cut", self)
cutAction.triggered.connect(self.cutContext)
copyAction = QAction("Copy", self)
copyAction.triggered.connect(self.copyContext)
pasteAction = QAction("Paste", self)
pasteAction.triggered.connect(self.pasteContext)
sepAction2 = QAction("", self)
sepAction2.setSeparator(True)
sepAction3 = QAction("", self)
sepAction3.setSeparator(True)
selectAllAction = QAction("Select All", self)
selectAllAction.triggered.connect(self.getContext)
sepAction4 = QAction("", self)
sepAction4.setSeparator(True)
breakpointAction = QAction("Run until Breakpoint", self)
breakpointAction.triggered.connect(self.breakpointContext)
terminalAction = QAction("Open Terminal", self)
terminalAction.triggered.connect(self.termContext)
self.addAction(undoAction)
self.addAction(redoAction)
self.addAction(sepAction1)
self.addAction(cutAction)
self.addAction(copyAction)
self.addAction(pasteAction)
self.addAction(sepAction2)
self.addAction(selectAllAction)
self.addAction(sepAction3)
self.addAction(breakpointAction)
self.addAction(sepAction4)
self.addAction(terminalAction)
# signals
self.SCN_FOCUSIN.connect(self.onFocusIn)
self.textChanged.connect(self.onTextChanged)
self.marginClicked.connect(self.onMarginClicked)
def onFocusIn(self):
self.mainWindow.refresh(self)
def onTextChanged(self):
notebook = self.mainWindow.notebook
textPad = notebook.currentWidget()
index = notebook.currentIndex()
if self.debugging is True:
self.mainWindow.statusBar.showMessage('remember to update CodeView if you delete or change lines in CodeEditor !', 3000)
if textPad == None:
return
if textPad.filename:
if not '*' in notebook.tabText(index):
fname = os.path.basename(textPad.filename)
fname += '*'
notebook.setTabText(index, fname)
else:
fname = notebook.tabText(index)
fname += '*'
if not '*' in notebook.tabText(index):
notebook.setTabText(index, fname)
def onMarginClicked(self, margin, line, modifiers):
if self.markersAtLine(line) != 0:
self.markerDelete(line, 8)
self.breakpoint = False
self.breakpointLine = None
self.mainWindow.statusBar.showMessage('Breakpoint removed', 3000)
else:
if self.breakpoint == False:
self.markerAdd(line, 8)
self.breakpoint = True
self.breakpointLine = line + 1
self.mainWindow.statusBar.showMessage('Breakpoint set on line ' + \
str(self.breakpointLine), 3000)
def checkPath(self, path):
if '\\' in path:
path = path.replace('\\', '/')
return path
def undoContext(self):
self.resetBreakpoint()
self.undo()
def redoContext(self):
self.resetBreakpoint()
self.redo()
def cutContext(self):
self.resetBreakpoint()
self.cut()
def copyContext(self):
self.resetBreakpoint()
self.copy()
def pasteContext(self):
self.resetBreakpoint()
self.paste()
def getContext(self):
self.selectAll()
def breakpointContext(self):
code = ''
lines = self.lines()
c = Configuration()
system = c.getSystem()
if self.breakpointLine:
for i in range(lines):
if i < self.breakpointLine:
code += self.text(i)
randomNumber = random.SystemRandom()
number = randomNumber.randint(0, sys.maxsize)
filename = 'temp_file_' + str(number) + '.py'
try:
with open(filename, 'w') as f:
f.write(code)
command = c.getRun(system).format(filename)
thread = RunThread(command)
thread.start()
except Exception as e:
print(str(e))
finally:
time.sleep(2)
os.remove(filename)
def termContext(self):
c = Configuration()
system = c.getSystem()
command = c.getTerminal(system)
thread = RunThread(command)
thread.start()
def getLexer(self):
return self.lexer
def setPythonStyle(self):
self.style = 'Python'
# Set Python lexer
self.setAutoIndent(True)
#self.lexer = QsciLexerPython()
self.lexer = PythonLexer()
self.lexer.setFont(self.font)
self.lexer.setFoldComments(True)
# set Lexer
self.setLexer(self.lexer)
self.setCaretLineBackgroundColor(QColor("#344c4c"))
self.lexer.setDefaultPaper(QColor("black"))
self.lexer.setDefaultColor(QColor("black"))
self.lexer.setColor(QColor('black'), 0) # default
self.lexer.setPaper(QColor('black'), -1) # default -1 vor all styles
self.lexer.setColor(QColor('gray'), PythonLexer.Comment) # = 1
self.lexer.setColor(QColor('orange'), 2) # Number = 2
self.lexer.setColor(QColor('lightblue'), 3) # DoubleQuotedString
self.lexer.setColor(QColor('lightblue'), 4) # SingleQuotedString
self.lexer.setColor(QColor('#33cccc'), 5) # Keyword
self.lexer.setColor(QColor('lightblue'), 6) # TripleSingleQuotedString
self.lexer.setColor(QColor('lightblue'), 7) # TripleDoubleQuotedString
self.lexer.setColor(QColor('#ffff00'), 8) # ClassName
self.lexer.setColor(QColor('#ffff66'), 9) # FunctionMethodName
self.lexer.setColor(QColor('green'), 10) # Operator
self.lexer.setColor(QColor('#e30b86'), 11) # Identifier
self.lexer.setColor(QColor('gray'), 12) # CommentBlock
self.lexer.setColor(QColor('#ff471a'), 13) # UnclosedString
self.lexer.setColor(QColor('gray'), 14) # HighlightedIdentifier
self.lexer.setColor(QColor('#5DD3AF'), 15) # Decorator
self.setPythonAutocomplete()
self.setFold()
def setPythonAutocomplete(self):
self.autocomplete = QsciAPIs(self.lexer)
self.keywords = self.lexer.keywords(1)
self.keywords = self.keywords.split(' ')
for word in self.keywords:
self.autocomplete.add(word)
self.autocomplete.add('super')
self.autocomplete.add('self')
self.autocomplete.add('__name__')
self.autocomplete.add('__main__')
self.autocomplete.add('__init__')
self.autocomplete.add('__str__')
self.autocomplete.add('__repr__')
self.autocomplete.prepare()
## Set the length of the string before the editor tries to autocomplete
self.setAutoCompletionThreshold(3)
## Tell the editor we are using a QsciAPI for the autocompletion
self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
self.updateAutoComplete()
def setFold(self):
# setup Fold Styles for classes and functions ...
x = self.FoldStyle(self.FoldStyle(5))
#self.textPad.folding()
if not x:
self.foldAll(False)
self.setFolding(x)
#self.textPad.folding()
def unsetFold(self):
self.setFolding(0)
def keyReleaseEvent(self, e):
# feed the autocomplete with the words from editor
# simple algorithm to do this ... everytime after Enter
# refresh CodeView
text = self.text()
self.updateCodeView(text)
# if ENTER was hit ... :
if e.key() == Qt.Key_Return:
self.updateAutoComplete()
if e.key() == Qt.Key_Backspace:
self.resetBreakpoint()
def resetBreakpoint(self):
self.markerDeleteAll()
self.breakpoint = False
self.breakpointLine = None
def updateCodeView(self, text=''):
codeView = self.mainWindow.codeView
codeViewDict = codeView.makeDictForCodeView(text)
codeView.updateCodeView(codeViewDict)
def updateAutoComplete(self, text=None):
self.autocomplete = QsciAPIs(self.lexer) # clear all
self.keywords = self.lexer.keywords(1)
self.keywords = self.keywords.split(' ')
for word in self.keywords:
self.autocomplete.add(word)
self.autocomplete.add('super')
self.autocomplete.add('self')
self.autocomplete.add('__name__')
self.autocomplete.add('__main__')
self.autocomplete.add('__init__')
self.autocomplete.add('__str__')
self.autocomplete.add('__repr__')
if not text:
firstList = [] # list to edit
secondList = [] # collect all items for autocomplete
text = self.text()
# parse complete text ....
firstList = text.splitlines()
for line in firstList:
if 'def' in line:
item = line.strip()
item = item.strip('def')
item = item.replace(':', '')
if not item in secondList:
secondList.append(item)
elif 'class' in line:
item = line.strip()
item = item.strip('class')
item = item.replace(':', '')
if not item in secondList:
secondList.append(item)
text = text.replace('"', " ").replace("'", " ").replace("(", " ").replace\
(")", " ").replace("[", " ").replace("]", " ").replace\
(':', " ").replace(',', " ").replace("<", " ").replace\
(">", " ").replace("/", " ").replace("=", " ").replace\
(";", " ")
firstList = text.split('\n')
for row in firstList:
if (row.strip().startswith('#')) or (row.strip().startswith('//')):
continue
else:
wordList = row.split()
for word in wordList:
if re.match("(^[0-9])", word):
continue
elif '#' in word or '//' in word:
continue
elif word in self.keywords:
continue
elif (word == '__init__') or (word == '__main__') or \
(word == '__name__') or (word == '__str__') or \
(word == '__repr__'):
continue
elif word in secondList:
continue
elif len(word) > 15:
continue
elif not len(word) < 3:
w = re.sub("{}<>;,:]", '', word)
#print(w)
secondList.append(w)
# delete doubled entries
x = set(secondList)
secondList = list(x)
# debugging ...
#print(secondList)
for item in secondList:
self.autocomplete.add(item)
self.autocomplete.prepare()
def setPythonPrintStyle(self):
# Set None lexer
self.font = QFont()
system = platform.system().lower()
if system == 'windows':
self.font.setFamily('Consolas')
else:
self.font.setFamily('Monospace')
self.font.setFixedPitch(True)
self.font.setPointSize(10)
self.setFont(self.font)
self.lexer = PythonLexer()
self.lexer.setFont(self.font)
# set Lexer
self.setLexer(self.lexer)
self.setCaretLineBackgroundColor(QColor("#344c4c"))
self.lexer.setDefaultPaper(QColor("black"))
self.lexer.setDefaultColor(QColor("black"))
self.lexer.setColor(QColor('black'), -1) # default
self.lexer.setPaper(QColor('black'), -1) # default
self.lexer.setColor(QColor('gray'), PythonLexer.Comment) # entspricht 1
self.lexer.setColor(QColor('orange'), 2) # Number entspricht 2
self.lexer.setColor(QColor('darkgreen'), 3) # DoubleQuotedString entspricht 3
self.lexer.setColor(QColor('darkgreen'), 4) # SingleQuotedString entspricht 4
self.lexer.setColor(QColor('darkblue'), 5) # Keyword entspricht 5
self.lexer.setColor(QColor('darkgreen'), 6) # TripleSingleQuotedString entspricht 6
self.lexer.setColor(QColor('darkgreen'), 7) # TripleDoubleQuotedString entspricht 7
self.lexer.setColor(QColor('red'), 8) # ClassName entspricht 8
self.lexer.setColor(QColor('crimson'), 9) # FunctionMethodName entspricht 9
self.lexer.setColor(QColor('green'), 10) # Operator entspricht 10
self.lexer.setColor(QColor('#e30b86'), 11) # Identifier entspricht 11 ### alle Wörter
self.lexer.setColor(QColor('gray'), 12) # CommentBlock entspricht 12
self.lexer.setColor(QColor('#ff471a'), 13) # UnclosedString entspricht 13
self.lexer.setColor(QColor('gray'), 14) # HighlightedIdentifier entspricht 14
self.lexer.setColor(QColor('#5DD3AF'), 15) # Decorator entspricht 15
self.setNoneAutocomplete()
self.unsetFold()
self.font = QFont()
system = platform.system().lower()
if system == 'windows':
self.font.setFamily('Consolas')
else:
self.font.setFamily('Monospace')
self.font.setFixedPitch(True)
self.font.setPointSize(self.pointSize)
def setNoneAutocomplete(self):
#AutoCompletion
self.autocomplete = Qsci.QsciAPIs(self.lexer)
self.autocomplete.clear()
self.autocomplete.prepare()
self.setAutoCompletionThreshold(3)
self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
def resetPythonPrintStyle(self, lexer):
self.font = QFont()
system = platform.system().lower()
if system == 'windows':
self.font.setFamily('Consolas')
else:
self.font.setFamily('Monospace')
self.font.setFixedPitch(True)
self.font.setPointSize(self.pointSize)
self.setFont(self.font)
lexer.setFont(self.font)
# set Lexer
self.setLexer(lexer)
# margins reset
# Margin 0 is used for line numbers
fontmetrics = QFontMetrics(self.font)
self.setMarginsFont(self.font)
self.setMarginWidth(0, fontmetrics.width("00000") + 5)
self.setMarginLineNumbers(0, True)
self.setMarginsBackgroundColor(QColor("#063970"))
self.setMarginsForegroundColor(QColor("#063970"))
# FoldingBox
self.setFoldMarginColors(QColor('dark green'), QColor('dark green'))