-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_core.py
More file actions
629 lines (496 loc) · 21.3 KB
/
Copy pathgui_core.py
File metadata and controls
629 lines (496 loc) · 21.3 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
from __future__ import annotations
"""gui_core.py
Mechanics GUI (PySide6) — a mdsolids-style launcher for the mechanics project.
It runs your existing CLIs using the current interpreter:
- python -m beams.cli ...
- python -m truss2D.cli ...
Run from repo root:
python gui_core.py
"""
import csv
import json
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Sequence
from PySide6 import QtCore, QtGui, QtWidgets
import gui_utils
from gui_log import LogPanel, QtLogHandler
logger = logging.getLogger("mechanics.gui")
@dataclass(frozen=True)
class ToolProfile:
key: str
title: str
module: str
template_kinds: tuple[str, ...]
default_in_dir: str
default_out_dir: str
anastruct_plots: tuple[str, ...]
TOOL_BEAMS = ToolProfile(
key="beams",
title="Beams",
module="beams.cli",
template_kinds=("beam_simple", "simply_supported_point"),
default_in_dir="beams/in",
default_out_dir="beams/out",
anastruct_plots=("structure", "reaction_force", "axial_force", "shear_force", "bending_moment", "displacement"),
)
TOOL_TRUSS = ToolProfile(
key="truss2D",
title="Truss 2D",
module="truss2D.cli",
template_kinds=("hinged_example", "triangle"),
default_in_dir="truss2D/in",
default_out_dir="truss2D/out",
anastruct_plots=("structure", "reaction_force", "axial_force", "shear_force", "bending_moment", "displacement"),
)
class CommandWorker(QtCore.QThread):
line = QtCore.Signal(str)
finished_result = QtCore.Signal(int, str, str) # rc, stdout, stderr
def __init__(self, *, cwd: Path, module: str, argv: Sequence[str], log_level: str) -> None:
super().__init__()
self._cwd = cwd
self._module = module
self._argv = list(argv)
self._log_level = log_level
def run(self) -> None:
def on_line(s: str) -> None:
self.line.emit(s)
res = gui_utils.run_module_command(
cwd=self._cwd,
module=self._module,
argv=self._argv,
log_level=self._log_level,
on_line=on_line,
)
self.finished_result.emit(res.returncode, res.stdout, res.stderr)
class FilePreview(QtWidgets.QTabWidget):
def __init__(self, parent: Optional[QtWidgets.QWidget] = None) -> None:
super().__init__(parent)
self._text = QtWidgets.QPlainTextEdit()
self._text.setReadOnly(True)
self._text.setFont(QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont))
self._table = QtWidgets.QTableWidget()
self._table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self._img = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
self._img.setMinimumHeight(240)
self._img.setText("No image loaded")
self.addTab(self._text, "Text / JSON")
self.addTab(self._table, "CSV")
self.addTab(self._img, "Image")
self._current_path: Optional[Path] = None
def load(self, path: Path) -> None:
self._current_path = path
suf = path.suffix.lower()
self._text.setPlainText("")
self._table.clear()
self._table.setRowCount(0)
self._table.setColumnCount(0)
self._img.setPixmap(QtGui.QPixmap())
self._img.setText("")
if suf in (".png", ".jpg", ".jpeg", ".bmp", ".gif"):
self._load_image(path)
self.setCurrentWidget(self._img)
return
if suf == ".csv":
self._load_csv(path)
self.setCurrentWidget(self._table)
return
self._load_text_or_json(path)
self.setCurrentWidget(self._text)
def _load_image(self, path: Path) -> None:
pix = QtGui.QPixmap(str(path))
if pix.isNull():
self._img.setText("Unable to load image.")
return
scaled = pix.scaled(self._img.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
self._img.setPixmap(scaled)
def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
super().resizeEvent(event)
if self._current_path and self._current_path.suffix.lower() in (".png", ".jpg", ".jpeg", ".bmp", ".gif"):
self._load_image(self._current_path)
def _load_csv(self, path: Path, *, max_rows: int = 200) -> None:
try:
with path.open("r", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
rows = list(reader)
except Exception:
self._text.setPlainText(gui_utils.read_text_head(path))
self.setCurrentWidget(self._text)
return
if not rows:
return
header = rows[0]
body = rows[1:max_rows + 1]
self._table.setColumnCount(len(header))
self._table.setRowCount(len(body))
self._table.setHorizontalHeaderLabels(header)
for r, row in enumerate(body):
for c, val in enumerate(row):
self._table.setItem(r, c, QtWidgets.QTableWidgetItem(val))
self._table.resizeColumnsToContents()
def _load_text_or_json(self, path: Path) -> None:
if path.suffix.lower() == ".json":
try:
obj = gui_utils.load_json(path)
self._text.setPlainText(json.dumps(obj, indent=2, sort_keys=False))
return
except Exception:
pass
self._text.setPlainText(gui_utils.read_text_head(path))
class ToolPage(QtWidgets.QWidget):
def __init__(self, *, profile: ToolProfile, root: Path, parent: Optional[QtWidgets.QWidget] = None) -> None:
super().__init__(parent)
self.profile = profile
self.root = root
self.infile = QtWidgets.QLineEdit()
self.btn_infile = QtWidgets.QPushButton("Browse…")
self.btn_infile.clicked.connect(self._pick_infile)
self.outdir = QtWidgets.QLineEdit()
self.btn_outdir = QtWidgets.QPushButton("Browse…")
self.btn_outdir.clicked.connect(self._pick_outdir)
self.chk_non_strict = QtWidgets.QCheckBox("Non-strict validation")
self.chk_no_csv = QtWidgets.QCheckBox("Disable CSV (--no-csv)")
self.chk_no_results = QtWidgets.QCheckBox("Disable results.json (--no-results-json)")
self.chk_no_plots = QtWidgets.QCheckBox("Disable plots (--no-plots)")
self.cmb_backend = QtWidgets.QComboBox()
self.cmb_backend.addItems(["(from JSON)", "anastruct", "plotly"])
self.cmb_backend.currentTextChanged.connect(self._on_backend_changed)
self.cmb_plot_format = QtWidgets.QComboBox()
self.cmb_plot_format.addItems(["html", "json"])
self.spin_dpi = QtWidgets.QSpinBox()
self.spin_dpi.setRange(50, 1200)
self.spin_dpi.setValue(200)
self.spin_fig_w = QtWidgets.QDoubleSpinBox()
self.spin_fig_w.setRange(2.0, 50.0)
self.spin_fig_w.setValue(12.0)
self.spin_fig_w.setDecimals(1)
self.spin_fig_h = QtWidgets.QDoubleSpinBox()
self.spin_fig_h.setRange(2.0, 50.0)
self.spin_fig_h.setValue(8.0)
self.spin_fig_h.setDecimals(1)
self.chk_zip_plots = QtWidgets.QCheckBox("Zip plots (plots.zip)")
self.spin_deform = QtWidgets.QDoubleSpinBox()
self.spin_deform.setRange(0.0, 1e6)
self.spin_deform.setValue(10.0)
self.spin_deform.setDecimals(2)
self.list_plots = QtWidgets.QListWidget()
self.list_plots.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
for p in self.profile.anastruct_plots:
it = QtWidgets.QListWidgetItem(p)
it.setSelected(True)
self.list_plots.addItem(it)
self.cmb_log_level = QtWidgets.QComboBox()
self.cmb_log_level.addItems(["INFO", "DEBUG", "WARNING", "ERROR"])
self.cmb_log_level.setCurrentText("INFO")
self.btn_help = QtWidgets.QPushButton("Help")
self.btn_help.clicked.connect(self._help)
self.cmb_template = QtWidgets.QComboBox()
self.cmb_template.addItems(list(self.profile.template_kinds))
self.btn_template = QtWidgets.QPushButton("Generate template…")
self.btn_template.clicked.connect(self._template)
self.btn_validate = QtWidgets.QPushButton("Validate")
self.btn_validate.clicked.connect(self._validate)
self.btn_solve = QtWidgets.QPushButton("Solve")
self.btn_solve.clicked.connect(self._solve)
self.btn_open_out = QtWidgets.QPushButton("Open output folder")
self.btn_open_out.clicked.connect(lambda: gui_utils.open_in_file_browser(self.outdir.text()))
self.outputs = QtWidgets.QListWidget()
self.outputs.itemSelectionChanged.connect(self._on_output_selected)
self.preview = FilePreview()
form = QtWidgets.QFormLayout()
row1 = QtWidgets.QHBoxLayout()
row1.addWidget(self.infile, 1)
row1.addWidget(self.btn_infile)
form.addRow("Input JSON:", row1)
row2 = QtWidgets.QHBoxLayout()
row2.addWidget(self.outdir, 1)
row2.addWidget(self.btn_outdir)
form.addRow("Output dir:", row2)
form.addRow("", self.chk_non_strict)
grp_outputs = QtWidgets.QGroupBox("Outputs")
vout = QtWidgets.QVBoxLayout(grp_outputs)
vout.addWidget(self.chk_no_csv)
vout.addWidget(self.chk_no_results)
vout.addWidget(self.chk_no_plots)
grp_plot = QtWidgets.QGroupBox("Plot settings")
g = QtWidgets.QGridLayout(grp_plot)
g.addWidget(QtWidgets.QLabel("Backend:"), 0, 0)
g.addWidget(self.cmb_backend, 0, 1)
g.addWidget(QtWidgets.QLabel("Plotly format:"), 0, 2)
g.addWidget(self.cmb_plot_format, 0, 3)
g.addWidget(QtWidgets.QLabel("DPI:"), 1, 0)
g.addWidget(self.spin_dpi, 1, 1)
g.addWidget(QtWidgets.QLabel("Figsize (in):"), 1, 2)
fs = QtWidgets.QHBoxLayout()
fs.addWidget(self.spin_fig_w)
fs.addWidget(QtWidgets.QLabel("×"))
fs.addWidget(self.spin_fig_h)
fsw = QtWidgets.QWidget()
fsw.setLayout(fs)
g.addWidget(fsw, 1, 3)
g.addWidget(QtWidgets.QLabel("Deform scale:"), 2, 0)
g.addWidget(self.spin_deform, 2, 1)
g.addWidget(self.chk_zip_plots, 2, 3)
g.addWidget(QtWidgets.QLabel("Anastruct plots:"), 3, 0)
g.addWidget(self.list_plots, 3, 1, 1, 3)
actions = QtWidgets.QHBoxLayout()
actions.addWidget(QtWidgets.QLabel("Log level:"))
actions.addWidget(self.cmb_log_level)
actions.addStretch(1)
actions.addWidget(self.btn_help)
actions.addWidget(self.cmb_template)
actions.addWidget(self.btn_template)
actions.addWidget(self.btn_validate)
actions.addWidget(self.btn_solve)
actions.addWidget(self.btn_open_out)
left = QtWidgets.QVBoxLayout()
left.addLayout(form)
left.addWidget(grp_outputs)
left.addWidget(grp_plot, 1)
left.addLayout(actions)
splitter = QtWidgets.QSplitter()
left_w = QtWidgets.QWidget()
left_w.setLayout(left)
right = QtWidgets.QSplitter(QtCore.Qt.Vertical)
right.addWidget(self.outputs)
right.addWidget(self.preview)
right.setStretchFactor(0, 1)
right.setStretchFactor(1, 2)
splitter.addWidget(left_w)
splitter.addWidget(right)
splitter.setStretchFactor(0, 2)
splitter.setStretchFactor(1, 3)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(splitter, 1)
self._worker: Optional[CommandWorker] = None
self._set_defaults()
self._on_backend_changed(self.cmb_backend.currentText())
def _set_defaults(self) -> None:
in_dir = self.root / self.profile.default_in_dir
out_dir = self.root / self.profile.default_out_dir
in_dir.mkdir(parents=True, exist_ok=True)
out_dir.mkdir(parents=True, exist_ok=True)
jsons = sorted(in_dir.glob("*.json"))
if jsons:
self.infile.setText(str(jsons[0]))
else:
self.infile.setText(str(in_dir))
self.outdir.setText(str(out_dir / f"{self.profile.key}_run1"))
def _pick_infile(self) -> None:
start = Path(self.infile.text()).expanduser()
base = str(start if start.is_dir() else (start.parent if start.parent.exists() else self.root))
fn, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Select input JSON", base, "JSON Files (*.json)")
if fn:
self.infile.setText(fn)
def _pick_outdir(self) -> None:
start = Path(self.outdir.text()).expanduser()
base = str(start if start.exists() else self.root)
d = QtWidgets.QFileDialog.getExistingDirectory(self, "Select output directory", base)
if d:
self.outdir.setText(d)
def _selected_plots(self) -> list[str]:
out = []
for i in range(self.list_plots.count()):
it = self.list_plots.item(i)
if it.isSelected():
out.append(it.text())
return out
def _common_args(self, *, cmd: str) -> list[str]:
args: list[str] = [cmd, "--infile", self.infile.text()]
if cmd == "solve":
args.extend(["--outdir", self.outdir.text()])
if self.chk_non_strict.isChecked():
args.append("--non-strict")
return args
def _solve_args(self) -> list[str]:
args = self._common_args(cmd="solve")
if self.chk_no_csv.isChecked():
args.append("--no-csv")
if self.chk_no_results.isChecked():
args.append("--no-results-json")
if self.chk_no_plots.isChecked():
args.append("--no-plots")
backend = self.cmb_backend.currentText()
if backend in ("anastruct", "plotly"):
args.extend(["--plot-backend", backend])
if backend == "plotly":
args.extend(["--plot-format", self.cmb_plot_format.currentText()])
if backend == "anastruct":
plots = self._selected_plots()
if plots:
args.extend(["--anastruct-plots", ",".join(plots)])
args.extend(["--plot-dpi", str(int(self.spin_dpi.value()))])
args.extend(["--plot-figsize", f"{self.spin_fig_w.value():g}", f"{self.spin_fig_h.value():g}"])
if self.chk_zip_plots.isChecked():
args.append("--zip-plots")
args.extend(["--deform-scale", f"{self.spin_deform.value():g}"])
return args
def _run(self, argv: Sequence[str]) -> None:
if self._worker and self._worker.isRunning():
QtWidgets.QMessageBox.information(self, "Busy", "A command is already running.")
return
log_level = self.cmb_log_level.currentText()
logger.info("Running: python -m %s %s", self.profile.module, " ".join(argv))
self._worker = CommandWorker(cwd=self.root, module=self.profile.module, argv=argv, log_level=log_level)
self._worker.line.connect(lambda s: logger.info("%s", s))
self._worker.finished_result.connect(self._on_finished)
self._set_buttons(False)
self._worker.start()
def _set_buttons(self, enabled: bool) -> None:
for b in (self.btn_help, self.btn_template, self.btn_validate, self.btn_solve, self.btn_open_out):
b.setEnabled(enabled)
@QtCore.Slot(int, str, str)
def _on_finished(self, rc: int, out: str, err: str) -> None:
self._set_buttons(True)
if rc == 0:
logger.info("Command finished OK.")
else:
logger.error("Command failed (rc=%s).", rc)
if err.strip():
logger.error(err.strip())
self._refresh_outputs()
def _help(self) -> None:
self._run(["--help"])
def _validate(self) -> None:
self._run(self._common_args(cmd="validate"))
def _template(self) -> None:
kind = self.cmb_template.currentText()
start_dir = str((self.root / self.profile.default_in_dir).resolve())
fn, _ = QtWidgets.QFileDialog.getSaveFileName(
self,
f"Save template ({kind})",
str(Path(start_dir) / f"{kind}.json"),
"JSON Files (*.json)",
)
if not fn:
return
self._run(["template", "--kind", kind, "--outfile", fn])
def _solve(self) -> None:
if not self.infile.text().strip():
QtWidgets.QMessageBox.warning(self, "Missing input", "Select an input JSON file.")
return
self._run(self._solve_args())
def _refresh_outputs(self) -> None:
outdir = Path(self.outdir.text()).expanduser()
files = gui_utils.list_outputs(outdir)
self.outputs.clear()
for p in files:
it = QtWidgets.QListWidgetItem(str(p.relative_to(outdir)))
it.setData(QtCore.Qt.UserRole, str(p))
self.outputs.addItem(it)
default = gui_utils.pick_preview_file(outdir)
if default:
for i in range(self.outputs.count()):
it = self.outputs.item(i)
if Path(it.data(QtCore.Qt.UserRole)) == default:
it.setSelected(True)
break
def _on_output_selected(self) -> None:
items = self.outputs.selectedItems()
if not items:
return
p = Path(items[0].data(QtCore.Qt.UserRole))
if p.suffix.lower() == ".html":
import webbrowser
webbrowser.open_new_tab(p.resolve().as_uri())
logger.info("Opened HTML in browser: %s", p)
return
self.preview.load(p)
def _on_backend_changed(self, text: str) -> None:
use = text if text in ("anastruct", "plotly") else "(from JSON)"
is_ana = use == "anastruct"
is_plotly = use == "plotly"
self.list_plots.setEnabled(is_ana)
self.spin_dpi.setEnabled(is_ana)
self.spin_fig_w.setEnabled(is_ana)
self.spin_fig_h.setEnabled(is_ana)
self.chk_zip_plots.setEnabled(is_ana)
self.cmb_plot_format.setEnabled(is_plotly)
class HomePage(QtWidgets.QWidget):
open_tool = QtCore.Signal(str)
def __init__(self, parent: Optional[QtWidgets.QWidget] = None) -> None:
super().__init__(parent)
title = QtWidgets.QLabel("Mechanics")
title.setAlignment(QtCore.Qt.AlignCenter)
title.setStyleSheet("font-size: 26px; font-weight: 700;")
sub = QtWidgets.QLabel("Pick a solver module")
sub.setAlignment(QtCore.Qt.AlignCenter)
sub.setStyleSheet("color: #666;")
btn_beams = QtWidgets.QPushButton("Beams")
btn_truss = QtWidgets.QPushButton("Truss 2D")
for b in (btn_beams, btn_truss):
b.setMinimumHeight(72)
b.setStyleSheet("font-size: 20px; font-weight: 600;")
btn_beams.clicked.connect(lambda: self.open_tool.emit("beams"))
btn_truss.clicked.connect(lambda: self.open_tool.emit("truss2D"))
grid = QtWidgets.QGridLayout()
grid.addWidget(btn_beams, 0, 0)
grid.addWidget(btn_truss, 0, 1)
lay = QtWidgets.QVBoxLayout(self)
lay.addStretch(1)
lay.addWidget(title)
lay.addWidget(sub)
lay.addSpacing(20)
lay.addLayout(grid)
lay.addStretch(2)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, root: Path) -> None:
super().__init__()
self.root = root
self.setWindowTitle("Mechanics (mdsolids-style)")
self.resize(1200, 780)
central = QtWidgets.QWidget()
self.setCentralWidget(central)
self.log_panel = LogPanel()
self.stack = QtWidgets.QStackedWidget()
self.home = HomePage()
self.stack.addWidget(self.home)
self.pages = {
"beams": ToolPage(profile=TOOL_BEAMS, root=self.root),
"truss2D": ToolPage(profile=TOOL_TRUSS, root=self.root),
}
self.stack.addWidget(self.pages["beams"])
self.stack.addWidget(self.pages["truss2D"])
self.home.open_tool.connect(self._open_tool)
tb = QtWidgets.QToolBar("Main")
tb.setMovable(False)
self.addToolBar(tb)
act_home = QtGui.QAction("Home", self)
act_home.triggered.connect(lambda: self.stack.setCurrentWidget(self.home))
tb.addAction(act_home)
tb.addSeparator()
act_open_root = QtGui.QAction("Open repo folder", self)
act_open_root.triggered.connect(lambda: gui_utils.open_in_file_browser(self.root))
tb.addAction(act_open_root)
splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
splitter.addWidget(self.stack)
splitter.addWidget(self.log_panel)
splitter.setStretchFactor(0, 6)
splitter.setStretchFactor(1, 2)
lay = QtWidgets.QVBoxLayout(central)
lay.addWidget(splitter)
_configure_logging(self.log_panel)
logger.info("mechanics root: %s", root)
def _open_tool(self, key: str) -> None:
page = self.pages.get(key)
if page:
self.stack.setCurrentWidget(page)
def _configure_logging(panel: LogPanel) -> None:
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
handler = QtLogHandler(level=logging.DEBUG)
panel.attach_handler(handler)
root_logger.addHandler(handler)
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
sh.setFormatter(logging.Formatter("%(levelname)s | %(message)s"))
root_logger.addHandler(sh)
def main() -> int:
root = gui_utils.find_mechanics_root()
app = QtWidgets.QApplication([])
win = MainWindow(root=root)
win.show()
return app.exec()
if __name__ == "__main__":
raise SystemExit(main())