-
Notifications
You must be signed in to change notification settings - Fork 21
/
gui_qt.py
1666 lines (1474 loc) · 61.8 KB
/
gui_qt.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
"""PyQT5 version of a treeview-based XML-editor
"""
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout, QApplication)
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
import os
import sys
## import functools
import PyQt5.QtWidgets as qtw
import PyQt5.QtGui as gui
import PyQt5.QtCore as core
from shared import ELSTART, iconame, log
from PyQt5 import uic
# This Python file uses the following encoding: utf-8
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog, QMessageBox
from PyQt5.QtGui import QIcon
from pyesmini.pyesmini.pyesmini import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# TODO : Only show path selection when the system cannot find the
# openDrive or OSG files
import threading
simulatorRunning = False
if os.name == "nt":
HMASK = "OpenScenario files (*.xml *.xosc);;All files (*.*)"
elif os.name == "posix":
HMASK = "OpenScenario files (*.xml *.XML *.xosc *.XOSC);;All files (*.*)"
IMASK = "All files (*.*)"
def calculate_location(win, node):
"""attempt to calculate some kind of identification for a tree node
this function returns a tuple of subsequent indices of a child under its
parent.
possibly this can be used in the replacements dictionary
"""
id_ = []
while node != win.top:
idx = node.parent().indexOfChild(node)
id_.insert(0, idx)
node = node.parent()
return tuple(id_)
# Dialog windows
class ElementDialog(qtw.QDialog):
"""Dialog for editing an element
"""
def __init__(self, parent, title="", item=None):
super().__init__(parent)
self.setWindowTitle(title)
self.setWindowIcon(parent._icon)
self._parent = parent
lbl_name = qtw.QLabel("element name: ", self)
self.txt_tag = qtw.QLineEdit(self)
self.cb_ns = qtw.QCheckBox('Namespace:', self)
self.cmb_ns = qtw.QComboBox(self)
self.cmb_ns.setEditable(False)
self.cmb_ns.addItem('-- none --')
self.cmb_ns.addItems(self._parent.editor.ns_uris)
self.cb = qtw.QCheckBox('Contains data: ', self)
self.cb.setCheckable(False)
self.txt_data = qtw.QTextEdit(self)
self.txt_data.setTabChangesFocus(True)
self.btn_ok = qtw.QPushButton('&Save', self)
self.btn_ok.clicked.connect(self.accept)
self.btn_ok.setDefault(True)
self.btn_cancel = qtw.QPushButton('&Cancel', self)
self.btn_cancel.clicked.connect(self.reject)
ns_tag = tag = ns_uri = txt = ''
if item:
ns_tag = item["tag"]
if ns_tag.startswith('{'):
ns_uri, tag = ns_tag[1:].split('}')
else:
tag = ns_tag
if "text" in item:
self.cb.toggle()
txt = item["text"]
if ns_uri:
self.cb_ns.toggle()
for ix, uri in enumerate(self._parent.ns_uris):
if uri == ns_uri:
self.cmb_ns.setCurrentIndex(ix + 1)
self.txt_tag.setText(tag)
self.txt_data.setText(txt)
sizer = qtw.QVBoxLayout()
hsizer = qtw.QHBoxLayout()
gsizer = qtw.QGridLayout()
gsizer.addWidget(lbl_name, 0, 0)
hsizer2 = qtw.QHBoxLayout()
hsizer2.addWidget(self.txt_tag)
hsizer2.addStretch()
gsizer.addLayout(hsizer2, 0, 1)
gsizer.addWidget(self.cb_ns)
gsizer.addWidget(self.cmb_ns)
hsizer.addLayout(gsizer)
hsizer.addStretch()
sizer.addLayout(hsizer)
hsizer = qtw.QHBoxLayout()
vsizer = qtw.QVBoxLayout()
vsizer.addWidget(self.cb)
vsizer.addWidget(self.txt_data)
hsizer.addLayout(vsizer)
sizer.addLayout(hsizer)
hsizer = qtw.QHBoxLayout()
hsizer.addStretch()
hsizer.addWidget(self.btn_ok)
hsizer.addWidget(self.btn_cancel)
hsizer.addStretch()
sizer.addLayout(hsizer)
self.setLayout(sizer)
# def on_cancel(self):
# super().done(qtw.QDialog.Rejected)
def accept(self):
"""final checks, send changed data to parent"""
self._parent.data = {}
tag = str(self.txt_tag.text())
fout = ''
if tag == '':
fout = 'Element name must not be empty'
elif len(tag.split()) > 1:
fout = 'Element name must not contain spaces'
elif tag[0].isdigit():
fout = 'Element name must not start with a digit'
if fout:
self._parent.meldfout(fout)
self.txt_tag.setFocus()
return
if self.cb_ns.isChecked():
seq = self.cmb_ns.currentIndex()
if seq == 0:
self._parent.meldfout('Namespace must be selected if checked')
self.cb_ns.setFocus()
return
tag = '{{{}}}{}'.format(self.cmb_ns.itemText(seq), tag)
self._parent.data["tag"] = tag
self._parent.data["data"] = self.cb.isChecked()
self._parent.data["text"] = self.txt_data.toPlainText()
super().accept()
def keyPressEvent(self, event):
"""reimplemented event handler for keystrokes """
if event.key() == core.Qt.Key_Escape:
super().done(qtw.QDialog.Rejected)
class AttributeDialog(qtw.QDialog):
"""Dialog for editing an attribute"""
def __init__(self, parent, title='', item=None):
super().__init__(parent)
self.setWindowTitle(title)
self.setWindowIcon(parent._icon)
self._parent = parent
lbl_name = qtw.QLabel("Attribute name:", self)
self.txt_name = qtw.QLineEdit(self)
self.cb_ns = qtw.QCheckBox('Namespace:', self)
self.cmb_ns = qtw.QComboBox(self)
self.cmb_ns.setEditable(False)
self.cmb_ns.addItem('-- none --')
self.cmb_ns.addItems(self._parent.editor.ns_uris)
lbl_value = qtw.QLabel("Attribute value:", self)
self.txt_value = qtw.QLineEdit(self)
self.btn_ok = qtw.QPushButton('&Save', self)
self.btn_ok.setDefault(True)
self.btn_ok.clicked.connect(self.accept)
self.btn_cancel = qtw.QPushButton('&Cancel', self)
self.btn_cancel.clicked.connect(self.reject)
ns_nam = nam = ns_uri = val = ''
if item:
ns_nam = item["name"]
if ns_nam.startswith('{'):
ns_uri, nam = ns_nam[1:].split('}')
else:
nam = ns_nam
if ns_uri:
self.cb_ns.toggle()
for ix, uri in enumerate(self._parent.ns_uris):
if uri == ns_uri:
self.cmb_ns.setCurrentIndex(ix + 1)
val = item["value"]
self.txt_name.setText(nam)
self.txt_value.setText(val)
sizer = qtw.QVBoxLayout()
hsizer = qtw.QHBoxLayout()
gsizer = qtw.QGridLayout()
gsizer.addWidget(lbl_name, 0, 0)
hsizer2 = qtw.QHBoxLayout()
hsizer2.addWidget(self.txt_name)
hsizer2.addStretch()
gsizer.addLayout(hsizer2, 0, 1)
gsizer.addWidget(self.cb_ns, 1, 0)
gsizer.addWidget(self.cmb_ns, 1, 1)
gsizer.addWidget(lbl_value, 2, 0)
hsizer2 = qtw.QHBoxLayout()
hsizer2.addWidget(self.txt_value)
hsizer2.addStretch()
gsizer.addLayout(hsizer2, 2, 1)
hsizer.addLayout(gsizer)
hsizer.addStretch()
sizer.addLayout(hsizer)
hsizer = qtw.QHBoxLayout()
hsizer.addStretch()
hsizer.addWidget(self.btn_ok)
hsizer.addWidget(self.btn_cancel)
hsizer.addStretch()
sizer.addLayout(hsizer)
self.setLayout(sizer)
# self.resize(320,125)
def accept(self):
"""final checks, transmit changes to parent"""
self._parent.data = {}
nam = self.txt_name.text()
fout = ''
if nam == '':
fout = 'Attribute name must not be empty'
elif len(nam.split()) > 1:
fout = 'Attribute name must not contain spaces'
elif nam[0].isdigit():
fout = 'Attribute name must not start with a digit'
if fout:
self._parent.meldfout(fout)
self.txt_name.setFocus()
return
if self.cb_ns.isChecked():
seq = self.cmb_ns.currentIndex()
if seq == 0:
self._parent.meldfout('Namespace must be selected if checked')
self.cb_ns.setFocus()
return
nam = '{{{}}}{}'.format(self.cmb_ns.itemText(seq), nam)
self._parent.data["name"] = nam
self._parent.data["value"] = self.txt_value.text()
super().accept()
# def on_cancel(self):
# super().done(qtw.QDialog.Rejected)
def keyPressEvent(self, event):
"""event handler for keystrokes """
if event.key() == core.Qt.Key_Escape:
super().done(qtw.QDialog.Rejected)
class SearchDialog(qtw.QDialog):
"""Dialog to get search arguments
"""
def __init__(self, parent, title=""):
super().__init__(parent)
self.setWindowTitle(title)
self._parent = parent
if self._parent.editor.search_args:
ele_name, attr_name, attr_val, text_val = self._parent.editor.search_args
else:
ele_name = attr_name = attr_val = text_val = ''
sizer = qtw.QVBoxLayout()
gsizer = qtw.QGridLayout()
self.cb_element = qtw.QLabel('Element', self)
gsizer.addWidget(self.cb_element, 0, 0)
vsizer = qtw.QVBoxLayout()
hsizer = qtw.QHBoxLayout()
lbl_element = qtw.QLabel("name:", self)
hsizer.addWidget(lbl_element)
self.txt_element = qtw.QLineEdit(self)
hsizer.addWidget(self.txt_element)
vsizer.addLayout(hsizer)
gsizer.addLayout(vsizer, 0, 1)
vsizer = qtw.QVBoxLayout()
self.cb_attr = qtw.QLabel('Attribute', self)
vsizer.addWidget(self.cb_attr)
gsizer.addLayout(vsizer, 1, 0)
vsizer = qtw.QVBoxLayout()
hsizer = qtw.QHBoxLayout()
lbl_attr_name = qtw.QLabel("name:", self)
hsizer.addWidget(lbl_attr_name)
self.txt_attr_name = qtw.QLineEdit(self)
hsizer.addWidget(self.txt_attr_name)
vsizer.addLayout(hsizer)
gsizer.addLayout(vsizer, 1, 1)
vsizer = qtw.QVBoxLayout()
hsizer = qtw.QHBoxLayout()
lbl_attr_val = qtw.QLabel("value:", self)
hsizer.addWidget(lbl_attr_val)
self.txt_attr_val = qtw.QLineEdit(self)
hsizer.addWidget(self.txt_attr_val)
vsizer.addLayout(hsizer)
gsizer.addLayout(vsizer, 2, 1)
self.cb_text = qtw.QLabel('Text', self)
gsizer.addWidget(self.cb_text, 3, 0)
hsizer = qtw.QHBoxLayout()
lbl_text = qtw.QLabel("value:", self)
hsizer.addWidget(lbl_text)
self.txt_text = qtw.QLineEdit(self)
hsizer.addWidget(self.txt_text)
gsizer.addLayout(hsizer, 3, 1)
sizer.addLayout(gsizer)
hsizer = qtw.QHBoxLayout()
self.lbl_search = qtw.QLabel('', self)
hsizer.addWidget(self.lbl_search)
sizer.addLayout(hsizer)
self.lblsizer = hsizer
hsizer = qtw.QHBoxLayout()
hsizer.addStretch()
self.btn_ok = qtw.QPushButton('&Ok', self)
self.btn_ok.clicked.connect(self.accept)
self.btn_ok.setDefault(True)
hsizer.addWidget(self.btn_ok)
self.btn_cancel = qtw.QPushButton('&Cancel', self)
self.btn_cancel.clicked.connect(self.reject)
hsizer.addWidget(self.btn_cancel)
self.btn_clear = qtw.QPushButton('C&lear Values', self)
self.btn_clear.clicked.connect(self.clear_values)
hsizer.addWidget(self.btn_clear)
hsizer.addStretch()
sizer.addLayout(hsizer)
self.sizer = sizer
self.setLayout(sizer)
self.txt_element.textChanged.connect(self.set_search)
self.txt_element.setText(ele_name)
self.txt_attr_name.textChanged.connect(self.set_search)
self.txt_attr_name.setText(attr_name)
self.txt_attr_val.textChanged.connect(self.set_search)
self.txt_attr_val.setText(attr_val)
self.txt_text.textChanged.connect(self.set_search)
self.txt_text.setText(text_val)
def set_search(self):
"""build text describing search action"""
out = ''
ele = self.txt_element.text()
attr_name = self.txt_attr_name.text()
attr_val = self.txt_attr_val.text()
text = self.txt_text.text()
out = self._parent.editor.get_search_text(
ele, attr_name, attr_val, text)
self.lbl_search.setText('\n'.join(out))
# self.layout()
def clear_values(self):
"set empty search values"
self.txt_element.clear()
self.txt_attr_name.clear()
self.txt_attr_val.clear()
self.txt_text.clear()
self.lbl_search.setText('')
self.lblsizer.update() # is bedoeld om de dialoog te laten krimpen, maar werkt niet
self.sizer.update()
self.update()
# self.adjustSize()
def accept(self):
"""confirm dialog and pass changed data to parent"""
ele = str(self.txt_element.text())
attr_name = str(self.txt_attr_name.text())
attr_val = str(self.txt_attr_val.text())
text = str(self.txt_text.text())
if not any((ele, attr_name, attr_val, text)):
self._parent.meldfout(
'Please enter search criteria or press cancel')
self.txt_element.setFocus()
return
self._parent.in_dialog = True
self._parent.editor.search_args = (ele, attr_name, attr_val, text)
super().accept()
# def on_cancel(self):
# super().done(qtw.QDialog.Rejected)
class VisualTree(qtw.QTreeWidget):
"""Tree widget subclass overriding some event handlers
"""
def __init__(self, parent):
self.parent = parent
super().__init__()
def mouseDoubleClickEvent(self, event):
"reimplemented to reject when on root element"
item = self.itemAt(event.x(), event.y())
if item:
if item == self.parent.top:
edit = False
else:
## data = str(item.text(0))
edit = True
## if data.startswith(ELSTART):
## if item.childCount() > 0:
## edit = False
if edit:
self.parent.edit_item(item)
else:
event.ignore()
def mouseReleaseEvent(self, event):
"reimplemented to show popup menu when applicable"
xc, yc = event.x(), event.y()
item = self.itemAt(xc, yc)
if event.button() == core.Qt.RightButton:
if item and item != self.parent.top:
## self.parent.setCurrentItem(item)
menu = self.parent.init_menus(popup=True)
menu.exec_(event.globalPos())
else: # left click
self.parent.set_selected_item(item)
event.ignore()
class UndoRedoStack(qtw.QUndoStack):
"""Undo stack subclass overriding some event handlers
"""
def __init__(self, parent):
super().__init__(parent)
self.cleanChanged.connect(self.clean_changed)
self.indexChanged.connect(self.index_changed)
self.maxundo = self.undoLimit()
self.setUndoLimit(1) # self.unset_undo_limit(False)
## log('Undo limit {}'.format(self.undoLimit()))
win = self.parent()
win.undo_item.setText('Nothing to undo')
win.redo_item.setText('Nothing to redo')
win.undo_item.setDisabled(True)
win.redo_item.setDisabled(True)
def unset_undo_limit(self, state):
"""change undo limit"""
log('state is {}'.format(state))
if state:
self.setUndoLimit(self.maxundo)
nolim, yeslim = 'un', ''
else:
self.setUndoLimit(1)
nolim, yeslim = '', ' to one'
# self.parent().setundo_action.setChecked(state)
self.parent().statusbar.showMessage(
'Undo level is now {}limited{}'.format(
nolim, yeslim))
def clean_changed(self, state):
"""change text of undo/redo menuitems according to stack change"""
## print('undo stack status changed:', state)
win = self.parent()
if state:
win.undo_item.setText('Nothing to undo')
win.undo_item.setDisabled(state)
def index_changed(self): # , num): currently only change from 1 to unlimited and back
"""change text of undo/redo menuitems according to stack change"""
## print('undo stack index changed:', num)
win = self.parent()
test = self.undoText()
if test:
win.undo_item.setText('&Undo ' + test)
win.undo_item.setEnabled(True)
else:
win.undo_item.setText('Nothing to undo')
win.undo_item.setDisabled(True)
test = self.redoText()
if test:
win.redo_item.setText('&Redo ' + test)
win.redo_item.setEnabled(True)
else:
win.redo_item.setText('Nothing to redo')
win.redo_item.setDisabled(True)
# UndoCommand subclasses
class PasteElementCommand(qtw.QUndoCommand):
"""subclass to make Undo/Redo possible"""
def __init__(self, win, tag, text, before, below, description="",
data=None, where=None):
"""
"where we are" is optional because it can be determined from the current
position but it should also be possible to provide it
"""
self.win = win # treewidget
self.tag = tag # element name
self.data = text # element text
self.before = before # switch
self.below = below # switch
self.children = data
self.where = where
self.replaced = None # in case item is replaced while redoing
if below:
description += ' Under'
elif before:
description += ' Before'
else:
description += ' After'
# , self.item)
log("init {} {} {}".format(description, self.tag, self.data))
self.first_edit = not self.win.editor.tree_dirty
super().__init__(description)
def redo(self):
"((Re)Do add element"
def zetzeronder(node, data, before=False, below=True):
"add elements recursively"
log('zetzeronder voor node {} met data {}'.format(node, data))
text, data, children = data
tag, value = data
is_attr = False if text.startswith(ELSTART) else True
add_under = self.win.editor.add_item(
node, tag, value, before=before, below=below, attr=is_attr)
below = True
for item in children:
zetzeronder(add_under, item)
return add_under
print('redo of add')
print(' tag is', self.tag)
print(' data is', self.data)
print(' before is', self.before)
print(' below is', self.below)
print(' where is', self.where)
log('In paste element redo for tag {} data {}'.format(self.tag, self.data))
self.added = self.win.editor.add_item(
self.where,
self.tag,
self.data,
before=self.before,
below=self.below)
log('newly added {} with children {}'.format(self.added, self.children))
if self.children is not None:
for item in self.children[0][2]:
zetzeronder(self.added, item)
# if self.replaced:
## self.win.replaced[calculate_location(add_under)] = self.added
self.win.tree.expandItem(self.added)
log("self.added after adding children: {}".format(self.added))
def undo(self):
"Undo add element"
# essentially 'cut' Command
log('In paste element undo for added: {}'.format(self.added))
self.replaced = self.added # remember original item in case redo replaces it
item = CopyElementCommand(self.win, self.added, cut=True, retain=False,
description=__doc__)
item.redo()
if self.first_edit:
self.win.editor.mark_dirty(False)
self.win.statusbar.showMessage('{} undone'.format(self.text()))
class PasteAttributeCommand(qtw.QUndoCommand):
"""subclass to make Undo/Redo possible"""
def __init__(self, win, name, value, item, description=""):
super().__init__(description)
self.win = win # treewidget
self.item = item # where we are now
self.name = name # attribute name
self.value = value # attribute value
log("init {} {} {} {}".format(description, self.name, self.value, self.item))
self.first_edit = not self.win.editor.tree_dirty
super().__init__(description)
def redo(self):
"(Re)Do add attribute"
log('(redo) add attr {} {} {}'.format(self.name, self.value, self.item))
self.added = self.win.editor.add_item(
self.item, self.name, self.value, attr=True)
self.win.tree.expandItem(self.added.parent())
log('Added {}'.format(self.added))
def undo(self):
"Undo add attribute"
# essentially 'cut' Command
item = CopyElementCommand(self.win, self.added, cut=True, retain=False,
description=__doc__)
item.redo()
if self.first_edit:
self.win.editor.mark_dirty(False)
self.win.statusbar.showMessage('{} undone'.format(self.text()))
class EditCommand(qtw.QUndoCommand):
"""subclass to make Undo/Redo possible"""
def __init__(self, win, old_state, new_state, description=""):
log("building editcommand for {}".format(description))
super().__init__(description)
self.win = win
self.item = self.win.item
self.old_state = old_state
self.new_state = new_state
self.first_edit = not self.win.editor.tree_dirty
def redo(self):
"change node's state to new"
self.item.setText(0, self.new_state[0])
self.item.setText(1, self.new_state[1])
self.item.setText(2, self.new_state[2])
def undo(self):
"change node's state back to old"
self.item.setText(0, self.old_state[0])
self.item.setText(1, self.old_state[1])
self.item.setText(2, self.old_state[2])
if self.first_edit:
self.win.editor.mark_dirty(False)
self.win.statusbar.showMessage('{} undone'.format(self.text()))
class CopyElementCommand(qtw.QUndoCommand):
"""subclass to make Undo/Redo possible"""
def __init__(self, win, item, cut, retain, description=""):
super().__init__(description)
self.undodata = None
self.win = win # treewidget
self.item = item # where we are now
self.tag = str(self.item.text(1))
self.data = str(self.item.text(2)) # name and text
log("init {} {} {} {}".format(description, self.tag, self.data, self.item))
self.cut = cut
self.retain = retain
self.first_edit = not self.win.editor.tree_dirty
def redo(self):
"(Re)Do Copy Element"
def push_el(el, result):
"do this recursively"
text = str(el.text(0))
data = (str(el.text(1)), str(el.text(2)))
children = []
for ix in range(el.childCount()):
subel = el.child(ix)
push_el(subel, children)
result.append((text, data, children))
return result
log('In copy element redo for item {} with data {}'.format(self.item,
self.data))
print("redo of ", self.item)
if self.undodata is None:
print('building reference data')
self.parent = self.item.parent()
self.loc = self.parent.indexOfChild(self.item)
self.undodata = push_el(self.item, [])
if self.loc > 0:
self.prev = self.parent.child(self.loc - 1)
else:
self.prev = self.parent
if self.prev == self.win.editor.rt:
self.prev = self.parent.child(self.loc + 1)
print(' parent:', self.parent)
print(' location:', self.loc)
print(' undodata:', self.undodata)
print(' pointer fallback:', self.prev)
if self.retain:
log('Retaining item')
self.win.cut_el = self.undodata
self.win.cut_att = None
self.win.enable_pasteitems(True)
if self.cut:
log('cutting item from parent {}'.format(self.parent))
self.parent.removeChild(self.item)
self.item = self.prev
self.win.tree.setCurrentItem(self.prev)
def undo(self):
"Undo Copy Element"
log('In copy element undo for tag {} data {} item {}'.format(
self.tag, self.data, self.item))
# self.cut_el = None
if self.cut:
print('undo of', self.item)
if self.loc >= self.parent.childCount():
item = PasteElementCommand(
self.win,
self.tag,
self.data,
before=False,
below=True,
data=self.undodata,
description=__doc__,
where=self.parent)
else:
item = PasteElementCommand(
self.win,
self.tag,
self.data,
before=True,
below=False,
data=self.undodata,
description=__doc__,
where=self.parent.child(
self.loc))
item.redo() # add_under=add_under, loc=self.loc)
self.item = item.added
if self.first_edit:
self.win.editor.mark_dirty(False)
self.win.statusbar.showMessage('{} undone'.format(self.text()))
# self.win.tree.setCurrentItem(self.item)
class CopyAttributeCommand(qtw.QUndoCommand):
"""subclass to make Undo/Redo possible"""
def __init__(self, win, item, cut, retain, description):
super().__init__(description)
self.win = win # treewidget
self.item = item # where we are now
self.name = str(self.item.text(1))
self.value = str(self.item.text(2)) # name and text
log("init {} {} {} {}".format(description, self.name, self.value, self.item))
self.cut = cut
self.retain = retain
self.first_edit = not self.win.editor.tree_dirty
def redo(self):
"(re)do copy attribute"
log('copying item {} with text {}'.format(self.item, self.value))
self.parent = self.item.parent()
self.loc = self.parent.indexOfChild(self.item)
if self.retain:
log('Retaining attribute')
self.win.cut_el = None
self.win.cut_att = (self.name, self.value)
self.win.enable_pasteitems(True)
if self.cut:
log('cutting attribute')
ix = self.loc
if ix > 0:
prev = self.parent.child(ix - 1)
else:
prev = self.parent
if prev == self.win.editor.rt:
prev = self.parent.child(ix + 1)
self.parent.removeChild(self.item)
self.item = None
self.win.tree.setCurrentItem(prev)
def undo(self):
"Undo Copy attribute"
log('{} for {} {} {}'.format(__doc__, self.name, self.value, self.item))
# self.win.cut_att = None
if self.cut:
item = PasteAttributeCommand(
self.win,
self.name,
self.value,
self.parent,
description=__doc__)
item.redo()
self.item = item.added
if self.first_edit:
self.win.editor.mark_dirty(False)
self.win.statusbar.showMessage('{} undone'.format(self.text()))
# class MainFrame(qtw.QMainWindow, AxeMixin):
class Gui(qtw.QMainWindow):
"Main application window"
undoredowarning = """\
NOTE:
Limiting undo/redo to one action has a reason.
This feature may not work as intended when items are removed
and immediately un-removed or when multiple redo actions are
executed when the originals were done at different levels
in the tree.
So be prepared for surprises, I haven't quite figured this lot
out yet.
"""
def __init__(self, parent=None, fn=''):
self.editor = parent
self.app = qtw.QApplication(sys.argv)
self.fn = fn
super().__init__()
self.show()
self.pyesmini = None
self.osiFileName = None
self.oscFileName = None
self.odrFilename = None
self.osgFilename = None
self.mainUi = uic.loadUi("ui/qt.ui")
self.mainUi.pushButton_bigstepforward.clicked.connect(
lambda x: self.step(100))
self.mainUi.pushButton_stepforward.clicked.connect(
lambda x: self.step(1))
self.mainUi.pushButton_play_pause.clicked.connect(
self.playpause_clicked)
self.mainUi.pushButton_reload.clicked.connect(lambda x: self.reload(0))
self.mainUi.pushButton_stepbackward.clicked.connect(
lambda x: self.reload(1))
self.mainUi.pushButton_bigstepbackward.clicked.connect(
lambda x: self.reload(10))
self.mainUi.pushButton_obj.clicked.connect(self.updateObject)
self.mainUi.pushButton_findobj.clicked.connect(self.findObject)
# self.mainUi.pushButton_road.clicked.connect(self.updateRoad)
self.mainUi.pushButton_findroad.clicked.connect(self.findRoad)
self.mainUi.comboBox_objects.activated.connect(self.update_obj_ui)
self.mainUi.pushButton_osgview.clicked.connect(self.osg)
self.mainUi.show()
def my_set_search(self, ele, attr_name, attr_val, text):
print("SEARCH:::", ele, attr_name, attr_val, text)
self.editor.search_args = (ele, attr_name, attr_val, text)
self.editor._search_pos = None
self.editor.find_next()
def findObject(self):
# self.clear_values()
objname = self.pyesmini.getObjectName(self.currentObjIndx)
self.my_set_search("", "", objname, "")
def findRoad(self):
pass
def osg(self):
# 3
print("---------------------------------------------")
self.editor.about()
# 3
def reload(self, stepsback=-1):
disable_ctrls = self.mainUi.checkBox_disable_ctrls.isChecked()
record = self.mainUi.checkBox_record.isChecked()
if record:
recordFile = "record.rec"
else:
recordFile = ""
threads = self.mainUi.checkBox_threads.isChecked()
use_viewer = self.mainUi.checkBox_use_viewer.isChecked()
print(
"disable_ctrls =",
disable_ctrls,
", use_viewer = ",
use_viewer,
", threads = ",
threads,
", recordFile = ",
recordFile)
if self.oscFileName:
self.pyesmini = PyEsmini(
self.oscFileName,
disable_ctrls=disable_ctrls,
use_viewer=use_viewer,
threads=threads,
recordFile=recordFile,
oscFile=True)
print("Scenario is loaded::", self.pyesmini)
if stepsback < 0:
return
timestamp = float(self.mainUi.lineEdit_timestamp.text())
print("timestamp : ", timestamp)
newtimestamp = timestamp - float(stepsback) * 0.1
print("newtimestamp", newtimestamp)
self.pyesmini.stepDT(newtimestamp)
self.update_timestamps()
self.update_obj_ui()
self.update_road_ui()
def step_helper(self, steps=1):
global simulatorRunning
print("step_helper, simulatorRunning = ", simulatorRunning)
for i in range(steps):
if simulatorRunning:
self.pyesmini.step()
else:
break
simulatorRunning = False
def step(self, steps=1):
global simulatorRunning
print("Step, simulatorRunning = ", simulatorRunning)
simulatorRunning = True
x = threading.Thread(target=self.step_helper, args=(steps,))
x.start()
self.update_timestamps()
self.update_obj_ui()
self.update_road_ui()
def playpause_clicked(self):
global simulatorRunning
print("playpause_clicked, simulatorRunning = ", simulatorRunning)
if not simulatorRunning:
self.step(10000)
else:
simulatorRunning = False
self.update_timestamps()
self.update_obj_ui()
self.update_road_ui()
def updateObject(self):
print("Update button is clicked")
x = float(self.mainUi.lineEdit_x.text())
y = float(self.mainUi.lineEdit_y.text())
z = float(self.mainUi.lineEdit_z.text())
h = float(self.mainUi.lineEdit_h.text())
p = float(self.mainUi.lineEdit_p.text())
r = float(self.mainUi.lineEdit_r.text())
speed = float(self.mainUi.lineEdit_speed.text())
s = float(self.mainUi.lineEdit_s.text())
t = float(self.mainUi.lineEdit_t.text())
laneoffset = float(self.mainUi.lineEdit_laneoffset.text())
roadid = int(self.mainUi.lineEdit_roadid.text())
laneid = int(self.mainUi.lineEdit_laneid.text())
centeroffsetx = float(self.mainUi.lineEdit_centeroffsetx.text())
centeroffsety = float(self.mainUi.lineEdit_centeroffsety.text())
centeroffsetz = float(self.mainUi.lineEdit_centeroffsetz.text())
width = float(self.mainUi.lineEdit_width.text())
length = float(self.mainUi.lineEdit_length.text())
height = float(self.mainUi.lineEdit_height.text())
self.pyesmini.reportObjectPos(
id=self.currentObjIndx,
timestamp=0,
x=x,
y=y,
z=z,
h=h,
p=p,
r=r,
speed=speed)
self.pyesmini.reportObjectRoadPos(
id=self.currentObjIndx,
timestamp=0,
roadId=roadid,
laneId=laneid,
laneOffset=laneoffset,
s=s,
speed=speed)
# adding line below breaks the changes
# self.pyesmini.reportObjectLateralPosition(id = self.currentObjIndx,
# t= t))
def about(self):
QMessageBox.information(None, "Information",
"This work is done by <a href='https://www.infotiv.se'>Infotiv AB</a> under <a href='https://valu3s.eu/'>VALU3S</a> project. This project has received funding from the <a href='https://www.ecsel.eu'>ECSEL</a> Joint Undertaking (JU) under grant agreement No 876852. The JU receives support from the European Union’s Horizon 2020 research and innovation programme and Austria, Czech Republic, Germany, Ireland, Italy, Portugal, Spain, Sweden, Turkey. This project is started and currently maintained by Hamid Ebadi.")
def about_esmini(self):
QMessageBox.information(
None,
"Information",
"<a href='https://github.com/esmini/esmini'>Environment Simulator Minimalistic (esmini)</a> is a basic OpenSCENARIO player that Open Scenario Editor and PyEsmini use internally.")
def license(self):
license = open('Licenses/LICENSE_pyesmini', 'r').read()
ScrollMessageBox(QMessageBox.Information, "Linceses", str(license))
def update_timestamps(self):
self.mainUi.lineEdit_timestamp.setText(
str(self.pyesmini.getSimulationTime()))