-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidgets.py
More file actions
2664 lines (2391 loc) · 113 KB
/
widgets.py
File metadata and controls
2664 lines (2391 loc) · 113 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
from PyQt5.QtWidgets import (QStackedLayout,QVBoxLayout,QHBoxLayout,QFormLayout,QComboBox,QLineEdit,QApplication, QMainWindow,QWidget, QLabel,QPushButton,QFrame,QSizePolicy)
from PyQt5.QtWidgets import (QMenu,QTreeView, QFileSystemModel,QFileIconProvider,QSplitter, QMessageBox,QTabWidget,QTabBar,QScrollArea,QTextEdit,QListWidget,QListWidgetItem,QAbstractItemView,QGraphicsDropShadowEffect,QTableWidget,QTableWidgetItem,QHeaderView)
from PyQt5.QtGui import QColor,QIcon,QPixmap, QTextCursor,QIntValidator,QDoubleValidator,QStandardItemModel,QStandardItem,QPainter,QDrag,QFont,QTextCharFormat,QBrush
from PyQt5.QtCore import QPoint,QDir,Qt,QModelIndex,QSize,QFileInfo,QPropertyAnimation,QObject,pyqtSignal,QThread,QEvent,QMimeData,QSortFilterProxyModel
import sys
import json
import time
import traceback
from func import *
import func
THEMES = {
'macOS': {'view_board': 'macos', 'command_block': 'minimal'},
'Windows': {'view_board': 'win', 'command_block': 'macos'},
'Colors': {'view_board': 'colors', 'command_block': 'minimal'},
'Carbon': {'view_board': 'carbon', 'command_block': 'minimal'},
'Office': {'view_board': 'office', 'command_block': 'minimal'},
}
def _load_theme_from_prefs():
try:
with open(os.path.join(CURRENT_PATH, 'preferences.json'), 'r') as f:
name = json.load(f).get('theme', 'macOS')
return name if name in THEMES else 'macOS'
except (FileNotFoundError, ValueError, KeyError):
return 'macOS'
CURRENT_THEME = _load_theme_from_prefs()
ICON_STYLE_VB = THEMES[CURRENT_THEME]['view_board']
ICON_STYLE_CB = THEMES[CURRENT_THEME]['command_block']
def _load_icon_set_from_prefs():
try:
with open(os.path.join(CURRENT_PATH, 'preferences.json'), 'r') as f:
return json.load(f).get('icon_set', 'cloud')
except (FileNotFoundError, ValueError, KeyError):
return 'cloud'
ICON_SET = _load_icon_set_from_prefs()
# basic widgets
class CodeLine(QWidget):
def __init__(self,text:str='CodeLine'):
super().__init__()
self.setObjectName("CodeLine")
ICON_SIZE = 15
self._text = text
self._current_args = None
layout = QHBoxLayout()
layout.setAlignment(Qt.AlignLeft)
layout.setSpacing(1)
# play button
BUTTON_STYLE = f"""
QPushButton {{
background-color: {CONFIG["Controls"]["background-color"]};
padding: {ICON_SIZE/4}px;
width: {ICON_SIZE}px;
height: {ICON_SIZE}px;
border-radius: {ICON_SIZE/2}px;
}}
QPushButton:hover {{
background-color: {CONFIG["Controls"]["hover-color"]};
border-color: {CONFIG["Controls"]["hover-color"]}
}}
"""
self.play = QPushButton('', self)
self.play.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/play.png'))
self.play.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.play.setStyleSheet(BUTTON_STYLE)
self.play.clicked.connect(self.run_command)
layout.addWidget(self.play)
# code line
self.line = QLineEdit(self)
self.line.setText(self._text)
#self.line.setPlaceholderText(self._text)
self.line.setStyleSheet(f'''
QLineEdit {{
font:{CONFIG['CodeLine']['font']};
color:{CONFIG['CodeLine']['color']};
background-color:{CONFIG['CodeLine']['background-color']};
border:{CONFIG['CodeLine']['border']};
border-radius:{CONFIG['CodeLine']['border-radius']};
width: 100px;
height: 25px;
}}
QLineEdit:focus {{
color: {CONFIG['CodeLine']['focus']['color']};
background-color: {CONFIG['CodeLine']['focus']['background-color']};
border: 1px solid {CONFIG['CodeLine']['focus']['border-color']};
}}
''')
self.line.returnPressed.connect(self.run_command)
layout.addWidget(self.line)
self.setLayout(layout)
self._current_args = self.get_current_parameters(self.line.text())
#print(f"self._current_args = {self._current_args}") # monitor
def set_text(self,text):
self.line.setText(text)
self._text =text
def run_command(self):
def set_marks_to_text(text):
if not text.startswith('>> '):
text = '>> ' + text
return text
def get_args(text):
def get_splits(text):
pattern = r',(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)'
return re.split(pattern, text)
try:
args_string = text[text.find('(')+1:text.find(')')]
splitted_args = get_splits(args_string)
print(splitted_args)
return {item.split('=')[0]:item.split('=')[1] for item in splitted_args}
except Exception as e:
return e
#print(f"code line run Command: {set_marks_to_text(self.line.text())[3:]}") # monitor
self.line.setText(set_marks_to_text(self.line.text()))
current_cmd_block = self.parent().parent()
current_cmd_block._cmd = set_marks_to_text(self.line.text())[3:] # update new cmd
current_cmd_block._args = get_args(current_cmd_block._cmd) # get cmd args
current_cmd_block._output = 'my output'
current_cmd_block.run_command()
def get_current_parameters(self,text):
cmd_string = text[text.find('(')+1:text.rfind(')')]
matches = re.findall(r"(\w+)\s*=\s*(\[.*?\]|\(.*?\)|\{.*?\}|'.*?'|\".*?\"|[^,)]+)",cmd_string)
return {item[0].strip():item[1].strip() for item in matches}
class CodeControls(QWidget):
def __init__(self):
super().__init__()
self.setObjectName("CodeControls")
ICON_SIZE = 15
layout = QHBoxLayout()
BUTTON_STYLE = f"""
QPushButton {{
background-color: {CONFIG["Controls"]["background-color"]};
padding: {ICON_SIZE/10}px;
width: {ICON_SIZE}px;
height: {ICON_SIZE}px;
border-radius: {ICON_SIZE/2}px;
}}
QPushButton:hover {{
background-color: {CONFIG["Controls"]["hover-color"]};
border-color: {CONFIG["Controls"]["hover-color"]}
}}
"""
self.up = QPushButton('', self)
self.up.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/up.png'))
self.up.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.up.setStyleSheet(BUTTON_STYLE)
self.up.clicked.connect(self.set_up)
layout.addWidget(self.up)
self.down = QPushButton('', self)
self.down.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/down.png'))
self.down.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.down.setStyleSheet(BUTTON_STYLE)
self.down.clicked.connect(self.set_down)
layout.addWidget(self.down)
self.pin = QPushButton('', self)
self.pin.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/pin.png'))
self.pin.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.pin.setStyleSheet(BUTTON_STYLE)
self.pin.clicked.connect(self.set_pin)
layout.addWidget(self.pin)
self.add = QPushButton('', self)
self.add.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/add.png'))
self.add.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.add.setStyleSheet(BUTTON_STYLE)
self.add.clicked.connect(self.set_add)
layout.addWidget(self.add)
self.trash = QPushButton('', self)
self.trash.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/trash.png'))
self.trash.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.trash.setStyleSheet(BUTTON_STYLE)
self.trash.clicked.connect(self.set_delete)
layout.addWidget(self.trash)
self.save = QPushButton('', self)
self.save.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/save.png'))
self.save.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.save.setStyleSheet(BUTTON_STYLE)
self.save.clicked.connect(self.set_save)
layout.addWidget(self.save)
self.setLayout(layout)
def set_pin(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
layout.removeWidget(current_cmd_block)
layout.insertWidget(0,current_cmd_block)
def set_up(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
if current_index > 0:
layout.removeWidget(current_cmd_block)
layout.insertWidget(current_index - 1, current_cmd_block)
def set_down(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
if current_index < layout.count() - 1:
layout.removeWidget(current_cmd_block)
layout.insertWidget(current_index + 1, current_cmd_block)
def set_add(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
layout.insertWidget(current_index + 1, CommandBlock(cmd=current_cmd_block._cmd))
def set_delete(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
layout.removeWidget(current_cmd_block)
current_cmd_block.deleteLater()
def set_save(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
data_viewer = DATA_TABLE.get('data_viewer')
if data_viewer:
data_viewer.story_container.addWidget(current_cmd_block)
layout.update()
class OutputControls(QWidget):
def __init__(self):
super().__init__()
self.setObjectName("OutputControls")
ICON_SIZE = 20
layout = QHBoxLayout()
layout.setAlignment(Qt.AlignLeft) # Align buttons to the left
BUTTON_STYLE = f"""
QPushButton {{
background-color: {CONFIG["Controls"]["background-color"]};
padding: {ICON_SIZE/4}px;
width: {ICON_SIZE}px;
height: {ICON_SIZE}px;
border-radius: {ICON_SIZE/2}px;
}}
QPushButton:hover {{
background-color: {CONFIG["Controls"]["hover-color"]};
border-color: {CONFIG["Controls"]["hover-color"]}
}}
"""
self.pic = QPushButton('', self)
self.pic.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/pic.png'))
self.pic.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.pic.setStyleSheet(BUTTON_STYLE)
self.pic.clicked.connect(self.set_picture)
layout.addWidget(self.pic)
self.comment = QPushButton('', self)
self.comment.setIcon(QIcon(f'{CURRENT_PATH}/icons/command_block/{ICON_STYLE_CB}/comment.png'))
self.comment.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.comment.setStyleSheet(BUTTON_STYLE)
self.comment.clicked.connect(self.set_comment)
layout.addWidget(self.comment)
self.setLayout(layout)
def set_comment(self):
#print('comment') # monitor
current_cmd_block = self.parent().parent()
current_cmd_block.add_comment()
def set_pin(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
layout.removeWidget(current_cmd_block)
layout.insertWidget(0,current_cmd_block)
def set_up(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
if current_index > 0:
layout.removeWidget(current_cmd_block)
layout.insertWidget(current_index - 1, current_cmd_block)
def set_down(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
if current_index < layout.count() - 1:
layout.removeWidget(current_cmd_block)
layout.insertWidget(current_index + 1, current_cmd_block)
def set_add(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
layout.insertWidget(current_index + 1, CommandBlock(cmd=current_cmd_block._cmd))
def set_delete(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
current_index = layout.indexOf(current_cmd_block)
layout.removeWidget(current_cmd_block)
current_cmd_block.deleteLater()
def set_save(self):
current_cmd_block = self.parent().parent()
layout = current_cmd_block.parent().layout()
data_viewer = DATA_TABLE.get('data_viewer')
if data_viewer:
data_viewer.story_container.addWidget(current_cmd_block)
layout.update()
def set_fold(self):
def is_folded(cmd_block):
return len(cmd_block._folded_items) > 0
#print("Folding")
current_cmd_block = self.parent().parent()
items = current_cmd_block.children()[0].children()
if current_cmd_block._output != None:
if is_folded(cmd_block=current_cmd_block):
current_cmd_block._output.show()
current_cmd_block._folded_items = []
current_cmd_block.block.setFixedHeight(150 + current_cmd_block._output._height)
else:
current_cmd_block._output.hide()
current_cmd_block._folded_items.append(current_cmd_block._output)
current_cmd_block.block.setFixedHeight(170)
#current_cmd_block.layout.addWidget(TextOutput(text='>>>'))
def set_picture(self):
output_item = self.parent().parent()._output
pixmap = QPixmap(output_item.size())
output_item.render(pixmap)
QApplication.clipboard().setPixmap(pixmap)
class ArgsMenu(QWidget):
def __init__(self,args:dict,cmd_block=None):
super().__init__()
self.setObjectName("ArgsMenu")
self._args = {}
self._cmd_block = cmd_block
MAX_ARG_WIDTH = 220
LABEL_STYLE = f"""
QLabel {{
font: {CONFIG['CodeLine']['font']};
color: {CONFIG['CodeLine']['color']};
padding: 0px 0px;
border: none;
}}
"""
self.form_layout = QFormLayout()
self.form_layout.setLabelAlignment(Qt.AlignRight) # Align labels
self.form_layout.setFormAlignment(Qt.AlignTop)
self.form_layout.setContentsMargins(40,0,40,0)
dt_label = QLabel('data table = ')
dt_label.setStyleSheet(LABEL_STYLE)
dt_arg_label = QLabel(f"{DATA_TABLE['tables'][DATA_TABLE['current_table_index']]._file_name}")
dt_arg_label.setStyleSheet(LABEL_STYLE)
self.form_layout.addRow(dt_label, dt_arg_label)
for arg_name,arg in args.items():
arg_label = QLabel(arg_name + ' =')
arg_label.setStyleSheet(LABEL_STYLE)
if arg['type'] == 'category':
combo = QComboBox()
combo.setStyleSheet(
"QComboBox { "
f"font: {CONFIG['arguments']['font']}; "
"color: purple;"
"padding: 1px 1px; "
"border: 1px solid #dedede; "
"border-radius: 5px; "
f"background-color: #f9f0fa; "
"selection-background-color: #dedede; "
"}"
"QComboBox::down-arrow {"
"border: none;"
"background: none;"
"}"
"QComboBox::drop-down {"
"border: none;"
"}"
)
combo.addItems(arg['options'])
#print(f"arg_name = {arg_name}, chosen = {self.get_parameter_value(arg_name)} all options = {arg['options']}") # monitor
combo.setCurrentText(f"'{str(self.get_parameter_value(arg_name))}'") # Set default text
combo.setFixedWidth(min(MAX_ARG_WIDTH,20 + max([12*len(str(item)) for item in arg['options']])))
combo.currentIndexChanged.connect(self.update_command)
self.form_layout.addRow(arg_label,combo)
elif arg['type'] in ['integer','float']:
int_arg = QLineEdit()
int_arg.setValidator(QDoubleValidator() if arg['type'] == 'float' else QIntValidator())
int_arg.setText(str(self.get_parameter_value(arg_name))) # Set default text
int_arg.setFixedWidth(min(MAX_ARG_WIDTH,max([12*len(str(item)) for item in arg['options']])))
int_arg.setStyleSheet(
"QLineEdit { "
f"font: {CONFIG['arguments']['font']}; "
"color: green;"
"padding: 1px 1px; "
"border: 1px solid #dedede; "
"border-radius: 5px; "
f"background-color: #f0faf7; "
"selection-background-color: #eafaf1; "
"}"
)
int_arg.textChanged.connect(self.update_command)
self.form_layout.addRow(arg_label,int_arg)
elif arg['type'] == 'text':
text_arg = QLineEdit()
text_arg.setText(f"'{str(self.get_parameter_value(arg_name))}'".replace("''","'")) # Set default text
text_arg.setFixedWidth(150)
text_arg.setStyleSheet(
"QLineEdit { "
f"font: {CONFIG['arguments']['font']}; "
"color: blue;"
"padding: 1px 1px; "
"border: 1px solid #dedede; "
"border-radius: 5px; "
f"background-color: #edfbfc; "
"selection-background-color: #eafaf1; "
"}"
)
text_arg.textChanged.connect(self.update_command)
self.form_layout.addRow(arg_label,text_arg)
elif arg['type'] == 'query':
self.sql_arg = QTextEdit()
self.sql_arg.setStyleSheet(f"""
QTextEdit {{
font:{CONFIG['CodeLine']['font']};
color:{CONFIG['CodeLine']['color']};
border: {CONFIG['CodeLine']['border']};
background-color: {CONFIG['CodeLine']['background-color']};
border-radius: 5px;
padding: 15px;
}}
QTextEdit:focus {{
border: 2px solid #3498db;
background-color: white;
}}
""")
self.sql_arg.setHtml(str(self.get_parameter_value(arg_name)[1:-1]))
self.sql_arg.textChanged.connect(self.set_sql)
self.form_layout.addRow(arg_label,self.sql_arg)
elif arg['type'] == 'items':
self.item_list = QListWidget()
self.item_list.setSelectionMode(QAbstractItemView.MultiSelection)
self.item_list.setStyleSheet(
f"""
QListWidget {{
background-color: None;
border: None;
padding: 3px;
font: {CONFIG['CodeLine']['font']};
}}
"""
)
self.item_list.setFlow(QListWidget.LeftToRight)
self.item_list.setWrapping(True) # Allow wrapping if width is exceeded
checked_items = self.get_parameter_value(arg_name)
for text_item in arg['options']:
item = QListWidgetItem(text_item)
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
if text_item in checked_items:
item.setCheckState(Qt.Checked)
else:
item.setCheckState(Qt.Unchecked)
self.item_list.addItem(item)
self.item_list.itemChanged.connect(self.update_command)
self.form_layout.addRow(arg_label,self.item_list)
self.setLayout(self.form_layout)
def get_parameter_value(self,arg_name: str):
"""
Extracts the value of a parameter from a Python-like function call string.
Returns the value as a Python object when possible, else as raw string.
"""
# Regex: match arg_name=value (value can be quoted, bracketed, or bare)
cmd_string = self._cmd_block._cmd
pattern = rf"{arg_name}\s*=\s*(\[.*?\]|\(.*?\)|\{{.*?\}}|'.*?'|\".*?\"|[^,)\s]+)"
match = re.search(pattern, cmd_string)
if not match:
return None # arg not found
raw_value = match.group(1).strip()
try:
# Safely convert to Python literal (str, int, float, bool, list, dict, tuple, None)
return ast.literal_eval(raw_value)
except Exception:
# If not evaluable (e.g., variable name), return raw string
return raw_value
def set_sql(self):
# print(self.sql_arg.toPlainText()) # monitor
query_string = '"' + self.sql_arg.toPlainText().replace('\n',' ').replace('"', "'") + '"'
cmd = self._cmd_block.code_line._text
query_end_index = min([cmd.find(c,cmd.find('query=') + len('query=') + 1) for c in [')','"',"'"]])
old_query = cmd[cmd.find('query=') + len('query='):query_end_index]
#self._cmd_block.code_line.set_text(f"old_query = {old_query} >> new query = {query_string}") # monitor
self._cmd_block.code_line.set_text(cmd.replace(old_query,query_string))
def update_command(self):
def set_new_parameters_to_cmd(cmd:str,args:ArgsMenu) -> str:
def delete_func_parameters(cmd:str):
open_idx = cmd.find('(')
close_idx = cmd.rfind(')')
if open_idx == -1 or close_idx == -1:
return cmd
prefix = cmd[:open_idx + 1]
suffix = cmd[close_idx:]
params = cmd[open_idx + 1:close_idx]
new_params = []
delete_flag = False
bracket_depth = 0
for char in params:
if char in ['[', '(', '{']:
bracket_depth += 1
elif char in [']', ')', '}']:
if bracket_depth > 0:
bracket_depth -= 1
continue
if bracket_depth > 0 and delete_flag:
continue
if char == '=' and bracket_depth == 0:
delete_flag = True
new_params.append(char)
continue
elif char == ',' and bracket_depth == 0:
delete_flag = False
new_params.append(char)
continue
if delete_flag:
continue
new_params.append(char)
return prefix + ''.join(new_params) + suffix
def get_new_parameters(args:ArgsMenu):
"""Get widget values, safely serialized for command injection."""
param = []
for widget in args.children():
if isinstance(widget, QComboBox):
val = widget.currentText()
elif isinstance(widget, QLineEdit):
val = widget.text()
elif isinstance(widget, QTextEdit):
val = widget.toPlainText()
elif isinstance(widget, QListWidget):
val = [widget.item(i).text() for i in range(widget.count()) if widget.item(i).checkState() == Qt.Checked]
else:
continue
# Serialize lists, tuples, dicts, numbers, bools, None
if isinstance(val, (list, tuple, dict)):
param.append(repr(val))
else:
# Keep normal strings as-is (no extra quotes)
param.append(val if val != '' else None)
return param
cmd_string = delete_func_parameters(cmd)
values = get_new_parameters(args)
for val in values:
if val is None:
continue # skip empty values
cmd_string = cmd_string.replace('=', f"@{val}", 1)
return cmd_string.replace('@', '=')
#print('update command') # monitor
# set code line
code_line = self.parent().findChild(CodeLine)
code_line.set_text(set_new_parameters_to_cmd(cmd=code_line._text,args=self))
code_line._current_args = code_line.get_current_parameters(code_line.line.text())
# set arguments fields
#print(self.children()[1:])
for item,current_arg in zip(self.children()[1:],code_line._current_args.values()):
#print(f"item={item}, current_arg={current_arg}") # monitor
if isinstance(item,QComboBox):
item.setCurrentText(current_arg)
elif isinstance(item,QLineEdit):
item.setText(current_arg)
elif isinstance(item,QTextEdit):
item.setHtml(current_arg)
class Comment(QWidget):
def __init__(self, expanded_height=120, duration=500):
super().__init__()
self._ROW_HEIGHT = 30
self._EXPANDED_HEIGHT = expanded_height
self._placeholder_cleared = False
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(0, 0, 0, 0)
main_layout.setSpacing(2)
TOOLBAR_BTN = f"""
QPushButton {{
background: transparent;
border: none;
font: 12px "Consolas";
padding: 2px 8px;
border-radius: 4px;
min-width: 24px;
}}
QPushButton:hover {{
background: {CONFIG['Controls']['hover-color']};
}}
QPushButton:checked {{
background: {CONFIG['CodeLine']['border'].split(' ')[-1]};
}}
"""
self.toolbar = QWidget()
self.toolbar.setFixedHeight(28)
tb_layout = QHBoxLayout(self.toolbar)
tb_layout.setContentsMargins(4, 0, 4, 0)
tb_layout.setSpacing(2)
self.btn_red = QPushButton("A")
self.btn_red.setStyleSheet(TOOLBAR_BTN + "QPushButton { color: #d32f2f; font-weight: bold; }")
self.btn_red.clicked.connect(lambda: self._set_color(QColor("#d32f2f")))
tb_layout.addWidget(self.btn_red)
self.btn_green = QPushButton("A")
self.btn_green.setStyleSheet(TOOLBAR_BTN + "QPushButton { color: #2e7d32; font-weight: bold; }")
self.btn_green.clicked.connect(lambda: self._set_color(QColor("#2e7d32")))
tb_layout.addWidget(self.btn_green)
self.btn_black = QPushButton("A")
self.btn_black.setStyleSheet(TOOLBAR_BTN + "QPushButton { color: #000000; font-weight: bold; }")
self.btn_black.clicked.connect(lambda: self._set_color(QColor("#000000")))
tb_layout.addWidget(self.btn_black)
tb_layout.addStretch()
self.toolbar.hide()
main_layout.addWidget(self.toolbar)
self.text_box = QTextEdit()
self.text_box.setStyleSheet(f"""
QTextEdit {{
font: {CONFIG['CodeLine']['font']};
color: black;
border: {CONFIG['CodeLine']['border']};
background-color: {CONFIG['CodeLine']['background-color']};
border-radius: {CONFIG['CodeLine']['border-radius']};
padding: 5px;
}}
QTextEdit:focus {{
color: {CONFIG['CodeLine']['focus']['color']};
background-color: {CONFIG['CodeLine']['focus']['background-color']};
border: 1px solid {CONFIG['CodeLine']['focus']['border-color']};
}}
""")
self.text_box.setHtml("<p>Type Comment.</p>")
self.text_box.setFixedHeight(self._EXPANDED_HEIGHT)
self.text_box.installEventFilter(self)
main_layout.addWidget(self.text_box)
def _set_color(self, color):
fmt = QTextCharFormat()
fmt.setForeground(color)
self._apply_format(fmt)
def _apply_format(self, fmt):
cursor = self.text_box.textCursor()
if cursor.hasSelection():
cursor.mergeCharFormat(fmt)
else:
self.text_box.mergeCurrentCharFormat(fmt)
self.text_box.setFocus()
def showEvent(self, event):
super().showEvent(event)
self.expand_editor()
def eventFilter(self, obj, event):
if obj == self.text_box:
if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Escape:
self.collapse_editor()
return True
elif event.type() in (QEvent.FocusIn, QEvent.MouseButtonPress):
self.expand_editor()
return super().eventFilter(obj, event)
def collapse_editor(self):
self.text_box.setReadOnly(True)
self.text_box.setFixedHeight(self._ROW_HEIGHT)
self.text_box.setStyleSheet(f"""
QTextEdit {{
font: {CONFIG['CodeLine']['font']};
color: black;
border: none;
background-color: transparent;
padding: 5px;
}}
""")
palette = self.text_box.palette()
palette.setColor(palette.Base, QColor(0, 0, 0, 0))
self.text_box.setPalette(palette)
self.text_box.viewport().setAutoFillBackground(False)
self.text_box.clearFocus()
self.toolbar.hide()
def expand_editor(self):
self.text_box.setReadOnly(False)
self.text_box.setFixedHeight(self._EXPANDED_HEIGHT)
self.text_box.viewport().setAutoFillBackground(True)
self.text_box.setStyleSheet(f"""
QTextEdit {{
font: {CONFIG['CodeLine']['font']};
color: black;
border: {CONFIG['CodeLine']['border']};
background-color: {CONFIG['CodeLine']['background-color']};
border-radius: {CONFIG['CodeLine']['border-radius']};
padding: 5px;
}}
QTextEdit:focus {{
color: {CONFIG['CodeLine']['focus']['color']};
background-color: {CONFIG['CodeLine']['focus']['background-color']};
border: 1px solid {CONFIG['CodeLine']['focus']['border-color']};
}}
""")
if not self._placeholder_cleared:
self.text_box.clear()
self._placeholder_cleared = True
self.text_box.setFocus(Qt.FocusReason.ActiveWindowFocusReason)
self.toolbar.show()
cursor = self.text_box.textCursor()
cursor.movePosition(QTextCursor.End)
self.text_box.setTextCursor(cursor)
# advanced widgets
class StoryDropTabBar(QTabBar):
"""Tab bar that accepts dropping a CommandBlock onto the Story tab to move it there (same as Save)."""
def __init__(self, tab_widget, story_tab_index, story_container, parent=None):
super().__init__(parent)
self._tab_widget = tab_widget
self._story_tab_index = story_tab_index
self._story_container = story_container
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat('application/x-commandblock') and isinstance(event.source(), CommandBlock):
event.acceptProposedAction()
def dragMoveEvent(self, event):
if event.mimeData().hasFormat('application/x-commandblock') and isinstance(event.source(), CommandBlock):
event.acceptProposedAction()
def dropEvent(self, event):
if not event.mimeData().hasFormat('application/x-commandblock'):
return
source = event.source()
if not isinstance(source, CommandBlock):
return
idx = self.tabAt(event.pos())
if idx != self._story_tab_index:
return
event.acceptProposedAction()
# Move block to Story (same as Save button)
old_parent = source.parent()
if old_parent and hasattr(old_parent, 'layout') and old_parent.layout():
layout = old_parent.layout()
if hasattr(layout, 'indexOf') and layout.indexOf(source) >= 0:
layout.removeWidget(source)
self._story_container.addWidget(source)
self._tab_widget.setCurrentIndex(self._story_tab_index)
class CommandBlockContainer(QWidget):
def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.setStyleSheet("CommandBlockContainer { background-color: #f9f9f9; }")
self.setObjectName("CommandBlockContainer")
self._layout = QVBoxLayout(self)
self._layout.setAlignment(Qt.AlignTop)
self._layout.setSpacing(0)
self._drop_line = QFrame(self)
self._drop_line.setFixedHeight(3)
self._drop_line.setStyleSheet("background-color: #3498db; border-radius: 1px;")
self._drop_line.hide()
def addWidget(self, widget):
self._layout.addWidget(widget)
def _get_drop_index(self, pos):
for i in range(self._layout.count()):
widget = self._layout.itemAt(i).widget()
if widget and pos.y() < widget.geometry().center().y():
return i
return self._layout.count()
def dragEnterEvent(self, event):
if isinstance(event.source(), CommandBlock):
event.acceptProposedAction()
def dragMoveEvent(self, event):
if isinstance(event.source(), CommandBlock):
event.acceptProposedAction()
idx = self._get_drop_index(event.pos())
if idx < self._layout.count():
widget = self._layout.itemAt(idx).widget()
y = widget.geometry().top() - 2
elif self._layout.count() > 0:
widget = self._layout.itemAt(self._layout.count() - 1).widget()
y = widget.geometry().bottom() + 1
else:
self._drop_line.hide()
return
self._drop_line.setGeometry(4, y, self.width() - 8, 3)
self._drop_line.show()
self._drop_line.raise_()
def dragLeaveEvent(self, event):
self._drop_line.hide()
def dropEvent(self, event):
self._drop_line.hide()
source = event.source()
if isinstance(source, CommandBlock):
target_index = self._get_drop_index(event.pos())
self._layout.removeWidget(source)
self._layout.insertWidget(target_index, source)
event.acceptProposedAction()
class CommandBlock(QWidget):
def __init__(self, dt: DataTable = pd.DataFrame(), cmd: str = ''):
super().__init__()
self.setObjectName("CommandBlock")
self._dt = dt
self._cmd = cmd
self._args = None
self._output = None
self._folded_items = []
# --- Main layout for the *entire* CommandBlock widget ---
# This layout will hold the white frame.
# We pass 'self' to set this as the main layout for CommandBlock
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
container_layout = QVBoxLayout(self)
container_layout.setContentsMargins(6, 4, 6, 4)
container_layout.setSpacing(0)
self.block = QFrame()
self.block.setFrameShape(QFrame.NoFrame)
self.block.setObjectName("CommandBlock_Frame")
self.block.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
self.block.setStyleSheet(f"""
QFrame#CommandBlock_Frame {{
background-color: white;
border: 1px solid #e8e8e8;
border-radius: 8px;
}}
""")
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(10)
shadow.setOffset(0, 2)
shadow.setColor(QColor(0, 0, 0, 40))
self.block.setGraphicsEffect(shadow)
self.layout = QVBoxLayout()
self.layout.setContentsMargins(8, 6, 8, 6)
self.layout.setSpacing(4)
self.code_layout = QHBoxLayout()
self._code_line = CodeLine(text=self._cmd)
self.code_layout.addWidget(self._code_line)
self.code_layout.addWidget(CodeControls())
self.layout.addLayout(self.code_layout)
self.block.setLayout(self.layout)
container_layout.addWidget(self.block)
def get_attributes(self):
return {'self._cmd':f"{self._cmd}",'self._args':f"{self._args}",'self._output':f"{self._output}"}
def add_comment(self):
self.comment = Comment()
self.layout.addWidget(self.comment)
def run_command(self):
def delete_prev_output(self):
for item_type in [ArgsMenu, TextOutput, TableOutput, AnalysisOutput, PlotOutput, OutputControls]:
try:
output_widget = self.findChild(item_type)
output_widget.setParent(None)
output_widget.deleteLater()
except:
pass
delete_prev_output(self)
try:
# no threads run
local_vars = {'df': self._dt._df, 'dt': self._dt}
local_vars.update({k: getattr(func, k) for k in dir(func) if not k.startswith("_")})
output_obj = eval(self._cmd, {}, local_vars)
self._args = ArgsMenu(args=output_obj['args'], cmd_block=self)
self.layout.addWidget(self._args)
self.output_controls = OutputControls() ##
self.layout.addWidget(self.output_controls) ##
if output_obj['output_type'] == 'text':
self._output = TextOutput(output_obj['output'])
elif output_obj['output_type'] == 'table':
self._output = TableOutput(output_obj['output'])
elif output_obj['output_type'] == 'plot':
self._output = PlotOutput(fig=output_obj['output'])
elif output_obj['output_type'] == 'analysis':
self._output = AnalysisOutput(
plot=output_obj['output']['plot'],
log=output_obj['output']['log'],
table=output_obj['output']['table']
)
except Exception:
#pass # use for full exception in vscode
error = traceback.format_exc()
self._output = TextOutput(text=error)
self.layout.addWidget(self._output)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self._drag_start_pos = event.pos()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if not (event.buttons() & Qt.LeftButton) or not hasattr(self, '_drag_start_pos'):
return super().mouseMoveEvent(event)
if (event.pos() - self._drag_start_pos).manhattanLength() < QApplication.startDragDistance():
return super().mouseMoveEvent(event)
drag = QDrag(self)
mime = QMimeData()
mime.setData('application/x-commandblock', b'')
drag.setMimeData(mime)
pixmap = self.grab()
scaled = pixmap.scaledToWidth(min(pixmap.width(), 400), Qt.SmoothTransformation)
painter = QPainter(scaled)
painter.setCompositionMode(QPainter.CompositionMode_DestinationIn)
painter.fillRect(scaled.rect(), QColor(0, 0, 0, 140))
painter.end()
drag.setPixmap(scaled)
drag.setHotSpot(event.pos())
drag.exec_(Qt.MoveAction)
# data viewer
class DataViewer(QWidget):
def __init__(self):
super().__init__()
self.setObjectName("DataViewer")
layout = QVBoxLayout()
# Create tab widget
self.tabs = QTabWidget()
self.tabs.tabBar().setExpanding(False)
tabs_shadow = QGraphicsDropShadowEffect(self)
tabs_shadow.setBlurRadius(20)
tabs_shadow.setOffset(0, 4)
tabs_shadow.setColor(QColor(0, 0, 0, 40))
self.tabs.setGraphicsEffect(tabs_shadow)
self.tabs.setStyleSheet(f"""
QTabWidget::pane {{
border: none;
background: #f5f5f5;
border-radius: 8px;
}}