-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui.py
More file actions
412 lines (343 loc) · 15.1 KB
/
ui.py
File metadata and controls
412 lines (343 loc) · 15.1 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
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
import matplotlib.pyplot as pyplot
from matplotlib.widgets import MultiCursor
import os
import sys
from highlighter import VHDLHighlighter
from line_number import QTextEditHighlighter
import error
import cli
import vcd_dump
import diagram
from typing import List, Union
class MyMultiCursor(MultiCursor):
def __init__(self, canvas, axes, useblit=True, horizOn=[], vertOn=[], xPos= None, **lineprops):
super(MyMultiCursor, self).__init__(canvas, axes, useblit=useblit, horizOn=False, vertOn=False, **lineprops)
self.horizAxes = horizOn
self.vertAxes = vertOn
if len(horizOn) > 0:
self.horizOn = True
if len(vertOn) > 0:
self.vertOn = True
xmid = xPos
if xPos == None:
xmin, xmax = axes[-1].get_xlim()
xmid = 0.5 * (xmin + xmax)
ymin, ymax = axes[-1].get_ylim()
ymid = 0.5 * (ymin + ymax)
self.vlines = [ax.axvline(xmid, visible=False, **lineprops) for ax in self.vertAxes]
self.hlines = [ax.axhline(ymid, visible=True, **lineprops) for ax in self.horizAxes]
def updatex(self,xPos, **lineprops):
for line in self.vlines:
line.x = int(xPos)
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("Editor")
self.setWindowIcon(QIcon("./res/images/vhdl.png"))
self.setGeometry(100, 100, 800, 400)
self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding))
self.config = {}
self.compiled = 0
self.buffer = ''
self.editor = QTextEditHighlighter()
self.errorbox = QListWidget()
self.errorbox.setResizeMode(QListView.ResizeMode.Adjust)
self.errorbox.setSizeAdjustPolicy(QListView.SizeAdjustPolicy.AdjustToContentsOnFirstShow)
self.errorbox.setMaximumHeight(150)
self.editor.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
self.myFont = QFont("Consolas", 10)
self.editor.setFont(self.myFont)
self.editor.setTabStopDistance(QFontMetricsF(self.editor.font()).horizontalAdvance(' ') * 4)
highlight = VHDLHighlighter(self.editor.document())
# font = QFontDatabase.systemFont()
# font.setPointSize(11)
# self.editor.setFont(font)
if (not os.path.exists('./editor.conf')):
with open('./editor.conf','w') as conf:
self.config["lastActiveFile"] = "./"
conf.write(str(self.config))
conf_file = open('./editor.conf','r+')
# configs = conf_file.read()
try:
self.config = eval(conf_file.read())
except:
self.config = {}
try:
self.config["lastActiveFile"]
except:
self.config["lastActiveFile"] = "./"
conf_file.write(str(self.config))
conf_file.close()
self.filePath = self.config["lastActiveFile"]
if self.filePath != "./":
try:
self.open_file(True)
except:
self.filePath = "./"
self.new_file()
else:
self.new_file()
self.errorbox.addItem(QListWidgetItem("No Errors"))
layout = QVBoxLayout()
layout.addWidget(self.editor)
layout.addWidget(self.errorbox)
self.container = QWidget(self)
self.container.setLayout(layout)
self.setCentralWidget(self.container)
# self.container.setMouseTracking(True)
# self.setMouseTracking(True)
self.status = QStatusBar(self)
self.setStatusBar(self.status)
file_toolbar = QToolBar("File")
file_toolbar.setIconSize(QSize(14,14))
self.addToolBar(file_toolbar)
file_menu = self.menuBar().addMenu("&File")
run_toolbar = QToolBar("Run")
run_toolbar.setIconSize(QSize(14,14))
self.addToolBar(run_toolbar)
run_menu = self.menuBar().addMenu("&Run")
self.add_action(file_toolbar, file_menu, "New File",'document-new.svg',"Ctrl+n", self.new_file)
self.add_action(file_toolbar, file_menu, "Open File",'document-open.svg',"Ctrl+o", self.open_file)
self.add_action(file_toolbar, file_menu, "Save File",'document-save.svg',"Ctrl+s", self.save_file)
self.add_action(file_toolbar, file_menu, "Save File As",'document-save-as.svg',"Ctrl+Shift+s", self.save_file_as)
self.add_action(run_toolbar, run_menu, "Compile",'builder-build-symbolic.svg',"Ctrl+Shift+b", self.compile)
self.add_simulation_time_spin_box(run_toolbar)
self.add_action(run_toolbar, run_menu, "Simulate",'builder-run-start-symbolic.svg',"f5", self.execute)
self.add_action(run_toolbar, run_menu, "Generate Circuit",'kstars-grid.svg',"f6", self.circuit)
self.update_title()
self.show()
self.arches = []
def add_simulation_time_spin_box(self, platform: QToolBar):
spinbox = QSpinBox()
spinbox.setStatusTip("Simulation End time")
spinbox.setMaximum(1000000000)
spinbox.setValue(1000)
platform.addWidget(spinbox)
self.spinbox = spinbox
def add_action(self, file_toolbar: QToolBar, file_menu: QMenu, name, iconPath, hotkey, actionHandler):
action = QAction(QIcon(os.path.join('res/images',iconPath)), name , self)
action.setStatusTip(name)
action.triggered.connect(actionHandler)
action.setShortcut(QKeySequence(QCoreApplication.translate("QKeySequence",hotkey)))
file_menu.addAction(action)
file_toolbar.addAction(action)
def new_file(self):
if self.filePath is not None and self.filePath != './':
self.file_close()
self.editor.clear()
self.buffer = ''
self.filePath = './'
self.update_title()
self.compiled = 0
def open_file(self, autoOpen: bool = False):
lastPath = self.filePath
if not autoOpen:
self.filePath, _ = QFileDialog.getOpenFileName(self, "Open File ", os.path.dirname(self.config["lastActiveFile"]), "VHDL Files (*.vhd *.vhdl);; All Files (*.*)", "VHDL Files (*.vhd *.vhdl)")
if self.filePath == '':
self.filePath = lastPath
return
if self.filePath:
with open(self.filePath, 'r') as f:
text = f.read()
self.editor.setPlainText(text)
self.buffer = text
self.update_title()
self.config["lastActiveFile"] = self.filePath
self.compiled = 0
def save_file(self):
if not self.filePath or self.filePath == './':
lastPath = self.filePath
self.filePath, _ = QFileDialog.getSaveFileName(self, "Save File ", os.path.dirname(self.config["lastActiveFile"]), "VHDL Files (*.vhd *.vhdl);; All Files (*.*)", "VHDL Files (*.vhd *.vhdl)")
if self.filePath == '':
self.filePath = lastPath
return
if self.filePath:
with open(self.filePath, 'w') as f:
text = self.editor.toPlainText()
self.buffer = text
f.write(text)
self.update_title()
self.config["lastActiveFile"] = self.filePath
def save_file_as(self):
lastPath = self.filePath
self.filePath, _ = QFileDialog.getSaveFileName(self, "Save File As", os.path.dirname(self.config["lastActiveFile"]), "VHDL Files (*.vhd *.vhdl);; All Files (*.*)", "VHDL Files (*.vhd *.vhdl)")
if self.filePath == '':
self.filePath = lastPath
return
if self.filePath:
with open(self.filePath, 'w') as f:
text = self.editor.toPlainText()
self.buffer = text
f.write(text)
self.update_title()
self.config["lastActiveFile"] = self.filePath
def update_title(self):
self.setWindowTitle("%s - VHDL Editor" %(os.path.basename(self.filePath) if self.filePath and self.filePath != './' else "Untitled - VHDL Editor"))
def closeEvent(self, event: QCloseEvent) -> None:
self.file_close()
return super().closeEvent(event)
def file_close(self):
if self.buffer != self.editor.toPlainText():
reply = QMessageBox.question(
self,
"Confirmation",
"Do you want to save the changes to this file?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No,
)
if reply == QMessageBox.Yes:
self.save_file()
def __del__(self):
with open('./editor.conf', 'w') as conf_file:
conf_file.write(str(self.config))
# def contextMenuEvent(self, e):
# context= QMenu(self)
# context.addAction(QAction("test 1", self))
# context.addAction(QAction("test 2", self))
# context.addAction(QAction("test 3", self))
# context.exec(e.globalPos())
def compile(self, suppressMessage = False):
self.errorbox.clear()
error.errno.clear()
if self.buffer != self.editor.toPlainText():
self.save_file()
print("Trying to compile", self.config["lastActiveFile"])
self.arches = cli.compile(self.config["lastActiveFile"])
self.compiled = 0
def errorbox_error_clicked(item):
index = self.errorbox.row(item)
print("Clicked", index)
# errno has the row and col get them
# here set the cursor to error place
self.editor.moveCursor(QTextCursor.MoveOperation.Start)
row, col = cli.error.errno[index].line - 1, cli.error.errno[index].col - 1
print(row, col)
for _ in range(row):
self.editor.moveCursor(QTextCursor.MoveOperation.Down, QTextCursor.MoveMode.MoveAnchor)
for _ in range(col):
self.editor.moveCursor(QTextCursor.MoveOperation.Right, QTextCursor.MoveMode.MoveAnchor)
self.editor.setFocus()
'''
Clear all errors already set
'''
cursor_current_pos = self.editor.textCursor()
self.editor.selectAll()
resetfmt = QTextCharFormat()
resetfmt.setUnderlineStyle(QTextCharFormat.UnderlineStyle.NoUnderline)
self.editor.textCursor().setCharFormat(resetfmt)
self.editor.setTextCursor(cursor_current_pos)
if len(cli.error.errno) == 0:
self.compiled = 1
if suppressMessage:
return True
self.statusBar().showMessage("Compilation Successful", 5000)
QMessageBox.information(
self,
"Result",
"Compilation Successful",
QMessageBox.StandardButton.Ok,
QMessageBox.StandardButton.Ok,
)
return True
self.errorbox.itemClicked.connect(errorbox_error_clicked)
self.errorbox.setStyleSheet("::item {border: 1px solid black} ::item:hover {background: rgba(0,0, 100, 0.3)} ::item:selected {color: black; background:rgba(0,100,0, 0.3)}")
for i in cli.error.errno:
self.errorbox.addItem(f"ERROR {i.line}:{i.col} {i.msg}")
row, col = i.line - 1, i.col - 1
self.editor.moveCursor(QTextCursor.MoveOperation.Start)
for _ in range(row):
self.editor.moveCursor(QTextCursor.MoveOperation.Down, QTextCursor.MoveMode.MoveAnchor)
for _ in range(col):
self.editor.moveCursor(QTextCursor.MoveOperation.Right, QTextCursor.MoveMode.MoveAnchor)
self.editor.moveCursor(QTextCursor.MoveOperation.EndOfWord, QTextCursor.MoveMode.KeepAnchor)
fmt = QTextCharFormat()
fmt.setUnderlineColor(QColor(255,0,0,255))
fmt.setUnderlineStyle(QTextCharFormat.UnderlineStyle.WaveUnderline)
self.editor.textCursor().setCharFormat(fmt)
self.editor.setTextCursor(cursor_current_pos)
return False
def execute(self):
def show_Legend(event):
#get mouse coordinates
mouseXdata = event.xdata
if mouseXdata is not None:
multi.updatex(mouseXdata, color='r')
def resize_plots(event):
for line in multi.vlines:
line.remove()
for line in multi.hlines:
line.remove()
multi.vlines.clear()
multi.hlines.clear()
multi.__init__(figure.canvas, tuple(axis), color='r' , lw=1, useblit=True, horizOn=[], vertOn=axis)
if self.compiled == 0:
if not self.compile(True):
return
time = self.spinbox.value()
cli.execute(self.arches, time)
times = [] # time steps 0 1 2 3 4
values: List[List[str]] = [] # [a: [], b: [], g: []]
signals = [] # a, b, g
for v in vcd_dump.variable_values.keys():
print("Keys: ", v)
values.append([])
signals.append(v)
first = True
for time in vcd_dump.values_over_time:
# print("time", time[0])
times.append(time[0])
if first:
first = False
else:
times.append(time[0])
for index, value in enumerate(time[1]):
# print("v:", value, end=" ")
values[index].append(value)
values[index].append(value)
for v in values:
v.pop()
logic_order = {
'0': 0,
'l': 1,
'w': 2,
'z': 3,
'u': 4,
'-': 5,
'x': 6,
'h': 7,
'1': 8,
}
def order(logic_value):
return logic_order[logic_value]
figure, axis = pyplot.subplots(len(signals), 1, sharex=True)
for i in range(len(signals)):
y = set(values[i])
y = sorted(y, key=order)
dummy, = axis[i].plot([0] * len(y), list(y), label = signals[i])
dummy.remove()
axis[i].plot(times, values[i], label=signals[i], color="#1f77b4")
axis[i].legend(loc='upper right')
multi = MyMultiCursor(figure.canvas, tuple(axis), color='r' , lw=1, useblit=True, horizOn=[], vertOn=axis)
figure.canvas.mpl_connect('motion_notify_event', show_Legend)
figure.canvas.mpl_connect('resize_event', resize_plots)
pyplot.show()
# vcd_dump.output.close()
vcd_dump.VcdWriter = None
vcd_dump.current_time = 0
# vcd_dump.variables = {}
vcd_dump.variable_values = {}
vcd_dump.values_over_time = []
def circuit(self):
n = len(self.arches)
if n == 0:
return
self.scene = QGraphicsScene(0, 0, 600, 500*n)
self.scene.setBackgroundBrush(Qt.white)
for i, arch in enumerate(self.arches):
diagram.draw(arch, self.scene, center = (300, 250 + 500*i))
self.view = QGraphicsView(self.scene)
self.view.setRenderHint(QPainter.Antialiasing)
self.view.show()