pymetrix-guide 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pymetrix_guide/__init__.py +109 -0
- pymetrix_guide/_version.py +1 -0
- pymetrix_guide/app.py +494 -0
- pymetrix_guide/casestudy.py +452 -0
- pymetrix_guide/checks.py +99 -0
- pymetrix_guide/courses/case_studies/03_forecast_round_guided.md +343 -0
- pymetrix_guide-0.1.0a1.dist-info/METADATA +167 -0
- pymetrix_guide-0.1.0a1.dist-info/RECORD +11 -0
- pymetrix_guide-0.1.0a1.dist-info/WHEEL +4 -0
- pymetrix_guide-0.1.0a1.dist-info/entry_points.txt +8 -0
- pymetrix_guide-0.1.0a1.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Guided case studies for pymetrix (``pymetrix-guide``): a trainee follows a workflow step by step in the desktop
|
|
2
|
+
app, through the real dialogs, and each step is checked as they go.
|
|
3
|
+
|
|
4
|
+
A case study is a Markdown file in a course folder with fenced ``pymetrix-step`` blocks (``casestudy``): each names
|
|
5
|
+
a dialog, its settings and a declarative check (``checks``), and ``##`` sections before the first step make its
|
|
6
|
+
introduction. The **Guide** panel (View → Guide) lists the case studies in the loaded courses, shows the
|
|
7
|
+
introduction and then one step at a time, with the stage of the workflow it belongs to, opens the step's dialog
|
|
8
|
+
filled in (**Open…**) or runs it (**Show me**), and ticks the step when its check passes. The steps are ordinary recorded steps, so the script, the
|
|
9
|
+
project and a lab book capture the trainee's work; the guide keeps no record of its own.
|
|
10
|
+
|
|
11
|
+
The plugin ships Lab 3 of the example course, the quarterly forecast round, as its first case study (a course in
|
|
12
|
+
the ``pymetrix.courses`` group, so it is in the help too).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from ._version import __version__
|
|
21
|
+
from pymetrix.extension import PluginInfo
|
|
22
|
+
|
|
23
|
+
PLUGIN = PluginInfo(
|
|
24
|
+
name="pymetrix-guide",
|
|
25
|
+
version=__version__,
|
|
26
|
+
api="1.5", # the oldest it works with: from 1.7 the panel opens a case study's demo (AppInterface.open_demo)
|
|
27
|
+
license="BSD-3-Clause",
|
|
28
|
+
maintainer="Geoffrey Heenan",
|
|
29
|
+
description="Guided case studies: follow a workflow step by step in the desktop app, with each step checked",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
from .casestudy import ( # noqa: E402
|
|
33
|
+
CaseStudy,
|
|
34
|
+
CaseStudyError,
|
|
35
|
+
CaseStudyWarning,
|
|
36
|
+
IntroPage,
|
|
37
|
+
Step,
|
|
38
|
+
build_command,
|
|
39
|
+
check_case_study,
|
|
40
|
+
parse,
|
|
41
|
+
read,
|
|
42
|
+
)
|
|
43
|
+
from .checks import Check, CheckError, parse_check # noqa: E402
|
|
44
|
+
|
|
45
|
+
_STEP_FENCE = re.compile(r"^\s*(`{3,}|~{3,})\s*pymetrix-step\s*$", re.MULTILINE)
|
|
46
|
+
COURSES = Path(__file__).resolve().parent / "courses"
|
|
47
|
+
_registered = False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def register() -> None:
|
|
51
|
+
"""The entry point: register the Guide panel (once). Qt is imported only when the app builds the panel."""
|
|
52
|
+
global _registered
|
|
53
|
+
if _registered:
|
|
54
|
+
return
|
|
55
|
+
from pymetrix.extension import AppPanel, plugin_context, register as add
|
|
56
|
+
|
|
57
|
+
def create(app): # noqa: ANN001, ANN202 - an AppInterface; returns a QWidget
|
|
58
|
+
from .app import create_panel
|
|
59
|
+
|
|
60
|
+
return create_panel(app)
|
|
61
|
+
|
|
62
|
+
with plugin_context(PLUGIN):
|
|
63
|
+
add("panels", AppPanel("Guide", create, area="right"), name="guide")
|
|
64
|
+
_registered = True
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def course_folders() -> list[Path]:
|
|
68
|
+
"""The course folders the plugin ships (each a course of case studies)."""
|
|
69
|
+
return sorted(p for p in COURSES.iterdir() if p.is_dir())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def load_courses() -> None:
|
|
73
|
+
"""The ``pymetrix.courses`` entry point: the plugin's case studies, as course material in the help."""
|
|
74
|
+
from pymetrix import help as pymetrix_help
|
|
75
|
+
|
|
76
|
+
for folder in course_folders():
|
|
77
|
+
pymetrix_help.load_course(folder)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def case_studies(session: object = None) -> list[CaseStudy]:
|
|
81
|
+
"""The case studies found: the plugin's own, those in the loaded courses (Help → Course material…, or a
|
|
82
|
+
``pymetrix.courses`` package) and those in the session's project courses. A Markdown note is a case study when it
|
|
83
|
+
has a ``pymetrix-step`` block."""
|
|
84
|
+
from pymetrix import help as pymetrix_help
|
|
85
|
+
|
|
86
|
+
folders = [*course_folders(), *(c.path for c in pymetrix_help.courses())]
|
|
87
|
+
folders += [Path(f) for f in getattr(session, "courses", []) or []]
|
|
88
|
+
seen: set[Path] = set()
|
|
89
|
+
found = []
|
|
90
|
+
for folder in folders:
|
|
91
|
+
folder = Path(folder).resolve()
|
|
92
|
+
if not folder.is_dir():
|
|
93
|
+
continue
|
|
94
|
+
for file in sorted(folder.rglob("*.md")):
|
|
95
|
+
file = file.resolve()
|
|
96
|
+
if file in seen or ".ipynb_checkpoints" in file.parts:
|
|
97
|
+
continue
|
|
98
|
+
seen.add(file)
|
|
99
|
+
try:
|
|
100
|
+
text = file.read_text(encoding="utf-8")
|
|
101
|
+
except OSError:
|
|
102
|
+
continue
|
|
103
|
+
if _STEP_FENCE.search(text):
|
|
104
|
+
found.append(parse(text, file))
|
|
105
|
+
return found
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
__all__ = ["PLUGIN", "COURSES", "CaseStudy", "CaseStudyError", "CaseStudyWarning", "Check", "CheckError", "IntroPage", "Step",
|
|
109
|
+
"build_command", "case_studies", "check_case_study", "course_folders", "load_courses", "parse", "parse_check", "read", "register"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0a1"
|
pymetrix_guide/app.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""The Guide panel in the desktop app: a case study one step at a time, through the app's own dialogs.
|
|
2
|
+
|
|
3
|
+
The panel docks on the right (View → Guide). It shows:
|
|
4
|
+
|
|
5
|
+
- a choice of the case studies in the loaded courses, the chosen one's summary, and its problems if a block could
|
|
6
|
+
not be read;
|
|
7
|
+
- if the case study starts from a demo project that is not open, an offer to open it;
|
|
8
|
+
- its introduction first, a page at a time (the ``##`` sections before the first step: an overview, the scenario);
|
|
9
|
+
- the stages of the workflow, as a strip with the current one in bold, when the case study names them;
|
|
10
|
+
- the step: its narrative, why it is done and what to look for, what will tick it, and progress
|
|
11
|
+
("Stage: Judgement — step 8 of 19 · 7 done");
|
|
12
|
+
- **Open…** (the step's dialog, filled in: the trainee runs it, changed or not), **Show me** (runs the step as it
|
|
13
|
+
is written), **Back**, **Next** (through the introduction, then the steps) and **Start over** (the introduction's
|
|
14
|
+
first page, and the demo again);
|
|
15
|
+
- every step, ticked when its check passes. Ticks follow the history: Undo takes one back, Redo gives it again.
|
|
16
|
+
|
|
17
|
+
It works the app only through the panel interface (``AppInterface``): the steps run as the app runs any step,
|
|
18
|
+
recorded, undoable and in the script, so the guide keeps no record of its own. Qt is imported only here.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from . import case_studies
|
|
26
|
+
from .casestudy import CaseStudy, CaseStudyError, Step, build_command
|
|
27
|
+
|
|
28
|
+
__all__ = ["GuidePanel", "create_panel", "intro_markdown", "stage_strip", "step_markdown"]
|
|
29
|
+
|
|
30
|
+
# the app's spacing tokens (pymetrix.ui.metrics: named sizes on a 4-pixel grid), as the sizes they have at Normal text:
|
|
31
|
+
# a plugin uses pymetrix's public surface only, and the app's metrics module is not part of it
|
|
32
|
+
_SIZES = {"none": 0, "tight": 4, "normal": 8}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _margins(layout: Any, left: str, top: str | None = None, right: str | None = None, bottom: str | None = None) -> None:
|
|
36
|
+
"""A layout's contents margins from token names, CSS-like (one for all four sides; four for left, top, right, bottom)."""
|
|
37
|
+
top = left if top is None else top
|
|
38
|
+
names = (left, top, left if right is None else right, top if bottom is None else bottom)
|
|
39
|
+
layout.setContentsMargins(*(_SIZES[n] for n in names))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _spacing(layout: Any, token: str) -> None:
|
|
43
|
+
layout.setSpacing(_SIZES[token])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def step_markdown(study: CaseStudy, index: int) -> str:
|
|
47
|
+
"""The Markdown the panel shows for step ``index`` (``len(steps)`` is the closing page)."""
|
|
48
|
+
if index >= len(study.steps):
|
|
49
|
+
return "## Finished\n\n" + (study.closing or "That is the whole case study.")
|
|
50
|
+
step = study.steps[index]
|
|
51
|
+
parts = [f"## {index + 1}. {step.title}", step.text]
|
|
52
|
+
if step.why:
|
|
53
|
+
parts.append(f"**Why this step.** {step.why}")
|
|
54
|
+
if step.look:
|
|
55
|
+
parts.append(f"**What to look for.** {step.look}")
|
|
56
|
+
return "\n\n".join(p for p in parts if p).rstrip()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def intro_markdown(study: CaseStudy, page: int) -> str:
|
|
60
|
+
"""The Markdown the panel shows for page ``page`` of the introduction."""
|
|
61
|
+
intro = study.intro[page]
|
|
62
|
+
return f"## {intro.title}\n\n{intro.text}".rstrip()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def stage_strip(study: CaseStudy, current: str = "", finished: bool = False) -> str:
|
|
66
|
+
"""The workflow's stages as rich text: the current one in bold, those still to come in grey ("" without stages).
|
|
67
|
+
On the introduction (no ``current``) and the finished page all are plain."""
|
|
68
|
+
import html
|
|
69
|
+
|
|
70
|
+
if not study.stages:
|
|
71
|
+
return ""
|
|
72
|
+
at = study.stages.index(current) if current in study.stages else (len(study.stages) if finished else -1)
|
|
73
|
+
out = []
|
|
74
|
+
for i, name in enumerate(study.stages):
|
|
75
|
+
text = html.escape(name).replace(" ", " ")
|
|
76
|
+
if i == at:
|
|
77
|
+
out.append(f"<b>{text}</b>")
|
|
78
|
+
elif 0 <= at < i:
|
|
79
|
+
out.append(f'<span style="color: #8a8a8a">{text}</span>')
|
|
80
|
+
else:
|
|
81
|
+
out.append(text)
|
|
82
|
+
return "Workflow: " + " › ".join(out)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _make_panel_class() -> type:
|
|
86
|
+
from PySide6 import QtCore, QtWidgets
|
|
87
|
+
|
|
88
|
+
Qt = QtCore.Qt
|
|
89
|
+
|
|
90
|
+
class GuidePanel(QtWidgets.QWidget):
|
|
91
|
+
"""The Guide: one case study, one step at a time."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, app: Any) -> None:
|
|
94
|
+
super().__init__()
|
|
95
|
+
self.app = app
|
|
96
|
+
self.studies: list[CaseStudy] = []
|
|
97
|
+
self.study: CaseStudy | None = None
|
|
98
|
+
self.index = 0 # the step (len(steps): the finished page)
|
|
99
|
+
self.page: int | None = None # the introduction's page shown, or None for a step
|
|
100
|
+
self._positions: dict[str, tuple[int | None, int]] = {}
|
|
101
|
+
self._courses_seen: tuple[str, ...] = ()
|
|
102
|
+
outer = QtWidgets.QVBoxLayout(self)
|
|
103
|
+
outer.setContentsMargins(0, 0, 0, 0)
|
|
104
|
+
outer.setSpacing(0)
|
|
105
|
+
# the case study's choice at the top and the step's buttons at the foot stay in view; what is between
|
|
106
|
+
# them (the step's text, its check, the list of steps) scrolls once the dock is smaller than its contents
|
|
107
|
+
top = QtWidgets.QHBoxLayout()
|
|
108
|
+
_margins(top, "normal", "normal", "normal", "none")
|
|
109
|
+
self.choice = QtWidgets.QComboBox(objectName="guide-choice")
|
|
110
|
+
self.choice.setToolTip("The case studies in the loaded course material (Help → Course material…)")
|
|
111
|
+
self.choice.setSizeAdjustPolicy(QtWidgets.QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
|
|
112
|
+
self.choice.setMinimumContentsLength(12) # a long title shortens: the reload button stays in view
|
|
113
|
+
self.choice.currentIndexChanged.connect(self._chosen)
|
|
114
|
+
rescan = QtWidgets.QToolButton(objectName="guide-rescan", text="↻")
|
|
115
|
+
rescan.setToolTip("Look again for case studies (after adding course material)")
|
|
116
|
+
rescan.setAccessibleName("Look again for case studies")
|
|
117
|
+
rescan.clicked.connect(self.reload_studies)
|
|
118
|
+
top.addWidget(self.choice, 1)
|
|
119
|
+
top.addWidget(rescan)
|
|
120
|
+
outer.addLayout(top)
|
|
121
|
+
self.scroll = QtWidgets.QScrollArea(objectName="guide-scroll", widgetResizable=True)
|
|
122
|
+
self.scroll.setFrameShape(QtWidgets.QFrame.Shape.NoFrame)
|
|
123
|
+
body = QtWidgets.QWidget(objectName="guide-body")
|
|
124
|
+
self.scroll.setWidget(body)
|
|
125
|
+
outer.addWidget(self.scroll, 1)
|
|
126
|
+
layout = QtWidgets.QVBoxLayout(body)
|
|
127
|
+
_margins(layout, "normal")
|
|
128
|
+
|
|
129
|
+
self.summary = QtWidgets.QLabel(objectName="guide-summary", wordWrap=True)
|
|
130
|
+
self.summary.setStyleSheet("font-style: italic")
|
|
131
|
+
layout.addWidget(self.summary)
|
|
132
|
+
|
|
133
|
+
self.problems = QtWidgets.QLabel(objectName="guide-problems", wordWrap=True)
|
|
134
|
+
self.problems.setStyleSheet("color: #b3261e")
|
|
135
|
+
layout.addWidget(self.problems)
|
|
136
|
+
|
|
137
|
+
self.start_bar = QtWidgets.QFrame(objectName="guide-start")
|
|
138
|
+
bar = QtWidgets.QHBoxLayout(self.start_bar)
|
|
139
|
+
bar.setContentsMargins(0, 0, 0, 0)
|
|
140
|
+
self.start_text = QtWidgets.QLabel(wordWrap=True)
|
|
141
|
+
self.demo_button = QtWidgets.QPushButton("Open the demo", objectName="guide-demo")
|
|
142
|
+
self.demo_button.clicked.connect(self.open_demo)
|
|
143
|
+
bar.addWidget(self.start_text, 1)
|
|
144
|
+
bar.addWidget(self.demo_button)
|
|
145
|
+
layout.addWidget(self.start_bar)
|
|
146
|
+
|
|
147
|
+
self.stages = QtWidgets.QLabel(objectName="guide-stages", wordWrap=True)
|
|
148
|
+
self.stages.setTextFormat(Qt.TextFormat.RichText)
|
|
149
|
+
self.stages.setToolTip("The stages of the workflow: where this step is in it")
|
|
150
|
+
layout.addWidget(self.stages)
|
|
151
|
+
self.progress = QtWidgets.QLabel(objectName="guide-progress", wordWrap=True)
|
|
152
|
+
layout.addWidget(self.progress)
|
|
153
|
+
self.text = QtWidgets.QTextBrowser(objectName="guide-text")
|
|
154
|
+
self.text.setOpenExternalLinks(True)
|
|
155
|
+
layout.addWidget(self.text, 3)
|
|
156
|
+
self.check_label = QtWidgets.QLabel(objectName="guide-check", wordWrap=True)
|
|
157
|
+
layout.addWidget(self.check_label)
|
|
158
|
+
|
|
159
|
+
row = QtWidgets.QHBoxLayout()
|
|
160
|
+
self.open_button = QtWidgets.QPushButton("Open…", objectName="guide-open")
|
|
161
|
+
self.open_button.setToolTip("Open the step's dialog filled in: run it as it is, or change it first")
|
|
162
|
+
self.show_button = QtWidgets.QPushButton("Show me", objectName="guide-show")
|
|
163
|
+
self.show_button.setToolTip("Run the step as the case study writes it (a recorded step, as any other)")
|
|
164
|
+
self.open_button.clicked.connect(self.open_step)
|
|
165
|
+
self.show_button.clicked.connect(self.show_me)
|
|
166
|
+
row.addWidget(self.open_button)
|
|
167
|
+
row.addWidget(self.show_button)
|
|
168
|
+
self.buttons = QtWidgets.QWidget(objectName="guide-buttons") # pinned under the scrolling part
|
|
169
|
+
pinned = QtWidgets.QVBoxLayout(self.buttons)
|
|
170
|
+
_margins(pinned, "normal", "tight", "normal", "normal")
|
|
171
|
+
_spacing(pinned, "tight")
|
|
172
|
+
pinned.addLayout(row)
|
|
173
|
+
nav = QtWidgets.QHBoxLayout()
|
|
174
|
+
self.back_button = QtWidgets.QPushButton("Back", objectName="guide-back")
|
|
175
|
+
self.next_button = QtWidgets.QPushButton("Next", objectName="guide-next")
|
|
176
|
+
self.restart_button = QtWidgets.QPushButton("Start over", objectName="guide-restart")
|
|
177
|
+
self.restart_button.setToolTip("Back to the introduction, and the case study's demo project as it first was")
|
|
178
|
+
self.back_button.clicked.connect(self.back)
|
|
179
|
+
self.next_button.clicked.connect(self.forward)
|
|
180
|
+
self.restart_button.clicked.connect(self.start_over)
|
|
181
|
+
for b in (self.back_button, self.next_button, self.restart_button):
|
|
182
|
+
nav.addWidget(b)
|
|
183
|
+
pinned.addLayout(nav)
|
|
184
|
+
self._nav, self._fold = nav, QtWidgets.QHBoxLayout() # Start over, on a row of its own when narrow
|
|
185
|
+
pinned.addLayout(self._fold)
|
|
186
|
+
|
|
187
|
+
self.steps = QtWidgets.QListWidget(objectName="guide-steps")
|
|
188
|
+
self.steps.itemClicked.connect(lambda item: self.go(self.steps.row(item)))
|
|
189
|
+
layout.addWidget(self.steps, 2)
|
|
190
|
+
# the buttons' strip keeps its height; a dock narrower than the buttons scrolls them sideways
|
|
191
|
+
self.button_strip = QtWidgets.QScrollArea(objectName="guide-button-strip", widgetResizable=True)
|
|
192
|
+
self.button_strip.setFrameShape(QtWidgets.QFrame.Shape.NoFrame)
|
|
193
|
+
self.button_strip.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
|
194
|
+
self.button_strip.setWidget(self.buttons)
|
|
195
|
+
outer.addWidget(self.button_strip)
|
|
196
|
+
self._fit_strip()
|
|
197
|
+
|
|
198
|
+
app.on_history_changed(self.refresh)
|
|
199
|
+
self.reload_studies()
|
|
200
|
+
|
|
201
|
+
def _fold_buttons(self, width: int) -> None:
|
|
202
|
+
"""Back, Next and Start over side by side where ``width`` has room for them, else Start over on a row of
|
|
203
|
+
its own under Back and Next: the buttons need less width (wider buttons, as with Windows' fonts and style,
|
|
204
|
+
no longer make a dock of ordinary width scroll them sideways)."""
|
|
205
|
+
margins = self.buttons.layout().contentsMargins()
|
|
206
|
+
row = (self.back_button, self.next_button, self.restart_button)
|
|
207
|
+
spacing = self._nav.spacing()
|
|
208
|
+
if spacing < 0: # the style spaces by the kind of widget (as on Windows)
|
|
209
|
+
button = QtWidgets.QSizePolicy.ControlType.PushButton
|
|
210
|
+
spacing = self.style().layoutSpacing(button, button, QtCore.Qt.Orientation.Horizontal)
|
|
211
|
+
three = sum(b.minimumSizeHint().width() for b in row) + 2 * max(spacing, 0) + margins.left() + margins.right()
|
|
212
|
+
fold = width < three
|
|
213
|
+
if fold and self._fold.indexOf(self.restart_button) < 0:
|
|
214
|
+
self._nav.removeWidget(self.restart_button)
|
|
215
|
+
self._fold.addWidget(self.restart_button)
|
|
216
|
+
elif not fold and self._nav.indexOf(self.restart_button) < 0:
|
|
217
|
+
self._fold.removeWidget(self.restart_button)
|
|
218
|
+
self._nav.addWidget(self.restart_button)
|
|
219
|
+
|
|
220
|
+
def _fit_strip(self) -> None:
|
|
221
|
+
"""The buttons' strip as tall as the buttons, and the sideways scroll bar when it shows."""
|
|
222
|
+
strip = self.button_strip
|
|
223
|
+
self._fold_buttons(self.width()) # the strip is as wide as the panel
|
|
224
|
+
self.buttons.layout().activate()
|
|
225
|
+
bar = strip.horizontalScrollBar()
|
|
226
|
+
needs_bar = self.buttons.minimumSizeHint().width() > strip.viewport().width() > 0
|
|
227
|
+
strip.setFixedHeight(self.buttons.sizeHint().height() + (bar.sizeHint().height() if needs_bar else 0))
|
|
228
|
+
|
|
229
|
+
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt's name
|
|
230
|
+
super().resizeEvent(event)
|
|
231
|
+
self._fit_strip()
|
|
232
|
+
|
|
233
|
+
# -- the case studies ------------------------------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
def _session(self) -> Any:
|
|
236
|
+
try:
|
|
237
|
+
return self.app.session
|
|
238
|
+
except Exception: # noqa: BLE001 - no session yet
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
def reload_studies(self) -> None:
|
|
242
|
+
current = self.study.path if self.study is not None else None
|
|
243
|
+
try:
|
|
244
|
+
self.studies = case_studies(self._session())
|
|
245
|
+
except Exception as exc: # noqa: BLE001 - a bad folder must not stop the panel
|
|
246
|
+
self.studies = []
|
|
247
|
+
self.app.status(f"Guide: could not read the case studies: {exc}")
|
|
248
|
+
self._courses_seen = tuple(getattr(self._session(), "courses", []) or [])
|
|
249
|
+
self.choice.blockSignals(True)
|
|
250
|
+
self.choice.clear()
|
|
251
|
+
for study in self.studies:
|
|
252
|
+
self.choice.addItem(study.title + (f" · {study.level}" if study.level else "")
|
|
253
|
+
+ (" (with problems)" if study.problems else ""))
|
|
254
|
+
if study.summary:
|
|
255
|
+
self.choice.setItemData(self.choice.count() - 1, study.summary, Qt.ItemDataRole.ToolTipRole)
|
|
256
|
+
self.choice.blockSignals(False)
|
|
257
|
+
if not self.studies:
|
|
258
|
+
self.choice.addItem("No case studies: add course material (Help → Course material…)")
|
|
259
|
+
self.choice.setEnabled(False)
|
|
260
|
+
self.study = None
|
|
261
|
+
else:
|
|
262
|
+
self.choice.setEnabled(True)
|
|
263
|
+
at = next((i for i, s in enumerate(self.studies) if s.path == current), 0)
|
|
264
|
+
self.choice.setCurrentIndex(at)
|
|
265
|
+
self.study = self.studies[at]
|
|
266
|
+
self._restore()
|
|
267
|
+
self.refresh()
|
|
268
|
+
|
|
269
|
+
def _start(self) -> tuple[int | None, int]:
|
|
270
|
+
return (0 if self.study is not None and self.study.intro else None), 0
|
|
271
|
+
|
|
272
|
+
def _restore(self) -> None:
|
|
273
|
+
self.page, self.index = self._positions.get(str(self.study.path), self._start())
|
|
274
|
+
if (self.page is not None and self.page >= len(self.study.intro)) or self.index > len(self.study.steps):
|
|
275
|
+
self.page, self.index = self._start() # the case study changed since
|
|
276
|
+
|
|
277
|
+
def _remember(self) -> None:
|
|
278
|
+
if self.study is not None:
|
|
279
|
+
self._positions[str(self.study.path)] = (self.page, self.index)
|
|
280
|
+
|
|
281
|
+
def choose(self, title: str) -> None:
|
|
282
|
+
"""Choose a case study by its title."""
|
|
283
|
+
at = next(i for i, s in enumerate(self.studies) if s.title == title)
|
|
284
|
+
self.choice.setCurrentIndex(at)
|
|
285
|
+
|
|
286
|
+
def _chosen(self, at: int) -> None:
|
|
287
|
+
if 0 <= at < len(self.studies):
|
|
288
|
+
self._remember()
|
|
289
|
+
self.study = self.studies[at]
|
|
290
|
+
self._restore()
|
|
291
|
+
self.refresh()
|
|
292
|
+
|
|
293
|
+
# -- the steps ---------------------------------------------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
def step(self) -> Step | None:
|
|
296
|
+
if self.study is None or self.page is not None or self.index >= len(self.study.steps):
|
|
297
|
+
return None
|
|
298
|
+
return self.study.steps[self.index]
|
|
299
|
+
|
|
300
|
+
def done(self) -> list[bool]:
|
|
301
|
+
"""Whether each step's check passes now (a step with no check never ticks itself)."""
|
|
302
|
+
s = self._session()
|
|
303
|
+
return [bool(st.check is not None and st.check.holds(s)) for st in (self.study.steps if self.study else ())]
|
|
304
|
+
|
|
305
|
+
def go(self, index: int) -> None:
|
|
306
|
+
"""Show step ``index`` (``len(steps)``: the finished page)."""
|
|
307
|
+
if self.study is None:
|
|
308
|
+
return
|
|
309
|
+
self.page = None
|
|
310
|
+
self.index = max(0, min(index, len(self.study.steps)))
|
|
311
|
+
self._remember()
|
|
312
|
+
self.refresh()
|
|
313
|
+
|
|
314
|
+
def go_intro(self, page: int = 0) -> None:
|
|
315
|
+
"""Show page ``page`` of the introduction (step 1 when there is none)."""
|
|
316
|
+
if self.study is None:
|
|
317
|
+
return
|
|
318
|
+
if not self.study.intro:
|
|
319
|
+
self.go(0)
|
|
320
|
+
return
|
|
321
|
+
self.page = max(0, min(page, len(self.study.intro) - 1))
|
|
322
|
+
self.index = 0
|
|
323
|
+
self._remember()
|
|
324
|
+
self.refresh()
|
|
325
|
+
|
|
326
|
+
def back(self) -> None:
|
|
327
|
+
if self.study is None:
|
|
328
|
+
return
|
|
329
|
+
if self.page is not None:
|
|
330
|
+
self.go_intro(self.page - 1)
|
|
331
|
+
elif self.index == 0 and self.study.intro:
|
|
332
|
+
self.go_intro(len(self.study.intro) - 1)
|
|
333
|
+
else:
|
|
334
|
+
self.go(self.index - 1)
|
|
335
|
+
|
|
336
|
+
def forward(self) -> None:
|
|
337
|
+
if self.study is None:
|
|
338
|
+
return
|
|
339
|
+
if self.page is not None and self.page + 1 < len(self.study.intro):
|
|
340
|
+
self.go_intro(self.page + 1)
|
|
341
|
+
elif self.page is not None:
|
|
342
|
+
self.go(0)
|
|
343
|
+
else:
|
|
344
|
+
self.go(self.index + 1)
|
|
345
|
+
|
|
346
|
+
def command(self) -> Any:
|
|
347
|
+
step = self.step()
|
|
348
|
+
return build_command(step.command, step.settings) if step is not None and step.command else None
|
|
349
|
+
|
|
350
|
+
def open_step(self) -> None:
|
|
351
|
+
try:
|
|
352
|
+
cmd = self.command()
|
|
353
|
+
except CaseStudyError as exc:
|
|
354
|
+
self.app.status(f"Guide: {exc}")
|
|
355
|
+
return
|
|
356
|
+
if cmd is not None:
|
|
357
|
+
self.app.open_dialog(type(cmd), cmd)
|
|
358
|
+
self.refresh()
|
|
359
|
+
|
|
360
|
+
def show_me(self) -> None:
|
|
361
|
+
try:
|
|
362
|
+
cmd = self.command()
|
|
363
|
+
if cmd is None:
|
|
364
|
+
return
|
|
365
|
+
self.app.run(cmd)
|
|
366
|
+
except Exception as exc: # noqa: BLE001 - the step's error is shown, as the app shows it
|
|
367
|
+
self.app.status(f"Guide: the step did not run: {exc}")
|
|
368
|
+
self.check_label.setText(f"The step did not run: {exc}")
|
|
369
|
+
return
|
|
370
|
+
self.refresh()
|
|
371
|
+
|
|
372
|
+
# -- the demo it starts from -----------------------------------------------------------------------------------
|
|
373
|
+
|
|
374
|
+
def needs_demo(self) -> bool:
|
|
375
|
+
return bool(self.study and self.study.demo and getattr(self._session(), "demo", None) != self.study.demo)
|
|
376
|
+
|
|
377
|
+
def open_demo(self) -> None:
|
|
378
|
+
"""Open the case study's demo project (as it first was), through the app; the app asks to save the work."""
|
|
379
|
+
if self.study is None or not self.study.demo:
|
|
380
|
+
return
|
|
381
|
+
from pymetrix.errors import NotSupportedError
|
|
382
|
+
|
|
383
|
+
opener = getattr(self.app, "open_demo", None) # extension API 1.7; an app before it has none
|
|
384
|
+
try:
|
|
385
|
+
if not callable(opener):
|
|
386
|
+
raise NotSupportedError("open_demo")
|
|
387
|
+
opener(self.study.demo) # the app asks to save unsaved work; the trainee may cancel
|
|
388
|
+
except NotSupportedError: # say where it is in the menus instead
|
|
389
|
+
again = getattr(self._session(), "demo", None) == self.study.demo
|
|
390
|
+
self.app.status(f"Guide: open the demo with File → {'Reload demo project' if again else 'Open demo project…'} "
|
|
391
|
+
f"({self.study.demo})")
|
|
392
|
+
except Exception as exc: # noqa: BLE001 - e.g. a demo this pymetrix does not have: said, not raised
|
|
393
|
+
self.app.status(f"Guide: the demo {self.study.demo} did not open: {exc}")
|
|
394
|
+
self.refresh()
|
|
395
|
+
|
|
396
|
+
def start_over(self) -> None:
|
|
397
|
+
self.go_intro(0)
|
|
398
|
+
if self.study is not None and self.study.demo:
|
|
399
|
+
self.open_demo()
|
|
400
|
+
else:
|
|
401
|
+
self.app.status("Guide: back to the start (File → New session starts from an empty workspace)")
|
|
402
|
+
|
|
403
|
+
# -- showing it ------------------------------------------------------------------------------------------------
|
|
404
|
+
|
|
405
|
+
def refresh(self) -> None:
|
|
406
|
+
import shiboken6
|
|
407
|
+
|
|
408
|
+
if not (shiboken6.isValid(self) and shiboken6.isValid(self.steps)):
|
|
409
|
+
return # the panel, or its window, is gone (an app older than 1.7 may still call it): nothing to show
|
|
410
|
+
if tuple(getattr(self._session(), "courses", []) or []) != self._courses_seen:
|
|
411
|
+
self.reload_studies() # another project, with its own course material
|
|
412
|
+
return
|
|
413
|
+
study = self.study
|
|
414
|
+
ticks = self.done()
|
|
415
|
+
self.summary.setVisible(bool(study and study.summary))
|
|
416
|
+
self.summary.setText(study.summary if study else "")
|
|
417
|
+
self.problems.setVisible(bool(study and study.problems))
|
|
418
|
+
if study and study.problems:
|
|
419
|
+
self.problems.setText("Some of this case study could not be read:\n" + "\n".join(study.problems))
|
|
420
|
+
self.start_bar.setVisible(self.needs_demo())
|
|
421
|
+
if study is not None and study.demo:
|
|
422
|
+
self.start_text.setText(f"This case study starts from the demo project <b>{study.demo}</b>.")
|
|
423
|
+
self.steps.clear()
|
|
424
|
+
for i, st in enumerate(study.steps if study else ()):
|
|
425
|
+
item = QtWidgets.QListWidgetItem(f"{i + 1}. {st.title}")
|
|
426
|
+
if st.stage:
|
|
427
|
+
item.setToolTip(f"Stage: {st.stage}")
|
|
428
|
+
item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)
|
|
429
|
+
item.setCheckState(Qt.CheckState.Checked if ticks[i] else Qt.CheckState.Unchecked)
|
|
430
|
+
self.steps.addItem(item)
|
|
431
|
+
if study is None:
|
|
432
|
+
self.stages.setVisible(False)
|
|
433
|
+
self.progress.setText("")
|
|
434
|
+
self.text.setMarkdown("")
|
|
435
|
+
self.check_label.setText("")
|
|
436
|
+
for b in (self.open_button, self.show_button, self.back_button, self.next_button, self.restart_button):
|
|
437
|
+
b.setEnabled(False)
|
|
438
|
+
return
|
|
439
|
+
n = len(study.steps)
|
|
440
|
+
if study.path is not None:
|
|
441
|
+
self.text.document().setBaseUrl(QtCore.QUrl.fromLocalFile(str(study.path.parent) + "/"))
|
|
442
|
+
step = self.step()
|
|
443
|
+
if self.page is not None:
|
|
444
|
+
self.text.setMarkdown(intro_markdown(study, self.page))
|
|
445
|
+
m = len(study.intro)
|
|
446
|
+
self.progress.setText(f"Introduction, page {self.page + 1} of {m} · then {n} steps · {sum(ticks)} done")
|
|
447
|
+
self.check_label.setText(f"Next: step 1, {study.steps[0].title}." if n else "")
|
|
448
|
+
self.steps.setCurrentRow(-1)
|
|
449
|
+
elif step is None:
|
|
450
|
+
self.text.setMarkdown(step_markdown(study, self.index))
|
|
451
|
+
self.progress.setText(f"{study.title}: finished · {sum(ticks)} of {n} steps done")
|
|
452
|
+
self.check_label.setText("")
|
|
453
|
+
else:
|
|
454
|
+
self.text.setMarkdown(step_markdown(study, self.index))
|
|
455
|
+
where = f"step {self.index + 1} of {n} · {sum(ticks)} done"
|
|
456
|
+
self.progress.setText(f"Stage: {step.stage} — {where}" if step.stage else where[0].upper() + where[1:])
|
|
457
|
+
self.steps.setCurrentRow(self.index)
|
|
458
|
+
if step.check is None:
|
|
459
|
+
self.check_label.setText("No check for this step: press Next when you are ready.")
|
|
460
|
+
elif ticks[self.index]:
|
|
461
|
+
self.check_label.setText(f"✓ Done: {step.check.describe()}.")
|
|
462
|
+
else:
|
|
463
|
+
self.check_label.setText(f"To do: {step.check.describe()}.")
|
|
464
|
+
strip = stage_strip(study, step.stage if step is not None else "", finished=self.page is None and step is None)
|
|
465
|
+
self.stages.setVisible(bool(strip))
|
|
466
|
+
self.stages.setText(strip)
|
|
467
|
+
has_command = step is not None and bool(step.command)
|
|
468
|
+
self.open_button.setEnabled(has_command)
|
|
469
|
+
self.show_button.setEnabled(has_command)
|
|
470
|
+
self.back_button.setEnabled(bool(self.page) if self.page is not None else (self.index > 0 or bool(study.intro)))
|
|
471
|
+
self.next_button.setEnabled(self.page is not None or self.index < n)
|
|
472
|
+
self.restart_button.setEnabled(True)
|
|
473
|
+
|
|
474
|
+
return GuidePanel
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
_PANEL: type | None = None
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def create_panel(app: Any) -> Any:
|
|
481
|
+
"""The Guide panel (a QWidget) for the app's ``AppInterface``."""
|
|
482
|
+
global _PANEL
|
|
483
|
+
if _PANEL is None:
|
|
484
|
+
_PANEL = _make_panel_class()
|
|
485
|
+
return _PANEL(app)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def __getattr__(name: str) -> Any:
|
|
489
|
+
if name == "GuidePanel":
|
|
490
|
+
global _PANEL
|
|
491
|
+
if _PANEL is None:
|
|
492
|
+
_PANEL = _make_panel_class()
|
|
493
|
+
return _PANEL
|
|
494
|
+
raise AttributeError(name)
|