This repository has been archived by the owner on Jun 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeneratePhaseUI.py
534 lines (431 loc) · 21.1 KB
/
GeneratePhaseUI.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
import re
import argparse
from dataclasses import dataclass, field
from typing import Optional, List
HEAD = """/* Auto generated by GeneratePhaseUI.py written by liuzikai */
#ifndef UI_PHASES_H
#define UI_PHASES_H
#include "CollapsibleGroupBox.hpp"
#include <QtWidgets/QScrollArea>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QLabel>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QVBoxLayout>
#include <QEvent>
#include "Parameters.pb.h"
#include "Parameters.h"
namespace meta {
class PhaseController : public QObject {
Q_OBJECT
public:
"""
TAIL = """
private:
bool eventFilter(QObject *watched, QEvent *event) {
if (event->type() == QEvent::Wheel && qobject_cast<QAbstractSpinBox*>(watched)) {
event->ignore();
return true;
}
return QObject::eventFilter(watched, event);
}
public:
signals:
void parameterEdited();
};
}
#endif // UI_PHASES_H
"""
@dataclass
class Param:
kind: str # (Toggle)?(Int|Float)(Range)? or Enum<enum name>
name: str
label: str
options: List[str] = ""
@dataclass
class Group:
name: str
params: List[Param]
info_label: Optional[str] = None
image: List[str] = field(default_factory=list)
def parse_groups(filename: str) -> [Group]:
"""
Parse groups from proto file.
:param filename: filename of the proto file
:return: List of Groups
"""
groups = {}
enums = {}
inside_message = None
inside_enum = None
cur_group_name = None
for line in open(filename, "r", encoding="utf-8"):
line = line.strip()
if line == "": # skip empty line
continue
if inside_message is None: # not in message
if re.match(r"message +ParamSet +\{", line):
inside_message = "ParamSet"
elif re.match(r"message +Result +\{", line):
inside_message = "Result"
elif inside_message == "ParamSet":
if inside_enum is not None:
if line.startswith("}"):
inside_enum = None
else:
if g := re.match(f"^(\S+?) *= *\d+ *;", line):
enums[inside_enum].append(g.group(1))
elif not line.startswith("//"):
raise ValueError(f'Unknown enum line "{line}"')
else: # not inside enum
if g := re.match(r"^enum +(\S+?) *\{", line):
inside_enum = g.group(1)
enums[inside_enum] = []
else: # inside ParamSet but not inside enum
if line.startswith("}"):
inside_message = None
else:
if g := re.match(f"^// *GROUP: *(.+?)$", line):
cur_group_name = g.group(1)
if cur_group_name not in groups.keys():
groups[cur_group_name] = Group(name=cur_group_name, params=[])
else:
if g := re.match(r"^(?:(?:optional|required) +)?(\S+?) +(\S+?) *= *\d+ *; *// *(.*) *",
line):
kind = g.group(1)
if kind in enums.keys():
# Add an enumeration parameter
groups[cur_group_name].params.append(
Param(kind="Enum" + kind, name=g.group(2), label=g.group(3),
options=enums[kind]))
else:
# Process primitive types
if kind == "int32" or kind == "int64":
kind = "Int"
elif kind == "double" or kind == "float":
kind = "Float"
elif kind == "bool":
kind = "Toggled"
groups[cur_group_name].params.append(
Param(kind=kind, name=g.group(2), label=g.group(3)))
else:
raise ValueError(f'Line "{line}" has incorrect structure')
elif inside_message == "Result":
if g := re.match(f"^// *GROUP: *(.+?)$", line):
cur_group_name = g.group(1)
assert cur_group_name in groups.keys(), f'Group "{cur_group_name}" in Result is not specified in ParamSet'
elif g := re.match(f"^// *INFO: *(\S+)$", line):
assert groups[cur_group_name].info_label is None, f'Duplicate info label for group "{cur_group_name}"'
groups[cur_group_name].info_label = g.group(1)
elif g := re.match(f"^// *IMAGE: *(\S+)$", line):
groups[cur_group_name].image.append(g.group(1))
return groups.values()
print_line_prefix = ""
def print_line(s: str = ""):
print(print_line_prefix, s, sep="")
def generate_ui_creation_code(groups: [Group]) -> ([(str, str)], [(str, str)]):
"""
Generate UI creation (and reset) code and variable definition lists.
:param groups: processed Groups.
:return: (private variable list, public variable list), both lists in (type, name) tuple
"""
global print_line_prefix
private_vars = [] # private member variables in (type, name) tuple
public_vars = [] # public member variables in (type, name) tuple
reset_images_lines = [] # lines of code (without indentations) for resetImageLabels()
print_line_prefix = " "
print_line("explicit PhaseController(QScrollArea *area, QVBoxLayout *areaLayout, QWidget *mainWindow) {")
print_line_prefix = " "
for group in groups:
print_line(f"\n// GROUP {group.name}")
# Group container
group_obj = f"group{group.name}"
private_vars.append(("CollapsibleGroupBox*", group_obj))
print_line(f'{group_obj} = new CollapsibleGroupBox(area);')
print_line(f'{group_obj}->setTitle(QString::fromUtf8("{group.name}"));')
# Horizontal layout of the group container
h_layout_obj = f'hLayout{group.name}'
private_vars.append(("QHBoxLayout*", h_layout_obj))
print_line(f'{h_layout_obj} = new QHBoxLayout();')
# Left-side container
left_container_obj = f'leftContainer{group.name}'
private_vars.append(("QWidget*", left_container_obj))
print_line(f'{left_container_obj} = new QWidget({group_obj});')
print_line(f'{h_layout_obj}->addWidget({left_container_obj});')
# Grid layout for the left-side container
g_layout_obj = f'gLayout{group.name}'
private_vars.append(("QGridLayout*", g_layout_obj))
print_line(f'{g_layout_obj} = new QGridLayout({left_container_obj});')
print_line(f'{g_layout_obj}->setContentsMargins(0, 0, 0, 0);')
# Add parameter widgets
row_count = 0
for param in group.params:
type_str = param.kind
# Add checkbox or label
if type_str.startswith("Toggled"):
type_str = type_str[len("Toggled"):] # consume the prefix
# Checkbox
label_obj = f'{param.name}Check'
private_vars.append(("QCheckBox*", label_obj))
print_line(f'{label_obj} = new QCheckBox({left_container_obj});')
print_line(f'connect({label_obj}, SIGNAL(stateChanged(int)), this, SIGNAL(parameterEdited()));')
else:
# Label
label_obj = f'{param.name}Label'
private_vars.append(("QLabel*", label_obj))
print_line(f'{label_obj} = new QLabel({left_container_obj});')
print_line(f'{label_obj}->setText(QString::fromUtf8("{param.label}"));')
print_line(f'{g_layout_obj}->addWidget({label_obj}, {row_count}, 0, 1, 1);') # span column 0
# Get data type
if type_str.startswith("Enum"):
combo_obj = f'{param.name}Combo'
private_vars.append(("QComboBox*", combo_obj))
print_line(f'{combo_obj} = new QComboBox({left_container_obj});')
print_line(
f'connect({combo_obj}, SIGNAL(currentTextChanged(const QString &)), this, SIGNAL(parameterEdited()));')
for option in param.options:
print_line(f'{combo_obj}->addItem(QString::fromUtf8("{option}"));')
print_line(f'{g_layout_obj}->addWidget({combo_obj}, {row_count}, 1, 1, 2);') # span column 1-2
elif type_str == "": # single Toggled
pass
else: # not Enum, numerical types
if type_str.startswith("Int"):
decimal = "0"
type_str = type_str[len("Int"):] # consume the prefix
elif type_str.startswith("Float"):
decimal = "2"
type_str = type_str[len("Float"):] # consume the prefix
else:
raise ValueError(f'Unknown data type prefix in "{type_str}"')
# Add one or two spin boxes
if len(type_str) == 0:
# No keyword "Range", single spin box
spin_obj = f'{param.name}Spin'
private_vars.append(("QDoubleSpinBox*", spin_obj))
print_line(f'{spin_obj} = new QDoubleSpinBox({left_container_obj});')
print_line(f'{spin_obj}->setDecimals({decimal});')
print_line(f'{spin_obj}->setMaximum(9999);')
print_line(f'{spin_obj}->setMinimum(-9999);')
print_line(f'{spin_obj}->setFocusPolicy(Qt::StrongFocus);')
print_line(f'{spin_obj}->installEventFilter(this);')
print_line(f'connect({spin_obj}, SIGNAL(valueChanged(double)), this, SIGNAL(parameterEdited()));')
print_line(f'{g_layout_obj}->addWidget({spin_obj}, {row_count}, 1, 1, 1);') # span column 1
elif type_str == "Range" or type_str == "Pair":
# Two spin boxes
first_spin_obj = f'{param.name}{"Min" if type_str == "Range" else "X"}Spin'
private_vars.append(("QDoubleSpinBox*", first_spin_obj))
print_line(f'{first_spin_obj} = new QDoubleSpinBox({left_container_obj});')
print_line(f'{first_spin_obj}->setDecimals({decimal});')
print_line(f'{first_spin_obj}->setMaximum(9999);')
print_line(f'{first_spin_obj}->setMinimum(-9999);')
print_line(f'{first_spin_obj}->setFocusPolicy(Qt::StrongFocus);')
print_line(f'{first_spin_obj}->installEventFilter(this);')
print_line(
f'connect({first_spin_obj}, SIGNAL(valueChanged(double)), this, SIGNAL(parameterEdited()));')
print_line(f'{g_layout_obj}->addWidget({first_spin_obj}, {row_count}, 1, 1, 1);') # span column 1
second_spin_obj = f'{param.name}{"Max" if type_str == "Range" else "Y"}Spin'
private_vars.append(("QDoubleSpinBox*", second_spin_obj))
print_line(f'{second_spin_obj} = new QDoubleSpinBox({left_container_obj});')
print_line(f'{second_spin_obj}->setDecimals({decimal});')
print_line(f'{second_spin_obj}->setMaximum(9999);')
print_line(f'{second_spin_obj}->setMinimum(-9999);')
print_line(f'{second_spin_obj}->setFocusPolicy(Qt::StrongFocus);')
print_line(f'{second_spin_obj}->installEventFilter(this);')
print_line(
f'connect({second_spin_obj}, SIGNAL(valueChanged(double)), this, SIGNAL(parameterEdited()));')
print_line(f'{g_layout_obj}->addWidget({second_spin_obj}, {row_count}, 2, 1, 1);') # span column 2
else:
raise ValueError(f'Unknown param type "{type_str}"')
row_count += 1
# Move to next param
# Add vertical spacer
v_spacer_obj = f'{group.name}VSpacer'
private_vars.append(("QSpacerItem*", v_spacer_obj))
print_line(f'{v_spacer_obj} = new QSpacerItem(229, 89, QSizePolicy::Minimum, QSizePolicy::Expanding);')
print_line(f'{g_layout_obj}->addItem({v_spacer_obj}, {row_count}, 0, 1, 3);') # span column 0 to 2
row_count += 1
# Add info label if required
if group.info_label is not None:
info_obj = f'{group.info_label}Label'
public_vars.append(("QLabel*", info_obj))
print_line(f'{info_obj} = new QLabel({left_container_obj});')
print_line(f'{info_obj}->setText("");')
print_line(f'{g_layout_obj}->addWidget({info_obj}, {row_count}, 0, 1, 3);') # span column 0 to 2
row_count += 1
# Finish the left part
# Add the horizontal spacer of the group
h_spacer_obj = f'{group.name}HSpacer'
private_vars.append(("QSpacerItem*", h_spacer_obj))
print_line(f'{h_spacer_obj} = new QSpacerItem(446, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);')
print_line(f'{h_layout_obj}->addItem({h_spacer_obj});')
# Add the image label(s) if required
for image in group.image:
label_obj = f'{image}Label'
public_vars.append(("QLabel*", label_obj))
qimage_obj = f'{image}'
public_vars.append(("QImage", qimage_obj))
print_line(f'{label_obj} = new QLabel({group_obj});')
print_line(f'{label_obj}->setMinimumSize(QSize(0, 360));')
print_line(f'{label_obj}->setMaximumSize(QSize(16777215, 360));')
print_line(f'{label_obj}->setAlignment(Qt::AlignCenter);')
reset_images_lines.append(f'{label_obj}->setText("");')
print_line(f'{h_layout_obj}->addWidget({label_obj});')
print_line(f'{group_obj}->setContentLayout({h_layout_obj});') # must be at last
print_line(f'areaLayout->addWidget({group_obj});')
print_line()
# Move to next group
v_spacer_obj = f'PhaseVSpacer'
private_vars.append(("QSpacerItem*", v_spacer_obj))
print_line(f'{v_spacer_obj} = new QSpacerItem(20, 446, QSizePolicy::Minimum, QSizePolicy::Expanding);')
print_line(f'areaLayout->addItem({v_spacer_obj});')
print_line("resetImageLabels();") # call the reset function
print_line_prefix = " "
print_line("}")
print_line()
# Generate UI reset function
print_line("void resetImageLabels() {")
print_line_prefix = " "
for line in reset_images_lines:
print_line(line)
print_line_prefix = " "
print_line("}")
print_line()
return private_vars, public_vars
def generate_apply_params_code(groups: [Group]) -> None:
"""
Generate code of applying parameter set.
:param groups: processed Groups
:return: None
"""
global print_line_prefix
print_line_prefix = " "
print_line("void applyParamSet(const package::ParamSet &p) {")
print_line_prefix = " "
for group in groups:
print_line(f"\n// GROUP {group.name}")
for param in group.params:
type_str = param.kind
# Add checkbox or label
if type_str.startswith("Toggled"):
type_str = type_str[len("Toggled"):] # consume the prefix
# Checkbox
label_obj = f'{param.name}Check'
print_line(f'{label_obj}->setChecked(p.{param.name}(){".enabled()" if type_str != "" else ""});')
else:
# Label
label_obj = f'{param.name}Label'
if type_str.startswith("Enum"): # Enum
combo_obj = f'{param.name}Combo'
print_line(f'{combo_obj}->setCurrentIndex(p.{param.name}());')
elif type_str == "": # single Toggled
pass
else: # not Enum, numerical types
if type_str.startswith("Int"):
type_str = type_str[len("Int"):] # consume the prefix
elif type_str.startswith("Float"):
type_str = type_str[len("Float"):] # consume the prefix
else:
raise ValueError(f'Unknown data type prefix in "{type_str}"')
# Add one or two spin boxes
if len(type_str) == 0:
# No keyword "Range", single spin box
spin_obj = f'{param.name}Spin'
print_line(
f'{spin_obj}->setValue(p.{param.name}(){".val()" if label_obj.endswith("Check") else ""});')
elif type_str == "Range" or type_str == "Pair":
# Two spin boxes
min_spin_obj = f'{param.name}{"Min" if type_str == "Range" else "X"}Spin'
print_line(f'{min_spin_obj}->setValue(p.{param.name}().{"min" if type_str == "Range" else "x"}());')
max_spin_obj = f'{param.name}{"Max" if type_str == "Range" else "Y"}Spin'
print_line(f'{max_spin_obj}->setValue(p.{param.name}().{"max" if type_str == "Range" else "y"}());')
else:
raise ValueError(f'Unknown param type "{type_str}"')
# Move to next param
# Move to next group
print_line_prefix = " "
print_line("}")
print_line()
def generate_get_params_code(groups: [Group]) -> None:
"""
Generate code of getting parameter set from UI.
:param groups: processed Groups
:return: None
"""
global print_line_prefix
print_line_prefix = " "
print_line("package::ParamSet getParamSet() const {")
print_line_prefix = " "
print_line("package::ParamSet p;")
for group in groups:
print_line(f"\n// GROUP {group.name}")
for param in group.params:
type_str = param.kind
if type_str in ["Int", "Float"]:
spin_obj = f'{param.name}Spin'
print_line(f'p.set_{param.name}({spin_obj}->value());')
elif type_str == "Toggled":
check_obj = f'{param.name}Check'
print_line(f'p.set_{param.name}({check_obj}->isChecked());')
elif type_str.startswith("Enum"):
combo_obj = f'{param.name}Combo'
print_line(f'p.set_{param.name}((package::ParamSet::{type_str[4:]}){combo_obj}->currentIndex());')
elif type_str in ["ToggledInt", "ToggledFloat"]:
check_obj = f'{param.name}Check'
spin_obj = f'{param.name}Spin'
print_line(
f'p.set_allocated_{param.name}(alloc{type_str}({check_obj}->isChecked(), {spin_obj}->value()));')
elif type_str == "FloatRange":
min_spin_obj = f'{param.name}MinSpin'
max_spin_obj = f'{param.name}MaxSpin'
print_line(
f'p.set_allocated_{param.name}(allocFloatRange({min_spin_obj}->value(), {max_spin_obj}->value()));')
elif type_str == "ToggledFloatRange":
check_obj = f'{param.name}Check'
min_spin_obj = f'{param.name}MinSpin'
max_spin_obj = f'{param.name}MaxSpin'
print_line(
f'p.set_allocated_{param.name}(allocToggledFloatRange({check_obj}->isChecked(), {min_spin_obj}->value(), {max_spin_obj}->value()));')
elif type_str == "IntPair" or type_str == "FloatPair":
x_spin_obj = f'{param.name}XSpin'
y_spin_obj = f'{param.name}YSpin'
print_line(
f'p.set_allocated_{param.name}(alloc{type_str}({x_spin_obj}->value(), {y_spin_obj}->value()));')
else:
raise ValueError(f'Unknown param type "{type_str}" in for "{param.name}"')
# Move to next param
# Move to next group
print_line("return p;")
print_line_prefix = " "
print_line("}")
print_line()
def generate_member_variables(private_vars: [(str, str)], public_vars: [(str, str)]) -> None:
"""
Print member variable definitions.
:param private_vars: private variable list in (type, name) tuple
:param public_vars: private variable list in (type, name) tuple
:return: None
"""
global print_line_prefix
print_line_prefix = " "
print("\nprivate:\n")
for kind, field in private_vars:
print_line(f'{kind} {field};')
print("\npublic:\n")
for kind, field in public_vars:
print_line(f'{kind} {field};')
def generate_all(proto_file: str) -> None:
groups = parse_groups(proto_file)
print(HEAD)
private_vars, public_vars = generate_ui_creation_code(groups)
generate_apply_params_code(groups)
generate_get_params_code(groups)
generate_member_variables(private_vars, public_vars)
print(TAIL)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("proto", help="Input proto file")
args = parser.parse_args()
generate_all(args.proto)