@flipova/foundation 1.14.0 → 2.0.5
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.
- package/CHANGELOG.md +181 -0
- package/README.md +53 -178
- package/components/ui/accordion/ANIMATION_CUSTOMIZATION.md +162 -0
- package/components/ui/accordion/AccordionAnimatedHeight.tsx +56 -0
- package/components/ui/accordion/AccordionAnimatedIcon.tsx +41 -0
- package/components/ui/accordion/AnimatedHeight.tsx +56 -0
- package/components/ui/accordion/AnimatedIcon.tsx +41 -0
- package/components/ui/accordion/MIGRATION_SUMMARY.md +250 -0
- package/components/ui/accordion/USAGE_EXAMPLE.tsx +179 -0
- package/components/ui/accordion/animation-config.ts +32 -0
- package/components/ui/accordion/index.tsx +253 -0
- package/components/ui/actionsheet/index.tsx +511 -0
- package/components/ui/alert/index.tsx +158 -0
- package/components/ui/alert-dialog/index.tsx +254 -0
- package/components/ui/avatar/index.tsx +139 -0
- package/components/ui/badge/index.tsx +163 -0
- package/components/ui/bottomsheet/index.tsx +477 -0
- package/components/ui/box/index.tsx +19 -0
- package/components/ui/box/index.web.tsx +19 -0
- package/components/ui/box/styles.tsx +10 -0
- package/components/ui/button/index.tsx +264 -0
- package/components/ui/calendar/creator.tsx +366 -0
- package/components/ui/calendar/index.tsx +462 -0
- package/components/ui/calendar/styles.tsx +140 -0
- package/components/ui/card/index.tsx +23 -0
- package/components/ui/card/index.web.tsx +26 -0
- package/components/ui/card/styles.tsx +16 -0
- package/components/ui/center/index.tsx +22 -0
- package/components/ui/center/index.web.tsx +20 -0
- package/components/ui/center/styles.tsx +8 -0
- package/components/ui/checkbox/index.tsx +184 -0
- package/components/ui/date-time-picker/creator.tsx +109 -0
- package/components/ui/date-time-picker/index.tsx +585 -0
- package/components/ui/date-time-picker/index.web.tsx +217 -0
- package/components/ui/date-time-picker/styles.tsx +56 -0
- package/components/ui/divider/index.tsx +40 -0
- package/components/ui/drawer/index.tsx +362 -0
- package/components/ui/fab/index.tsx +215 -0
- package/components/ui/flat-list/index.tsx +21 -0
- package/components/ui/form-control/index.tsx +352 -0
- package/components/ui/gluestack-ui-provider/config.ts +72 -0
- package/components/ui/gluestack-ui-provider/index.tsx +47 -0
- package/components/ui/gluestack-ui-provider/index.web.tsx +96 -0
- package/components/ui/gluestack-ui-provider/script.ts +19 -0
- package/components/ui/gluestack-ui-provider/tokens.d.ts +17 -0
- package/components/ui/gluestack-ui-provider/tokens.js +188 -0
- package/components/ui/gluestack-ui-provider/useGluestackColors.ts +82 -0
- package/components/ui/grid/index.tsx +283 -0
- package/components/ui/grid/index.web.tsx +66 -0
- package/components/ui/grid/styles.tsx +15 -0
- package/components/ui/heading/index.tsx +220 -0
- package/components/ui/heading/index.web.tsx +202 -0
- package/components/ui/heading/styles.tsx +43 -0
- package/components/ui/hstack/index.tsx +27 -0
- package/components/ui/hstack/index.web.tsx +26 -0
- package/components/ui/hstack/styles.tsx +25 -0
- package/components/ui/icon/index.tsx +1588 -0
- package/components/ui/icon/index.web.tsx +1573 -0
- package/components/ui/image/index.tsx +48 -0
- package/components/ui/image-background/index.tsx +25 -0
- package/components/ui/image-viewer/index.tsx +743 -0
- package/components/ui/image-viewer/index.web.tsx +302 -0
- package/components/ui/index.ts +58 -0
- package/components/ui/input/index.tsx +125 -0
- package/components/ui/input-accessory-view/index.tsx +2 -0
- package/components/ui/keyboard-avoiding-view/index.tsx +2 -0
- package/components/ui/link/index.tsx +102 -0
- package/components/ui/liquid-glass/index.tsx +74 -0
- package/components/ui/menu/index.tsx +186 -0
- package/components/ui/modal/index.tsx +237 -0
- package/components/ui/popover/index.tsx +272 -0
- package/components/ui/portal/index.tsx +17 -0
- package/components/ui/pressable/index.tsx +39 -0
- package/components/ui/progress/index.tsx +83 -0
- package/components/ui/radio/index.tsx +217 -0
- package/components/ui/refresh-control/index.tsx +2 -0
- package/components/ui/safe-area-view/index.tsx +2 -0
- package/components/ui/scroll-view/index.tsx +2 -0
- package/components/ui/section-list/index.tsx +2 -0
- package/components/ui/select/index.tsx +277 -0
- package/components/ui/select/select-actionsheet.tsx +562 -0
- package/components/ui/skeleton/index.tsx +105 -0
- package/components/ui/skeleton/index.web.tsx +103 -0
- package/components/ui/skeleton/styles.tsx +35 -0
- package/components/ui/slider/index.tsx +181 -0
- package/components/ui/spinner/index.tsx +40 -0
- package/components/ui/status-bar/index.tsx +2 -0
- package/components/ui/switch/index.tsx +41 -0
- package/components/ui/table/index.tsx +210 -0
- package/components/ui/table/index.web.tsx +157 -0
- package/components/ui/table/styles.tsx +44 -0
- package/components/ui/tabs/TabsAnimatedIndicator.tsx +160 -0
- package/components/ui/tabs/animation-config.ts +3 -0
- package/components/ui/tabs/creator.tsx +206 -0
- package/components/ui/tabs/index.tsx +484 -0
- package/components/ui/text/index.tsx +48 -0
- package/components/ui/text/index.web.tsx +45 -0
- package/components/ui/text/styles.tsx +47 -0
- package/components/ui/textarea/index.tsx +94 -0
- package/components/ui/toast/index.tsx +252 -0
- package/components/ui/tooltip/index.tsx +131 -0
- package/components/ui/view/index.tsx +2 -0
- package/components/ui/virtualized-list/index.tsx +2 -0
- package/components/ui/vstack/index.tsx +28 -0
- package/components/ui/vstack/index.web.tsx +27 -0
- package/components/ui/vstack/styles.tsx +25 -0
- package/design/canonical.index.txt +53 -0
- package/design/documentation.xml +519 -0
- package/design/manifest.xml +90 -0
- package/design/schema.xsd +639 -0
- package/design/themes.xml +204 -0
- package/design/tokens.xml +510 -0
- package/design/tools/design.js +165 -0
- package/design/tools/npm.js +65 -0
- package/design/tools/requirements.txt +35 -0
- package/design/tools/sources/.checker/__init__.py +81 -0
- package/design/tools/sources/.checker/checks.py +198 -0
- package/design/tools/sources/.checker/cli.py +154 -0
- package/design/tools/sources/.checker/io.py +242 -0
- package/design/tools/sources/.checker/model.py +144 -0
- package/design/tools/sources/.checker/registry.py +115 -0
- package/design/tools/sources/.checker/report.py +21 -0
- package/design/tools/sources/.docgen/__init__.py +45 -0
- package/design/tools/sources/.docgen/cli.py +101 -0
- package/design/tools/sources/.docgen/model.py +147 -0
- package/design/tools/sources/.docgen/reference.py +97 -0
- package/design/tools/sources/.docgen/site.py +145 -0
- package/design/tools/sources/.docgen/xsddoc.py +329 -0
- package/design/tools/sources/.generate/__init__.py +35 -0
- package/design/tools/sources/.generate/cli.py +76 -0
- package/design/tools/sources/.generate/common.py +33 -0
- package/design/tools/sources/.generate/config.py +119 -0
- package/design/tools/sources/.generate/model.py +51 -0
- package/design/tools/sources/.generate/tokens.py +141 -0
- package/design/tools/sources/.linter/__init__.py +9 -0
- package/design/tools/sources/.linter/cli.py +44 -0
- package/design/tools/sources/.linter/discovery.py +30 -0
- package/design/tools/sources/.linter/errors.py +45 -0
- package/design/tools/sources/.linter/linter.py +68 -0
- package/design/tools/sources/.xmleditor/__init__.py +74 -0
- package/design/tools/sources/.xmleditor/blocks.py +185 -0
- package/design/tools/sources/.xmleditor/cli.py +141 -0
- package/design/tools/sources/.xmleditor/editor.py +906 -0
- package/design/tools/sources/.xmleditor/model.py +708 -0
- package/design/tools/sources/.xmleditor/widgets.py +1832 -0
- package/design/tools/sources/.xmleditor/xsdmodel.py +753 -0
- package/design/tools/sources/checker.py +55 -0
- package/design/tools/sources/docgen.py +66 -0
- package/design/tools/sources/generate.py +48 -0
- package/design/tools/sources/linter.py +54 -0
- package/design/tools/sources/ruff.toml +12 -0
- package/design/tools/sources/xmleditor.py +62 -0
- package/design/tools/unix/_venv_python.sh +16 -0
- package/design/tools/unix/check.sh +13 -0
- package/design/tools/unix/doc.sh +14 -0
- package/design/tools/unix/gen.sh +14 -0
- package/design/tools/unix/lint.sh +10 -0
- package/design/tools/unix/run.sh +20 -0
- package/design/tools/unix/verify.sh +12 -0
- package/design/tools/unix/xmledit.sh +12 -0
- package/design/tools/windows/check.cmd +12 -0
- package/design/tools/windows/doc.cmd +12 -0
- package/design/tools/windows/gen.cmd +11 -0
- package/design/tools/windows/lint.cmd +9 -0
- package/design/tools/windows/run.cmd +26 -0
- package/design/tools/windows/verify.cmd +10 -0
- package/design/tools/windows/xmledit.cmd +10 -0
- package/dist/chunk-LV4UIEQN.js +9730 -0
- package/dist/chunk-LV4UIEQN.js.map +1 -0
- package/dist/chunk-WNVU3BM2.mjs +9401 -0
- package/dist/chunk-WNVU3BM2.mjs.map +1 -0
- package/dist/index.d.mts +40 -10
- package/dist/index.d.ts +40 -10
- package/dist/index.js +726 -414
- package/dist/index.mjs +1 -5
- package/dist/ui/index.d.mts +6931 -3070
- package/dist/ui/index.d.ts +6931 -3070
- package/dist/ui/index.js +779 -352
- package/dist/ui/index.mjs +1 -2
- package/package.json +66 -149
- package/dist/chunk-2XORADW6.js +0 -24552
- package/dist/chunk-2XORADW6.js.map +0 -1
- package/dist/chunk-52BHHF5M.js +0 -46
- package/dist/chunk-52BHHF5M.js.map +0 -1
- package/dist/chunk-5647JY7Z.mjs +0 -100
- package/dist/chunk-5647JY7Z.mjs.map +0 -1
- package/dist/chunk-5N5HC4ZA.mjs +0 -3
- package/dist/chunk-5N5HC4ZA.mjs.map +0 -1
- package/dist/chunk-7QFZMGL6.js +0 -8583
- package/dist/chunk-7QFZMGL6.js.map +0 -1
- package/dist/chunk-ASZEP37D.js +0 -423
- package/dist/chunk-ASZEP37D.js.map +0 -1
- package/dist/chunk-BH5SU2JQ.mjs +0 -8282
- package/dist/chunk-BH5SU2JQ.mjs.map +0 -1
- package/dist/chunk-BO65GO53.mjs +0 -422
- package/dist/chunk-BO65GO53.mjs.map +0 -1
- package/dist/chunk-BSVXX52E.mjs +0 -413
- package/dist/chunk-BSVXX52E.mjs.map +0 -1
- package/dist/chunk-DNV5UBNF.mjs +0 -3
- package/dist/chunk-DNV5UBNF.mjs.map +0 -1
- package/dist/chunk-EDTAMUO2.js +0 -8310
- package/dist/chunk-EDTAMUO2.js.map +0 -1
- package/dist/chunk-IJTI6EX4.js +0 -4
- package/dist/chunk-IJTI6EX4.js.map +0 -1
- package/dist/chunk-M3YLASM2.js +0 -428
- package/dist/chunk-M3YLASM2.js.map +0 -1
- package/dist/chunk-OXKOGLXE.js +0 -4
- package/dist/chunk-OXKOGLXE.js.map +0 -1
- package/dist/chunk-RQXQK3ZO.mjs +0 -8486
- package/dist/chunk-RQXQK3ZO.mjs.map +0 -1
- package/dist/chunk-SR25V4EA.mjs +0 -40
- package/dist/chunk-SR25V4EA.mjs.map +0 -1
- package/dist/chunk-UB34WFEQ.js +0 -106
- package/dist/chunk-UB34WFEQ.js.map +0 -1
- package/dist/chunk-ZBRWXKDF.mjs +0 -24431
- package/dist/chunk-ZBRWXKDF.mjs.map +0 -1
- package/dist/cli/ds.d.mts +0 -1
- package/dist/cli/ds.d.ts +0 -1
- package/dist/cli/ds.js +0 -602
- package/dist/cli/ds.js.map +0 -1
- package/dist/cli/ds.mjs +0 -579
- package/dist/cli/ds.mjs.map +0 -1
- package/dist/cli/flipova.d.mts +0 -1
- package/dist/cli/flipova.d.ts +0 -1
- package/dist/cli/flipova.js +0 -161
- package/dist/cli/flipova.js.map +0 -1
- package/dist/cli/flipova.mjs +0 -154
- package/dist/cli/flipova.mjs.map +0 -1
- package/dist/config/index.d.mts +0 -123
- package/dist/config/index.d.ts +0 -123
- package/dist/config/index.js +0 -28
- package/dist/config/index.js.map +0 -1
- package/dist/config/index.mjs +0 -3
- package/dist/config/index.mjs.map +0 -1
- package/dist/createTheme-DQeX3s0I.d.mts +0 -78
- package/dist/createTheme-Y4jfz4-u.d.ts +0 -78
- package/dist/index-CuaJA3gM.d.mts +0 -78
- package/dist/index-CuaJA3gM.d.ts +0 -78
- package/dist/registry/index.d.mts +0 -10160
- package/dist/registry/index.d.ts +0 -10160
- package/dist/registry/index.js +0 -392
- package/dist/registry/index.js.map +0 -1
- package/dist/registry/index.mjs +0 -3
- package/dist/registry/index.mjs.map +0 -1
- package/dist/theme/index.d.mts +0 -35
- package/dist/theme/index.d.ts +0 -35
- package/dist/theme/index.js +0 -28
- package/dist/theme/index.js.map +0 -1
- package/dist/theme/index.mjs +0 -3
- package/dist/theme/index.mjs.map +0 -1
- package/dist/tokens/index.d.mts +0 -423
- package/dist/tokens/index.d.ts +0 -423
- package/dist/tokens/index.js +0 -44
- package/dist/tokens/index.js.map +0 -1
- package/dist/tokens/index.mjs +0 -3
- package/dist/tokens/index.mjs.map +0 -1
- package/dist/types/index.d.mts +0 -202
- package/dist/types/index.d.ts +0 -202
- package/dist/types/index.js +0 -4
- package/dist/types/index.js.map +0 -1
- package/dist/types/index.mjs +0 -3
- package/dist/types/index.mjs.map +0 -1
- package/dist/web/index.d.mts +0 -316
- package/dist/web/index.d.ts +0 -316
- package/dist/web/index.js +0 -1500
- package/dist/web/index.js.map +0 -1
- package/dist/web/index.mjs +0 -1396
- package/dist/web/index.mjs.map +0 -1
|
@@ -0,0 +1,1832 @@
|
|
|
1
|
+
"""Tk widgets for the visual XML editor.
|
|
2
|
+
|
|
3
|
+
All widgets are driven by ``BlockSpec``/``ParticleSpec`` objects: the palette
|
|
4
|
+
lists what the schema allows, the tree renders the document as nested blocks,
|
|
5
|
+
the inspector renders typed editors per attribute and the diagram draws the
|
|
6
|
+
same blocks as a foldable, colour-coded graph. Nothing here hardcodes an
|
|
7
|
+
element or attribute name.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
import tkinter as tk
|
|
15
|
+
import tkinter.font as tkfont
|
|
16
|
+
from collections import OrderedDict
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from tkinter import ttk
|
|
20
|
+
from typing import Callable
|
|
21
|
+
|
|
22
|
+
from .blocks import PaletteEntry, describe
|
|
23
|
+
from .model import DocumentModel, Issue
|
|
24
|
+
from .xsdmodel import BlockSpec, localname
|
|
25
|
+
|
|
26
|
+
# ---------------------------------------------------------------------------
|
|
27
|
+
# Shared look & feel
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
# kind -> (accent colour, tint colour, human label) — Apple-flavoured palette
|
|
31
|
+
KIND_STYLES = {
|
|
32
|
+
"root": ("#5e5ce6", "#eeedff", "Root"),
|
|
33
|
+
"container": ("#0071e3", "#eaf3ff", "Container"),
|
|
34
|
+
"value": ("#248a3d", "#e9f8ee", "Value"),
|
|
35
|
+
"text": ("#b25e00", "#fff4e5", "Text"),
|
|
36
|
+
"empty": ("#8e8e93", "#f2f2f7", "Empty"),
|
|
37
|
+
"freeform": ("#d6336c", "#fdeef4", "Free key"),
|
|
38
|
+
"unknown": ("#8e8e93", "#f0f0f4", "Not in schema"),
|
|
39
|
+
}
|
|
40
|
+
KIND_COLOURS = {kind: style[1] for kind, style in KIND_STYLES.items()}
|
|
41
|
+
KIND_GLYPHS = {
|
|
42
|
+
"root": "◆", "container": "▣", "value": "●", "text": "¶",
|
|
43
|
+
"empty": "○", "freeform": "✎", "unknown": "?",
|
|
44
|
+
}
|
|
45
|
+
ISSUE_MARKS = {"error": "✖", "warning": "⚠"}
|
|
46
|
+
ISSUE_COLOURS = {"error": "#ff3b30", "warning": "#ff9500"} # graphics
|
|
47
|
+
ISSUE_TEXT = {"error": "#d70015", "warning": "#b25e00"} # text
|
|
48
|
+
|
|
49
|
+
BG = "#f5f5f7"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def kind_of(block: BlockSpec | None) -> str:
|
|
53
|
+
"""Visual category of a block (drives colours and glyphs everywhere)."""
|
|
54
|
+
if block is None:
|
|
55
|
+
return "unknown"
|
|
56
|
+
if block.is_root:
|
|
57
|
+
return "root"
|
|
58
|
+
if block.type_name == "xs:any":
|
|
59
|
+
return "freeform"
|
|
60
|
+
return block.kind if block.kind in KIND_STYLES else "container"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def apply_theme(root: tk.Misc) -> None:
|
|
64
|
+
"""One consistent, calm ttk theme for the whole editor."""
|
|
65
|
+
style = ttk.Style(root)
|
|
66
|
+
if "clam" in style.theme_names():
|
|
67
|
+
style.theme_use("clam")
|
|
68
|
+
preferred = {"win32": "Segoe UI", "darwin": "SF Pro Text"}.get(sys.platform)
|
|
69
|
+
for name in ("TkDefaultFont", "TkTextFont", "TkMenuFont"):
|
|
70
|
+
try:
|
|
71
|
+
tkfont.nametofont(name).configure(
|
|
72
|
+
**({"family": preferred} if preferred else {}), size=10)
|
|
73
|
+
except tk.TclError:
|
|
74
|
+
pass
|
|
75
|
+
family = preferred or tkfont.nametofont("TkDefaultFont").actual("family")
|
|
76
|
+
try:
|
|
77
|
+
root.configure(background=BG)
|
|
78
|
+
except tk.TclError:
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
# -- surfaces --------------------------------------------------------
|
|
82
|
+
style.configure("TFrame", background=BG)
|
|
83
|
+
style.configure("TLabel", background=BG)
|
|
84
|
+
style.configure("TCheckbutton", background=BG)
|
|
85
|
+
style.configure("TLabelframe", background=BG, bordercolor="#e5e5ea")
|
|
86
|
+
style.configure("TLabelframe.Label", background=BG, foreground="#1d1d1f",
|
|
87
|
+
font=(family, 10, "bold"))
|
|
88
|
+
style.configure("TPanedwindow", background=BG)
|
|
89
|
+
style.configure("TSeparator", background="#e5e5ea")
|
|
90
|
+
|
|
91
|
+
# -- notebook: flat, VSCode-like tabs ---------------------------------
|
|
92
|
+
style.configure("TNotebook", background=BG, borderwidth=0, tabmargins=(0, 6, 0, 0))
|
|
93
|
+
style.configure("TNotebook.Tab", padding=(16, 7), background=BG,
|
|
94
|
+
foreground="#6e6e73")
|
|
95
|
+
style.map("TNotebook.Tab",
|
|
96
|
+
background=[("selected", "#ffffff"), ("active", "#ececf0")],
|
|
97
|
+
foreground=[("selected", "#0071e3"), ("active", "#1d1d1f")])
|
|
98
|
+
|
|
99
|
+
# -- lists ------------------------------------------------------------
|
|
100
|
+
style.configure("Treeview", rowheight=26, background="#ffffff",
|
|
101
|
+
fieldbackground="#ffffff", borderwidth=0)
|
|
102
|
+
style.map("Treeview",
|
|
103
|
+
background=[("selected", "#0071e3")],
|
|
104
|
+
foreground=[("selected", "#ffffff")])
|
|
105
|
+
style.configure("Treeview.Heading", padding=(8, 6), background="#f0f0f4",
|
|
106
|
+
foreground="#1d1d1f", font=(family, 10, "bold"),
|
|
107
|
+
relief="flat")
|
|
108
|
+
style.map("Treeview.Heading", background=[("active", "#e9e9ee")])
|
|
109
|
+
|
|
110
|
+
# -- controls: flat white buttons, accent primary, focus ring ---------
|
|
111
|
+
try:
|
|
112
|
+
style.configure("TButton", padding=(12, 6), background="#ffffff",
|
|
113
|
+
foreground="#1d1d1f", bordercolor="#d2d2d7",
|
|
114
|
+
relief="flat", focusthickness=1, focuscolor="#0071e3")
|
|
115
|
+
style.map("TButton",
|
|
116
|
+
background=[("active", "#f0f0f5"), ("pressed", "#e5e5ea"),
|
|
117
|
+
("disabled", "#f5f5f7")],
|
|
118
|
+
foreground=[("disabled", "#aeaeb2")])
|
|
119
|
+
style.configure("Toolbar.TButton", padding=(12, 6), background="#ffffff",
|
|
120
|
+
foreground="#1d1d1f", bordercolor="#d2d2d7",
|
|
121
|
+
relief="flat", focusthickness=1, focuscolor="#0071e3")
|
|
122
|
+
style.map("Toolbar.TButton",
|
|
123
|
+
background=[("active", "#f0f0f5"), ("pressed", "#e5e5ea"),
|
|
124
|
+
("disabled", "#f5f5f7")],
|
|
125
|
+
foreground=[("disabled", "#aeaeb2")])
|
|
126
|
+
style.configure("Accent.TButton", padding=(14, 6), background="#0071e3",
|
|
127
|
+
foreground="#ffffff", bordercolor="#0071e3",
|
|
128
|
+
relief="flat", focusthickness=1, focuscolor="#0068d0")
|
|
129
|
+
style.map("Accent.TButton",
|
|
130
|
+
background=[("active", "#0077ed"), ("pressed", "#0068d0"),
|
|
131
|
+
("disabled", "#a6c8f0")],
|
|
132
|
+
foreground=[("disabled", "#ffffff")])
|
|
133
|
+
style.configure("TEntry", fieldbackground="#ffffff",
|
|
134
|
+
bordercolor="#d2d2d7", lightcolor="#0071e3", padding=6,
|
|
135
|
+
relief="flat", focusthickness=1, focuscolor="#0071e3")
|
|
136
|
+
style.configure("TCombobox", fieldbackground="#ffffff",
|
|
137
|
+
bordercolor="#d2d2d7", lightcolor="#0071e3", padding=5,
|
|
138
|
+
arrowsize=11, relief="flat", focusthickness=1,
|
|
139
|
+
focuscolor="#0071e3")
|
|
140
|
+
style.map("TCombobox",
|
|
141
|
+
fieldbackground=[("readonly", "#ffffff")],
|
|
142
|
+
foreground=[("readonly", "#1d1d1f")])
|
|
143
|
+
except tk.TclError:
|
|
144
|
+
# toolkits lacking these clam options keep the simpler flat look
|
|
145
|
+
style.configure("TButton", padding=(12, 6), background="#ffffff",
|
|
146
|
+
foreground="#1d1d1f")
|
|
147
|
+
style.map("TButton", background=[("active", "#f0f0f5"),
|
|
148
|
+
("disabled", "#f5f5f7")])
|
|
149
|
+
style.configure("Accent.TButton", padding=(14, 6), background="#0071e3",
|
|
150
|
+
foreground="#ffffff")
|
|
151
|
+
style.map("Accent.TButton", background=[("active", "#0077ed"),
|
|
152
|
+
("disabled", "#a6c8f0")])
|
|
153
|
+
|
|
154
|
+
# -- calm scrollbars: slim, arrowless, macOS-like segmented thumb -----
|
|
155
|
+
try:
|
|
156
|
+
style.layout("Vertical.TScrollbar", [
|
|
157
|
+
("Scrollbar.trough",
|
|
158
|
+
{"children": [("Scrollbar.thumb",
|
|
159
|
+
{"expand": True, "unit": 1, "sticky": "ns"})],
|
|
160
|
+
"sticky": "ns"})])
|
|
161
|
+
style.layout("Horizontal.TScrollbar", [
|
|
162
|
+
("Scrollbar.trough",
|
|
163
|
+
{"children": [("Scrollbar.thumb",
|
|
164
|
+
{"expand": True, "unit": 1, "sticky": "ew"})],
|
|
165
|
+
"sticky": "ew"})])
|
|
166
|
+
for scrollbar in ("Vertical.TScrollbar", "Horizontal.TScrollbar"):
|
|
167
|
+
style.configure(scrollbar, background="#c7c7cc",
|
|
168
|
+
troughcolor="#f5f5f7", bordercolor="#f5f5f7",
|
|
169
|
+
arrowcolor=BG, width=11, borderwidth=0)
|
|
170
|
+
style.map(scrollbar, background=[("active", "#a1a1a6"),
|
|
171
|
+
("pressed", "#8e8e93")])
|
|
172
|
+
except tk.TclError:
|
|
173
|
+
pass
|
|
174
|
+
|
|
175
|
+
# -- hairline sashes (no grips) ---------------------------------------
|
|
176
|
+
try:
|
|
177
|
+
style.configure("Sash", background="#e5e5ea", gripcount=0,
|
|
178
|
+
sashthickness=5, borderwidth=0, relief="flat")
|
|
179
|
+
except tk.TclError:
|
|
180
|
+
pass
|
|
181
|
+
|
|
182
|
+
# -- text styles -------------------------------------------------------
|
|
183
|
+
style.configure("Section.TLabel", font=(family, 11, "bold"),
|
|
184
|
+
foreground="#1d1d1f")
|
|
185
|
+
style.configure("Hint.TLabel", foreground="#86868b", font=(family, 9))
|
|
186
|
+
style.configure("Title.TLabel", font=(family, 17, "bold"),
|
|
187
|
+
foreground="#1d1d1f")
|
|
188
|
+
style.configure("Crumb.TLabel", foreground="#0071e3")
|
|
189
|
+
style.configure("CrumbLast.TLabel", foreground="#1d1d1f",
|
|
190
|
+
font=(family, 10, "bold"))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def context_sequences(widget: tk.Misc) -> tuple[str, ...]:
|
|
194
|
+
"""Right-click sequences for the running windowing system."""
|
|
195
|
+
if widget.tk.call("tk", "windowingsystem") == "aqua":
|
|
196
|
+
return ("<Button-2>", "<Control-Button-1>")
|
|
197
|
+
return ("<Button-3>",)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def bind_mousewheel(panel: tk.Misc, canvas: tk.Canvas) -> None:
|
|
201
|
+
"""Scroll *canvas* with the wheel while the pointer is anywhere over *panel*."""
|
|
202
|
+
|
|
203
|
+
def wheel(event) -> None:
|
|
204
|
+
delta = event.delta if event.delta else (120 if event.num == 4 else -120)
|
|
205
|
+
canvas.yview_scroll(-1 if delta > 0 else 1, "units")
|
|
206
|
+
|
|
207
|
+
def enter(_event) -> None:
|
|
208
|
+
canvas.bind_all("<MouseWheel>", wheel)
|
|
209
|
+
canvas.bind_all("<Button-4>", wheel)
|
|
210
|
+
canvas.bind_all("<Button-5>", wheel)
|
|
211
|
+
|
|
212
|
+
def leave(_event) -> None:
|
|
213
|
+
under = canvas.winfo_containing(*canvas.winfo_pointerxy())
|
|
214
|
+
if under is not None and str(under).startswith(str(panel)):
|
|
215
|
+
return
|
|
216
|
+
canvas.unbind_all("<MouseWheel>")
|
|
217
|
+
canvas.unbind_all("<Button-4>")
|
|
218
|
+
canvas.unbind_all("<Button-5>")
|
|
219
|
+
|
|
220
|
+
panel.bind("<Enter>", enter, add="+")
|
|
221
|
+
panel.bind("<Leave>", leave, add="+")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class Tip:
|
|
225
|
+
"""Tiny tooltip: attach to a widget, or drive it by hand with ``arm``."""
|
|
226
|
+
|
|
227
|
+
def __init__(self, widget: tk.Misc, text: str = "", delay: int = 450) -> None:
|
|
228
|
+
self.widget = widget
|
|
229
|
+
self.text = text
|
|
230
|
+
self.delay = delay
|
|
231
|
+
self._job = None
|
|
232
|
+
self._win: tk.Toplevel | None = None
|
|
233
|
+
if text:
|
|
234
|
+
widget.bind("<Enter>", lambda _e: self.arm(self.text), add="+")
|
|
235
|
+
widget.bind("<Leave>", self.hide, add="+")
|
|
236
|
+
widget.bind("<ButtonPress>", self.hide, add="+")
|
|
237
|
+
|
|
238
|
+
def arm(self, text: str) -> None:
|
|
239
|
+
self.hide()
|
|
240
|
+
self.text = text
|
|
241
|
+
if text:
|
|
242
|
+
self._job = self.widget.after(self.delay, self._show)
|
|
243
|
+
|
|
244
|
+
def _show(self) -> None:
|
|
245
|
+
self._job = None
|
|
246
|
+
x = self.widget.winfo_pointerx() + 14
|
|
247
|
+
y = self.widget.winfo_pointery() + 18
|
|
248
|
+
win = tk.Toplevel(self.widget)
|
|
249
|
+
win.wm_overrideredirect(True)
|
|
250
|
+
win.wm_geometry(f"+{x}+{y}")
|
|
251
|
+
tk.Label(win, text=self.text, justify="left", background="#1d1d1f",
|
|
252
|
+
foreground="#ffffff", padx=9, pady=6, wraplength=380).pack()
|
|
253
|
+
self._win = win
|
|
254
|
+
|
|
255
|
+
def hide(self, _event=None) -> None:
|
|
256
|
+
if self._job is not None:
|
|
257
|
+
try:
|
|
258
|
+
self.widget.after_cancel(self._job)
|
|
259
|
+
except tk.TclError:
|
|
260
|
+
pass
|
|
261
|
+
self._job = None
|
|
262
|
+
if self._win is not None:
|
|
263
|
+
try:
|
|
264
|
+
self._win.destroy()
|
|
265
|
+
except tk.TclError:
|
|
266
|
+
pass
|
|
267
|
+
self._win = None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# ---------------------------------------------------------------------------
|
|
271
|
+
# File explorer
|
|
272
|
+
# ---------------------------------------------------------------------------
|
|
273
|
+
|
|
274
|
+
class FileExplorer(ttk.Frame):
|
|
275
|
+
"""Tree of the XML files under a root folder (``design/`` by default).
|
|
276
|
+
|
|
277
|
+
Directories that hold an XML file somewhere below are expandable (top
|
|
278
|
+
level starts open), files open on double-click/Enter, and the document
|
|
279
|
+
currently loaded in the editor is highlighted in accent blue.
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
def __init__(self, master: tk.Misc, root: Path,
|
|
283
|
+
on_open: Callable[[Path], None]) -> None:
|
|
284
|
+
super().__init__(master)
|
|
285
|
+
self.root_dir = Path(root)
|
|
286
|
+
self.on_open = on_open
|
|
287
|
+
self._files: dict[str, Path] = {}
|
|
288
|
+
self._dirs: dict[str, Path] = {}
|
|
289
|
+
self._current: Path | None = None
|
|
290
|
+
family = tkfont.nametofont("TkDefaultFont").actual("family")
|
|
291
|
+
|
|
292
|
+
head = ttk.Frame(self)
|
|
293
|
+
head.pack(fill="x", padx=6, pady=(6, 2))
|
|
294
|
+
ttk.Label(head, text="Files", style="Section.TLabel").pack(side="left")
|
|
295
|
+
ttk.Button(head, text="Refresh", style="Toolbar.TButton",
|
|
296
|
+
command=self.refresh).pack(side="right")
|
|
297
|
+
|
|
298
|
+
ttk.Label(self, text="Double-click to open",
|
|
299
|
+
style="Hint.TLabel").pack(side="bottom", fill="x",
|
|
300
|
+
padx=6, pady=(2, 4))
|
|
301
|
+
self.tree = ttk.Treeview(self, show="tree", selectmode="browse")
|
|
302
|
+
scroll = ttk.Scrollbar(self, orient="vertical",
|
|
303
|
+
command=self.tree.yview)
|
|
304
|
+
self.tree.configure(yscrollcommand=scroll.set)
|
|
305
|
+
self.tree.tag_configure("folder", foreground="#6e6e73")
|
|
306
|
+
self.tree.tag_configure("file", foreground="#1d1d1f")
|
|
307
|
+
self.tree.tag_configure("current", foreground="#0071e3",
|
|
308
|
+
font=(family, 10, "bold"))
|
|
309
|
+
self.tree.pack(side="left", fill="both", expand=True,
|
|
310
|
+
padx=(6, 0), pady=(2, 0))
|
|
311
|
+
scroll.pack(side="right", fill="y", pady=(2, 0))
|
|
312
|
+
|
|
313
|
+
self.tree.bind("<Double-1>", self._on_double)
|
|
314
|
+
self.tree.bind("<Return>", self._on_double)
|
|
315
|
+
self.refresh()
|
|
316
|
+
|
|
317
|
+
# -- building ---------------------------------------------------------
|
|
318
|
+
|
|
319
|
+
@staticmethod
|
|
320
|
+
def _has_xml(folder: Path) -> bool:
|
|
321
|
+
"""True when *folder* holds an XML file directly or deeper."""
|
|
322
|
+
try:
|
|
323
|
+
for entry in folder.iterdir():
|
|
324
|
+
if entry.is_symlink():
|
|
325
|
+
continue
|
|
326
|
+
if entry.is_file() and entry.suffix.lower() == ".xml":
|
|
327
|
+
return True
|
|
328
|
+
if entry.is_dir() and FileExplorer._has_xml(entry):
|
|
329
|
+
return True
|
|
330
|
+
except OSError:
|
|
331
|
+
return False
|
|
332
|
+
return False
|
|
333
|
+
|
|
334
|
+
def refresh(self) -> None:
|
|
335
|
+
"""Rebuild from disk, preserving which folders were expanded."""
|
|
336
|
+
open_dirs = {self._dirs[iid] for iid in self._dirs
|
|
337
|
+
if self.tree.item(iid, "open")}
|
|
338
|
+
self.tree.delete(*self.tree.get_children())
|
|
339
|
+
self._files.clear()
|
|
340
|
+
self._dirs.clear()
|
|
341
|
+
self._add_dir("", self.root_dir, open_dirs)
|
|
342
|
+
if self._current is not None:
|
|
343
|
+
self.mark_current(self._current)
|
|
344
|
+
|
|
345
|
+
def _add_dir(self, parent: str, folder: Path, open_dirs: set) -> None:
|
|
346
|
+
try:
|
|
347
|
+
entries = sorted(folder.iterdir(), key=lambda p: p.name.lower())
|
|
348
|
+
except OSError:
|
|
349
|
+
return
|
|
350
|
+
for entry in entries:
|
|
351
|
+
if entry.is_symlink():
|
|
352
|
+
continue
|
|
353
|
+
if entry.is_dir():
|
|
354
|
+
if not self._has_xml(entry):
|
|
355
|
+
continue
|
|
356
|
+
iid = self.tree.insert(
|
|
357
|
+
parent, "end", text=entry.name, tags=("folder",),
|
|
358
|
+
open=(entry in open_dirs or not parent))
|
|
359
|
+
self._dirs[iid] = entry
|
|
360
|
+
self._add_dir(iid, entry, open_dirs)
|
|
361
|
+
elif entry.is_file() and entry.suffix.lower() == ".xml":
|
|
362
|
+
iid = self.tree.insert(parent, "end", text=entry.name,
|
|
363
|
+
tags=("file",))
|
|
364
|
+
self._files[iid] = entry
|
|
365
|
+
|
|
366
|
+
# -- interaction ------------------------------------------------------
|
|
367
|
+
|
|
368
|
+
def _on_double(self, _event=None):
|
|
369
|
+
iid = self.tree.focus()
|
|
370
|
+
if not iid:
|
|
371
|
+
return None
|
|
372
|
+
if iid in self._files:
|
|
373
|
+
self.on_open(self._files[iid])
|
|
374
|
+
return "break"
|
|
375
|
+
if iid in self._dirs:
|
|
376
|
+
self.tree.item(iid, open=not self.tree.item(iid, "open"))
|
|
377
|
+
return "break"
|
|
378
|
+
return None
|
|
379
|
+
|
|
380
|
+
def mark_current(self, path: Path | None) -> None:
|
|
381
|
+
"""Highlight *path* as the open document and reveal it in the tree."""
|
|
382
|
+
self._current = Path(path) if path is not None else None
|
|
383
|
+
target = None
|
|
384
|
+
want = (self._current.resolve() if self._current is not None
|
|
385
|
+
else None)
|
|
386
|
+
for iid, file_path in self._files.items():
|
|
387
|
+
tags = [t for t in self.tree.item(iid, "tags") if t != "current"]
|
|
388
|
+
if want is not None and file_path.resolve() == want:
|
|
389
|
+
tags.append("current")
|
|
390
|
+
target = iid
|
|
391
|
+
self.tree.item(iid, tags=tags)
|
|
392
|
+
if target is None:
|
|
393
|
+
return
|
|
394
|
+
parent = self.tree.parent(target)
|
|
395
|
+
while parent:
|
|
396
|
+
self.tree.item(parent, open=True)
|
|
397
|
+
parent = self.tree.parent(parent)
|
|
398
|
+
self.tree.selection_set(target)
|
|
399
|
+
self.tree.see(target)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def severity_for(issues: list[Issue], element) -> str:
|
|
403
|
+
"""Worst severity reported for *element* (identity comparison)."""
|
|
404
|
+
worst = ""
|
|
405
|
+
for issue in issues:
|
|
406
|
+
if issue.element is element:
|
|
407
|
+
if issue.severity == "error":
|
|
408
|
+
return "error"
|
|
409
|
+
worst = "warning"
|
|
410
|
+
return worst
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
# ---------------------------------------------------------------------------
|
|
414
|
+
# Breadcrumb + empty state
|
|
415
|
+
# ---------------------------------------------------------------------------
|
|
416
|
+
|
|
417
|
+
class Breadcrumb(ttk.Frame):
|
|
418
|
+
"""Clickable path root › … › selection (always tells you where you are)."""
|
|
419
|
+
|
|
420
|
+
def __init__(self, master: tk.Misc, on_pick: Callable[[object], None]) -> None:
|
|
421
|
+
super().__init__(master)
|
|
422
|
+
self.on_pick = on_pick
|
|
423
|
+
self.show([])
|
|
424
|
+
|
|
425
|
+
def show(self, elements: list) -> None:
|
|
426
|
+
for child in list(self.winfo_children()):
|
|
427
|
+
child.destroy()
|
|
428
|
+
if not elements:
|
|
429
|
+
ttk.Label(self, text="No selection — click a block to inspect and edit it",
|
|
430
|
+
style="Hint.TLabel").pack(side="left")
|
|
431
|
+
return
|
|
432
|
+
ttk.Label(self, text="Selection:", style="Hint.TLabel").pack(side="left", padx=(0, 6))
|
|
433
|
+
for index, element in enumerate(elements):
|
|
434
|
+
last = index == len(elements) - 1
|
|
435
|
+
label = ttk.Label(self, text=localname(str(element.tag)),
|
|
436
|
+
style="CrumbLast.TLabel" if last else "Crumb.TLabel",
|
|
437
|
+
cursor="" if last else "hand2")
|
|
438
|
+
label.pack(side="left")
|
|
439
|
+
if not last:
|
|
440
|
+
label.bind("<Button-1>", lambda _e, el=element: self.on_pick(el))
|
|
441
|
+
ttk.Label(self, text=" › ", style="Hint.TLabel").pack(side="left")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
class EmptyState(ttk.Frame):
|
|
445
|
+
"""Friendly start screen shown while no document is open."""
|
|
446
|
+
|
|
447
|
+
def __init__(self, master: tk.Misc, root_names: list[str],
|
|
448
|
+
on_new_root: Callable[[str], None], on_open: Callable[[], None]) -> None:
|
|
449
|
+
super().__init__(master)
|
|
450
|
+
inner = ttk.Frame(self)
|
|
451
|
+
inner.place(relx=0.5, rely=0.42, anchor="center")
|
|
452
|
+
ttk.Label(inner, text="No document open", style="Title.TLabel").pack()
|
|
453
|
+
ttk.Label(inner, style="Hint.TLabel", justify="center",
|
|
454
|
+
text="Start a new document from a root element of the schema,\n"
|
|
455
|
+
"or open an existing XML file.").pack(pady=(4, 14))
|
|
456
|
+
for name in list(root_names)[:8]:
|
|
457
|
+
ttk.Button(inner, text=f"✚ New <{name}>", style="Toolbar.TButton",
|
|
458
|
+
command=lambda n=name: on_new_root(n)).pack(fill="x", pady=2)
|
|
459
|
+
ttk.Separator(inner).pack(fill="x", pady=8)
|
|
460
|
+
ttk.Button(inner, text="Open an XML file…", style="Accent.TButton",
|
|
461
|
+
command=on_open).pack(fill="x")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
# ---------------------------------------------------------------------------
|
|
465
|
+
# Palette
|
|
466
|
+
# ---------------------------------------------------------------------------
|
|
467
|
+
|
|
468
|
+
class _EntryList(ttk.Frame):
|
|
469
|
+
"""A grouped list of palette entries that keeps scroll/fold/selection."""
|
|
470
|
+
|
|
471
|
+
def __init__(self, master: tk.Misc, on_pick: Callable, on_activate: Callable) -> None:
|
|
472
|
+
super().__init__(master)
|
|
473
|
+
self.on_pick = on_pick
|
|
474
|
+
self.on_activate = on_activate
|
|
475
|
+
self._entries: dict[str, PaletteEntry] = {}
|
|
476
|
+
self._groups: dict[str, str] = {}
|
|
477
|
+
self._open: dict[str, bool] = {}
|
|
478
|
+
self._sig = None
|
|
479
|
+
self._key: str | None = None
|
|
480
|
+
self._bold = tkfont.nametofont("TkDefaultFont").copy()
|
|
481
|
+
self._bold.configure(weight="bold")
|
|
482
|
+
|
|
483
|
+
self.tree = ttk.Treeview(self, columns=("detail",), show="tree",
|
|
484
|
+
selectmode="browse", height=5)
|
|
485
|
+
self.tree.column("#0", width=150, stretch=True)
|
|
486
|
+
self.tree.column("detail", width=110, stretch=False)
|
|
487
|
+
self.tree.tag_configure("group", font=self._bold, foreground="#3c4043")
|
|
488
|
+
self.tree.tag_configure("required", foreground="#b3261e")
|
|
489
|
+
self.tree.tag_configure("allowed", foreground="#188038")
|
|
490
|
+
self.tree.tag_configure("root", foreground="#5e35b1")
|
|
491
|
+
self.tree.tag_configure("muted", foreground="#80868b")
|
|
492
|
+
|
|
493
|
+
scroll = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
|
|
494
|
+
self.tree.configure(yscrollcommand=scroll.set)
|
|
495
|
+
self.tree.pack(side="left", fill="both", expand=True)
|
|
496
|
+
scroll.pack(side="right", fill="y")
|
|
497
|
+
self.tree.bind("<<TreeviewSelect>>", self._on_select)
|
|
498
|
+
self.tree.bind("<Double-1>", self._on_double)
|
|
499
|
+
self.tree.bind("<Return>", self._on_double)
|
|
500
|
+
|
|
501
|
+
@staticmethod
|
|
502
|
+
def _key_of(entry: PaletteEntry) -> str:
|
|
503
|
+
return f"{entry.category}/{entry.block.key or entry.block.name}"
|
|
504
|
+
|
|
505
|
+
def fill(self, groups: OrderedDict[str, list[PaletteEntry]],
|
|
506
|
+
allowed: frozenset = frozenset(), empty_text: str = "",
|
|
507
|
+
open_default: tuple | None = None) -> None:
|
|
508
|
+
sig = (tuple((cat, tuple((self._key_of(e), e.detail) for e in entries))
|
|
509
|
+
for cat, entries in groups.items()), allowed)
|
|
510
|
+
if sig == self._sig:
|
|
511
|
+
return
|
|
512
|
+
self._sig = sig
|
|
513
|
+
for cat, iid in self._groups.items():
|
|
514
|
+
if self.tree.exists(iid):
|
|
515
|
+
self._open[cat] = bool(self.tree.item(iid, "open"))
|
|
516
|
+
top = self.tree.yview()[0]
|
|
517
|
+
wanted = self._key
|
|
518
|
+
self.tree.delete(*self.tree.get_children())
|
|
519
|
+
self._entries.clear()
|
|
520
|
+
self._groups.clear()
|
|
521
|
+
if not groups:
|
|
522
|
+
self.tree.insert("", "end", text=empty_text, tags=("muted",))
|
|
523
|
+
return
|
|
524
|
+
counter = 0
|
|
525
|
+
for cat, entries in groups.items():
|
|
526
|
+
default = True if open_default is None else cat in open_default
|
|
527
|
+
gid = self.tree.insert("", "end", text=f"{cat} ({len(entries)})",
|
|
528
|
+
open=self._open.get(cat, default), tags=("group",))
|
|
529
|
+
self._groups[cat] = gid
|
|
530
|
+
for entry in entries:
|
|
531
|
+
counter += 1
|
|
532
|
+
iid = f"p{counter}"
|
|
533
|
+
self._entries[iid] = entry
|
|
534
|
+
tags = []
|
|
535
|
+
is_allowed = entry.block.name in allowed
|
|
536
|
+
if entry.category == "Required":
|
|
537
|
+
tags.append("required")
|
|
538
|
+
elif entry.block.is_root:
|
|
539
|
+
tags.append("root")
|
|
540
|
+
elif is_allowed:
|
|
541
|
+
tags.append("allowed")
|
|
542
|
+
self.tree.insert(gid, "end", iid=iid,
|
|
543
|
+
text=("✓ " if is_allowed else "") + entry.label,
|
|
544
|
+
values=(entry.detail or entry.block.summary,),
|
|
545
|
+
tags=tuple(tags))
|
|
546
|
+
if wanted is not None and wanted == self._key_of(entry):
|
|
547
|
+
self.tree.selection_set(iid)
|
|
548
|
+
self.tree.yview_moveto(top)
|
|
549
|
+
|
|
550
|
+
def selected_entry(self) -> PaletteEntry | None:
|
|
551
|
+
selection = self.tree.selection()
|
|
552
|
+
return self._entries.get(selection[0]) if selection else None
|
|
553
|
+
|
|
554
|
+
def clear_selection(self) -> None:
|
|
555
|
+
self._key = None
|
|
556
|
+
if self.tree.selection():
|
|
557
|
+
self.tree.selection_set(())
|
|
558
|
+
|
|
559
|
+
def _on_select(self, _event=None) -> None:
|
|
560
|
+
entry = self.selected_entry()
|
|
561
|
+
if entry is None:
|
|
562
|
+
return
|
|
563
|
+
self._key = self._key_of(entry)
|
|
564
|
+
self.on_pick(self, entry)
|
|
565
|
+
|
|
566
|
+
def _on_double(self, _event=None) -> None:
|
|
567
|
+
entry = self.selected_entry()
|
|
568
|
+
if entry is not None:
|
|
569
|
+
self.on_activate(entry)
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
class BlockPalette(ttk.Frame):
|
|
573
|
+
"""Schema-driven palette with two *permanently visible* lists.
|
|
574
|
+
|
|
575
|
+
Top: the whole schema profile (what can exist at all). It never goes away
|
|
576
|
+
when the selection changes; blocks that can be added to the current
|
|
577
|
+
selection get a green ✓. Bottom: what is allowed right now under the
|
|
578
|
+
selection, missing required blocks first. A search box filters both.
|
|
579
|
+
"""
|
|
580
|
+
|
|
581
|
+
def __init__(self, master: tk.Misc, on_activate: Callable[[PaletteEntry], None]) -> None:
|
|
582
|
+
super().__init__(master)
|
|
583
|
+
self.on_activate = on_activate
|
|
584
|
+
self._profile: OrderedDict[str, list[PaletteEntry]] = OrderedDict()
|
|
585
|
+
self._context: list[PaletteEntry] = []
|
|
586
|
+
self._context_name = ""
|
|
587
|
+
self._allowed: frozenset = frozenset()
|
|
588
|
+
self._active: PaletteEntry | None = None
|
|
589
|
+
self._query = tk.StringVar()
|
|
590
|
+
self._context_title = tk.StringVar(value="Allowed here")
|
|
591
|
+
|
|
592
|
+
ttk.Label(self, text="Blocks", style="Section.TLabel").pack(
|
|
593
|
+
anchor="w", padx=6, pady=(6, 2))
|
|
594
|
+
search = ttk.Frame(self)
|
|
595
|
+
search.pack(fill="x", padx=6)
|
|
596
|
+
self.search_entry = ttk.Entry(search, textvariable=self._query)
|
|
597
|
+
self.search_entry.pack(side="left", fill="x", expand=True)
|
|
598
|
+
Tip(self.search_entry, "Filter blocks by name or documentation (Ctrl+F)")
|
|
599
|
+
ttk.Button(search, text="×", width=3, style="Toolbar.TButton",
|
|
600
|
+
command=lambda: self._query.set("")).pack(side="left", padx=(2, 0))
|
|
601
|
+
self._query.trace_add("write", lambda *_: self._render())
|
|
602
|
+
self.search_entry.bind("<Escape>", lambda _e: self._query.set(""))
|
|
603
|
+
|
|
604
|
+
self.add_button = ttk.Button(self, text="Add to selection", style="Accent.TButton",
|
|
605
|
+
state="disabled", command=self._add_active)
|
|
606
|
+
self.add_button.pack(side="bottom", fill="x", padx=6, pady=6)
|
|
607
|
+
self.description = tk.Text(self, height=8, wrap="word", relief="flat", borderwidth=0,
|
|
608
|
+
background="#ffffff", foreground="#1d1d1f", padx=8, pady=6)
|
|
609
|
+
self.description.pack(side="bottom", fill="x", padx=6)
|
|
610
|
+
self._set_description("Pick a block to read its schema documentation.\n"
|
|
611
|
+
"Double-click a block to add it.")
|
|
612
|
+
|
|
613
|
+
panes = ttk.PanedWindow(self, orient="vertical")
|
|
614
|
+
panes.pack(fill="both", expand=True, padx=2, pady=4)
|
|
615
|
+
|
|
616
|
+
profile_box = ttk.Frame(panes)
|
|
617
|
+
head = ttk.Frame(profile_box)
|
|
618
|
+
head.pack(fill="x", padx=4)
|
|
619
|
+
ttk.Label(head, text="Schema profile", style="Section.TLabel").pack(side="left")
|
|
620
|
+
ttk.Label(head, text="✓ = can be added to the selection",
|
|
621
|
+
style="Hint.TLabel").pack(side="right")
|
|
622
|
+
self.profile_list = _EntryList(profile_box, self._picked, self._activate)
|
|
623
|
+
self.profile_list.pack(fill="both", expand=True, padx=4, pady=(2, 4))
|
|
624
|
+
panes.add(profile_box, weight=1)
|
|
625
|
+
|
|
626
|
+
context_box = ttk.Frame(panes)
|
|
627
|
+
ttk.Label(context_box, textvariable=self._context_title,
|
|
628
|
+
style="Section.TLabel").pack(anchor="w", padx=4)
|
|
629
|
+
self.context_list = _EntryList(context_box, self._picked, self._activate)
|
|
630
|
+
self.context_list.pack(fill="both", expand=True, padx=4, pady=(2, 4))
|
|
631
|
+
panes.add(context_box, weight=1)
|
|
632
|
+
|
|
633
|
+
# -- content ---------------------------------------------------------
|
|
634
|
+
|
|
635
|
+
def set_profile(self, categories) -> None:
|
|
636
|
+
"""Set the schema profile (category -> blocks). Called once per schema."""
|
|
637
|
+
self._profile = OrderedDict(
|
|
638
|
+
(cat, [PaletteEntry(block=b, category=cat, reason=f"{cat.lower()} block")
|
|
639
|
+
for b in blocks])
|
|
640
|
+
for cat, blocks in categories.items())
|
|
641
|
+
self._render()
|
|
642
|
+
|
|
643
|
+
def set_context(self, parent_name: str, entries: list[PaletteEntry]) -> None:
|
|
644
|
+
"""Update the 'allowed here' list; the profile list is left untouched."""
|
|
645
|
+
self._context_name = parent_name
|
|
646
|
+
self._context = list(entries)
|
|
647
|
+
self._allowed = frozenset(e.block.name for e in entries if e.block.name != "*")
|
|
648
|
+
self._render()
|
|
649
|
+
|
|
650
|
+
def _render(self) -> None:
|
|
651
|
+
query = self._query.get().strip().lower()
|
|
652
|
+
|
|
653
|
+
def keep(entry: PaletteEntry) -> bool:
|
|
654
|
+
return (not query or query in entry.block.name.lower()
|
|
655
|
+
or query in (entry.block.documentation or "").lower())
|
|
656
|
+
|
|
657
|
+
profile: OrderedDict[str, list[PaletteEntry]] = OrderedDict()
|
|
658
|
+
for cat, entries in self._profile.items():
|
|
659
|
+
kept = [e for e in entries if keep(e)]
|
|
660
|
+
if kept:
|
|
661
|
+
profile[cat] = kept
|
|
662
|
+
context: OrderedDict[str, list[PaletteEntry]] = OrderedDict()
|
|
663
|
+
for entry in self._context:
|
|
664
|
+
if keep(entry):
|
|
665
|
+
context.setdefault(entry.category or "Allowed", []).append(entry)
|
|
666
|
+
|
|
667
|
+
self.profile_list.fill(profile, allowed=self._allowed, open_default=("Roots",),
|
|
668
|
+
empty_text="No block matches" if query else "Schema has no blocks")
|
|
669
|
+
self.context_list.fill(context, empty_text="No block matches" if query
|
|
670
|
+
else "Nothing can be added here")
|
|
671
|
+
self._context_title.set(f"Allowed in <{self._context_name}>"
|
|
672
|
+
if self._context_name else "Allowed here")
|
|
673
|
+
|
|
674
|
+
# -- interaction -----------------------------------------------------
|
|
675
|
+
|
|
676
|
+
def focus_search(self) -> None:
|
|
677
|
+
self.search_entry.focus_set()
|
|
678
|
+
self.search_entry.select_range(0, "end")
|
|
679
|
+
|
|
680
|
+
def selected_entry(self) -> PaletteEntry | None:
|
|
681
|
+
return self._active
|
|
682
|
+
|
|
683
|
+
def _picked(self, source: _EntryList, entry: PaletteEntry) -> None:
|
|
684
|
+
self._active = entry
|
|
685
|
+
other = self.context_list if source is self.profile_list else self.profile_list
|
|
686
|
+
other.clear_selection()
|
|
687
|
+
is_root = entry.category == "Roots"
|
|
688
|
+
self.add_button.configure(
|
|
689
|
+
state="normal",
|
|
690
|
+
text="New document with this root" if is_root else "Add to selection")
|
|
691
|
+
lines = []
|
|
692
|
+
if entry.reason:
|
|
693
|
+
lines.append(entry.reason[:1].upper() + entry.reason[1:])
|
|
694
|
+
if entry.particle is not None:
|
|
695
|
+
lines.append(f"Occurrences allowed: {entry.particle.occurs_label}")
|
|
696
|
+
lines += ["", describe(entry.block)]
|
|
697
|
+
self._set_description("\n".join(lines))
|
|
698
|
+
|
|
699
|
+
def _activate(self, entry: PaletteEntry) -> None:
|
|
700
|
+
self.on_activate(entry)
|
|
701
|
+
|
|
702
|
+
def _add_active(self) -> None:
|
|
703
|
+
if self._active is not None:
|
|
704
|
+
self.on_activate(self._active)
|
|
705
|
+
|
|
706
|
+
def _set_description(self, text: str) -> None:
|
|
707
|
+
self.description.configure(state="normal")
|
|
708
|
+
self.description.delete("1.0", "end")
|
|
709
|
+
self.description.insert("1.0", text)
|
|
710
|
+
self.description.configure(state="disabled")
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
# ---------------------------------------------------------------------------
|
|
714
|
+
# Document tree
|
|
715
|
+
# ---------------------------------------------------------------------------
|
|
716
|
+
|
|
717
|
+
class DocumentTree(ttk.Frame):
|
|
718
|
+
"""The document rendered as nested schema blocks (the "blocks" view)."""
|
|
719
|
+
|
|
720
|
+
def __init__(self, master: tk.Misc, on_select: Callable[[object], None],
|
|
721
|
+
on_context: Callable | None = None) -> None:
|
|
722
|
+
super().__init__(master)
|
|
723
|
+
self.on_select = on_select
|
|
724
|
+
self.on_context = on_context
|
|
725
|
+
self._map: dict[str, object] = {}
|
|
726
|
+
self._paths: dict[str, tuple] = {}
|
|
727
|
+
self._closed: set[tuple] = set()
|
|
728
|
+
self._issues: list[Issue] = []
|
|
729
|
+
self._severity: dict[int, str] = {}
|
|
730
|
+
|
|
731
|
+
bar = ttk.Frame(self)
|
|
732
|
+
bar.grid(row=0, column=0, columnspan=2, sticky="ew", padx=4, pady=4)
|
|
733
|
+
for text, command, tip in (
|
|
734
|
+
("Expand all", self.expand_all, "Unfold every block"),
|
|
735
|
+
("Collapse all", self.collapse_all, "Fold everything below the root")):
|
|
736
|
+
button = ttk.Button(bar, text=text, command=command, style="Toolbar.TButton")
|
|
737
|
+
button.pack(side="left", padx=(0, 4))
|
|
738
|
+
Tip(button, tip)
|
|
739
|
+
ttk.Label(bar, text="Right-click a block for actions", style="Hint.TLabel").pack(
|
|
740
|
+
side="right")
|
|
741
|
+
|
|
742
|
+
self.tree = ttk.Treeview(self, columns=("attrs", "occurs"), show="tree headings")
|
|
743
|
+
self.tree.heading("#0", text="Document blocks")
|
|
744
|
+
self.tree.heading("attrs", text="Attributes / value")
|
|
745
|
+
self.tree.heading("occurs", text="Occurs")
|
|
746
|
+
self.tree.column("#0", width=300, stretch=True)
|
|
747
|
+
self.tree.column("attrs", width=260, stretch=False)
|
|
748
|
+
self.tree.column("occurs", width=70, stretch=False, anchor="center")
|
|
749
|
+
|
|
750
|
+
scroll_y = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
|
|
751
|
+
scroll_x = ttk.Scrollbar(self, orient="horizontal", command=self.tree.xview)
|
|
752
|
+
self.tree.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
|
|
753
|
+
self.tree.grid(row=1, column=0, sticky="nsew")
|
|
754
|
+
scroll_y.grid(row=1, column=1, sticky="ns")
|
|
755
|
+
scroll_x.grid(row=2, column=0, sticky="ew")
|
|
756
|
+
self.rowconfigure(1, weight=1)
|
|
757
|
+
self.columnconfigure(0, weight=1)
|
|
758
|
+
|
|
759
|
+
for kind, colour in KIND_COLOURS.items():
|
|
760
|
+
self.tree.tag_configure(kind, background=colour)
|
|
761
|
+
self.tree.tag_configure("error", foreground=ISSUE_TEXT["error"])
|
|
762
|
+
self.tree.tag_configure("warning", foreground=ISSUE_TEXT["warning"])
|
|
763
|
+
|
|
764
|
+
self.tree.bind("<<TreeviewSelect>>", self._on_select)
|
|
765
|
+
self.tree.bind("<<TreeviewOpen>>", lambda _e: self.after_idle(self._sync_closed))
|
|
766
|
+
self.tree.bind("<<TreeviewClose>>", lambda _e: self.after_idle(self._sync_closed))
|
|
767
|
+
for sequence in context_sequences(self.tree):
|
|
768
|
+
self.tree.bind(sequence, self._on_context)
|
|
769
|
+
|
|
770
|
+
# -- rendering -------------------------------------------------------
|
|
771
|
+
|
|
772
|
+
def _sync_closed(self) -> None:
|
|
773
|
+
for iid, path in self._paths.items():
|
|
774
|
+
if self.tree.exists(iid) and self.tree.get_children(iid):
|
|
775
|
+
if self.tree.item(iid, "open"):
|
|
776
|
+
self._closed.discard(path)
|
|
777
|
+
else:
|
|
778
|
+
self._closed.add(path)
|
|
779
|
+
|
|
780
|
+
def refresh(self, doc: DocumentModel | None, issues: list[Issue] | None = None) -> None:
|
|
781
|
+
self._sync_closed()
|
|
782
|
+
# Read the scroll position only when the tab can paint: yview() on a
|
|
783
|
+
# hidden treeview still works, but moving it back afterwards forces an
|
|
784
|
+
# off-screen layout pass for nothing.
|
|
785
|
+
top = self.tree.yview()[0] if self.tree.winfo_viewable() else 0.0
|
|
786
|
+
self._issues = list(issues or [])
|
|
787
|
+
# O(1) id-keyed lookup replaces the O(issues) scan per element below.
|
|
788
|
+
self._severity = {id(issue.element): issue.severity for issue in self._issues
|
|
789
|
+
if issue.element is not None}
|
|
790
|
+
self.tree.delete(*self.tree.get_children())
|
|
791
|
+
self._map.clear()
|
|
792
|
+
self._paths.clear()
|
|
793
|
+
if doc is None:
|
|
794
|
+
return
|
|
795
|
+
self._add("", doc.root, doc, ())
|
|
796
|
+
if self.tree.winfo_viewable():
|
|
797
|
+
self.tree.yview_moveto(top)
|
|
798
|
+
|
|
799
|
+
def _add(self, parent_iid: str, element, doc: DocumentModel, path: tuple) -> None:
|
|
800
|
+
block = doc.block_of(element)
|
|
801
|
+
particle = doc.particle_of(element)
|
|
802
|
+
kind = kind_of(block)
|
|
803
|
+
severity = self.severity_of(element)
|
|
804
|
+
marker = f" {ISSUE_MARKS[severity]}" if severity in ISSUE_MARKS else ""
|
|
805
|
+
kids = [c for c in element if isinstance(c.tag, str)]
|
|
806
|
+
iid = self.tree.insert(
|
|
807
|
+
parent_iid, "end",
|
|
808
|
+
text=f"{KIND_GLYPHS[kind]} {localname(str(element.tag))}{marker}",
|
|
809
|
+
values=(self._summary(element, kids),
|
|
810
|
+
particle.occurs_label if particle is not None else ""),
|
|
811
|
+
open=path not in self._closed,
|
|
812
|
+
tags=(kind,) + ((severity,) if severity in ISSUE_MARKS else ()),
|
|
813
|
+
)
|
|
814
|
+
self._map[iid] = element
|
|
815
|
+
self._paths[iid] = path
|
|
816
|
+
for index, child in enumerate(kids):
|
|
817
|
+
self._add(iid, child, doc, path + (index,))
|
|
818
|
+
|
|
819
|
+
@staticmethod
|
|
820
|
+
def _summary(element, kids: list) -> str:
|
|
821
|
+
pairs = []
|
|
822
|
+
for name, value in element.attrib.items():
|
|
823
|
+
if name.startswith("{"):
|
|
824
|
+
continue
|
|
825
|
+
text = (value or "").strip()
|
|
826
|
+
if len(text) > 28:
|
|
827
|
+
text = text[:27] + "…"
|
|
828
|
+
pairs.append(f"{name}={text}" if text else name)
|
|
829
|
+
text = (element.text or "").strip()
|
|
830
|
+
if text and not kids:
|
|
831
|
+
pairs.append("= " + (text if len(text) <= 32 else text[:31] + "…"))
|
|
832
|
+
return " ".join(pairs)
|
|
833
|
+
|
|
834
|
+
def severity_of(self, element) -> str:
|
|
835
|
+
return self._severity.get(id(element), "") if self._severity else ""
|
|
836
|
+
|
|
837
|
+
# -- folding ---------------------------------------------------------
|
|
838
|
+
|
|
839
|
+
def expand_all(self) -> None:
|
|
840
|
+
self._closed.clear()
|
|
841
|
+
for iid in self._map:
|
|
842
|
+
self.tree.item(iid, open=True)
|
|
843
|
+
|
|
844
|
+
def collapse_all(self) -> None:
|
|
845
|
+
for iid, path in self._paths.items():
|
|
846
|
+
if path and self.tree.get_children(iid):
|
|
847
|
+
self.tree.item(iid, open=False)
|
|
848
|
+
self._sync_closed()
|
|
849
|
+
|
|
850
|
+
# -- selection -------------------------------------------------------
|
|
851
|
+
|
|
852
|
+
def _on_select(self, _event=None) -> None:
|
|
853
|
+
element = self.selected_element()
|
|
854
|
+
if element is not None:
|
|
855
|
+
self.on_select(element)
|
|
856
|
+
|
|
857
|
+
def _on_context(self, event) -> None:
|
|
858
|
+
iid = self.tree.identify_row(event.y)
|
|
859
|
+
if not iid or self.on_context is None:
|
|
860
|
+
return
|
|
861
|
+
self.tree.selection_set(iid)
|
|
862
|
+
self.tree.focus(iid)
|
|
863
|
+
self.on_context(self._map[iid], event)
|
|
864
|
+
|
|
865
|
+
def selected_element(self):
|
|
866
|
+
selection = self.tree.selection()
|
|
867
|
+
return self._map.get(selection[0]) if selection else None
|
|
868
|
+
|
|
869
|
+
def iid_for(self, element) -> str | None:
|
|
870
|
+
for iid, node in self._map.items():
|
|
871
|
+
if node is element:
|
|
872
|
+
return iid
|
|
873
|
+
return None
|
|
874
|
+
|
|
875
|
+
def select_element(self, element) -> None:
|
|
876
|
+
iid = self.iid_for(element)
|
|
877
|
+
if iid is None:
|
|
878
|
+
return
|
|
879
|
+
self.tree.see(iid)
|
|
880
|
+
if self.tree.selection() != (iid,):
|
|
881
|
+
self.tree.selection_set(iid)
|
|
882
|
+
self.tree.focus(iid)
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
# ---------------------------------------------------------------------------
|
|
886
|
+
# Inspector
|
|
887
|
+
# ---------------------------------------------------------------------------
|
|
888
|
+
|
|
889
|
+
class ResizableText(tk.Frame):
|
|
890
|
+
"""Multiline text field whose height can be adjusted in-place."""
|
|
891
|
+
|
|
892
|
+
def __init__(self, master: tk.Misc, height: int = 4) -> None:
|
|
893
|
+
super().__init__(master, background="#ffffff")
|
|
894
|
+
self.text = tk.Text(self, height=height, wrap="word", undo=True,
|
|
895
|
+
relief="solid", borderwidth=1)
|
|
896
|
+
self.text.grid(row=0, column=0, sticky="nsew")
|
|
897
|
+
self.grip = tk.Canvas(self, width=12, height=12, highlightthickness=0,
|
|
898
|
+
background="#ffffff", cursor="sb_v_double_arrow")
|
|
899
|
+
self.grip.grid(row=0, column=0, sticky="se")
|
|
900
|
+
self.columnconfigure(0, weight=1)
|
|
901
|
+
self.rowconfigure(0, weight=1)
|
|
902
|
+
self._start_y = 0
|
|
903
|
+
self._start_height = height
|
|
904
|
+
self.grip.bind("<ButtonPress-1>", self._start_resize)
|
|
905
|
+
self.grip.bind("<B1-Motion>", self._resize)
|
|
906
|
+
|
|
907
|
+
def insert(self, value: str) -> None:
|
|
908
|
+
self.text.insert("1.0", value)
|
|
909
|
+
|
|
910
|
+
def get(self, start: str, end: str) -> str:
|
|
911
|
+
return self.text.get(start, end)
|
|
912
|
+
|
|
913
|
+
def bind(self, sequence=None, func=None, add=None):
|
|
914
|
+
return self.text.bind(sequence, func, add)
|
|
915
|
+
|
|
916
|
+
def _start_resize(self, event) -> None:
|
|
917
|
+
self._start_y = event.y_root
|
|
918
|
+
self._start_height = int(self.text.cget("height"))
|
|
919
|
+
|
|
920
|
+
def _resize(self, event) -> None:
|
|
921
|
+
line_height = max(1, self.text.winfo_fpixels("1i") / 12)
|
|
922
|
+
delta = round((event.y_root - self._start_y) / line_height)
|
|
923
|
+
self.text.configure(height=max(2, min(30, self._start_height + delta)))
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
class PropertyPanel(ttk.Frame):
|
|
927
|
+
"""Typed inspector: schema attributes plus a value editor for the block.
|
|
928
|
+
|
|
929
|
+
Every field is generated from ``AttributeSpec``/``LeafSpec``: enumerations
|
|
930
|
+
become read-only combo boxes, ``@fixed`` attributes are locked, booleans
|
|
931
|
+
become true/false selectors, and the XSD documentation of the selected
|
|
932
|
+
block is displayed underneath. Editing a field does *not* rebuild the
|
|
933
|
+
panel, so Tab moves smoothly from one field to the next.
|
|
934
|
+
"""
|
|
935
|
+
|
|
936
|
+
def __init__(self, master: tk.Misc, on_change: Callable) -> None:
|
|
937
|
+
super().__init__(master)
|
|
938
|
+
self.on_change = on_change # (element, kind, name, value) -> None
|
|
939
|
+
self._element = None
|
|
940
|
+
self._block: BlockSpec | None = None
|
|
941
|
+
self._attr_labels: dict[str, tuple] = {}
|
|
942
|
+
self._default_fg = ttk.Style(self).lookup("TLabel", "foreground") or "#1d1d1f"
|
|
943
|
+
family = tkfont.nametofont("TkDefaultFont").actual("family")
|
|
944
|
+
|
|
945
|
+
self.strip = tk.Frame(self, height=4, background="#e5e5ea")
|
|
946
|
+
self.strip.grid(row=0, column=0, columnspan=2, sticky="ew")
|
|
947
|
+
ttk.Label(self, text="Properties", style="Section.TLabel").grid(
|
|
948
|
+
row=1, column=0, sticky="w", padx=8, pady=(6, 0))
|
|
949
|
+
self.heading = ttk.Label(self, text="Nothing selected", font=(family, 13, "bold"))
|
|
950
|
+
self.heading.grid(row=2, column=0, columnspan=2, sticky="w", padx=8)
|
|
951
|
+
self.subheading = ttk.Label(self, text="", style="Hint.TLabel",
|
|
952
|
+
wraplength=300, justify="left")
|
|
953
|
+
self.subheading.grid(row=3, column=0, columnspan=2, sticky="w", padx=8)
|
|
954
|
+
self.issue_box = ttk.Frame(self)
|
|
955
|
+
self.issue_box.grid(row=4, column=0, columnspan=2, sticky="ew", padx=8)
|
|
956
|
+
|
|
957
|
+
self.canvas = tk.Canvas(self, highlightthickness=0, background=BG)
|
|
958
|
+
self.body = ttk.Frame(self.canvas)
|
|
959
|
+
self.canvas.create_window((0, 0), window=self.body, anchor="nw", tags="body")
|
|
960
|
+
self.scroller = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
|
|
961
|
+
self.canvas.configure(yscrollcommand=self.scroller.set)
|
|
962
|
+
self.canvas.grid(row=5, column=0, sticky="nsew", padx=(6, 0), pady=6)
|
|
963
|
+
self.scroller.grid(row=5, column=1, sticky="ns", pady=6)
|
|
964
|
+
self.body.bind("<Configure>",
|
|
965
|
+
lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
|
|
966
|
+
self.canvas.bind("<Configure>", lambda _e: self.canvas.itemconfigure(
|
|
967
|
+
"body", width=self.canvas.winfo_width()))
|
|
968
|
+
bind_mousewheel(self, self.canvas)
|
|
969
|
+
|
|
970
|
+
ttk.Label(self, text="Schema (XSD)", style="Section.TLabel").grid(
|
|
971
|
+
row=6, column=0, sticky="w", padx=8)
|
|
972
|
+
self.schema_text = tk.Text(self, height=9, wrap="word", relief="flat", borderwidth=0,
|
|
973
|
+
background="#ffffff", foreground="#1d1d1f", padx=8, pady=6)
|
|
974
|
+
self.schema_text.grid(row=7, column=0, columnspan=2, sticky="nsew", padx=6, pady=(2, 6))
|
|
975
|
+
self.schema_text.configure(state="disabled")
|
|
976
|
+
|
|
977
|
+
self.rowconfigure(5, weight=3)
|
|
978
|
+
self.rowconfigure(7, weight=2)
|
|
979
|
+
self.columnconfigure(0, weight=1)
|
|
980
|
+
|
|
981
|
+
# -- loading ---------------------------------------------------------
|
|
982
|
+
|
|
983
|
+
def load(self, doc: DocumentModel | None, element, issues=None) -> None:
|
|
984
|
+
self._element = element
|
|
985
|
+
self._attr_labels.clear()
|
|
986
|
+
for child in list(self.body.winfo_children()):
|
|
987
|
+
child.destroy()
|
|
988
|
+
self._set_schema_text("")
|
|
989
|
+
self.set_issues(issues)
|
|
990
|
+
|
|
991
|
+
if doc is None or element is None:
|
|
992
|
+
self._block = None
|
|
993
|
+
self.strip.configure(background="#dadce0")
|
|
994
|
+
self.heading.configure(text="Nothing selected")
|
|
995
|
+
self.subheading.configure(
|
|
996
|
+
text="Select a block in the tree or the diagram to edit its properties.")
|
|
997
|
+
return
|
|
998
|
+
|
|
999
|
+
block = doc.block_of(element)
|
|
1000
|
+
self._block = block
|
|
1001
|
+
kind = kind_of(block)
|
|
1002
|
+
self.strip.configure(background=KIND_STYLES[kind][0])
|
|
1003
|
+
self.heading.configure(text=localname(str(element.tag)))
|
|
1004
|
+
detail = block.type_name if block is not None and block.type_name else ""
|
|
1005
|
+
self.subheading.configure(text=" · ".join(
|
|
1006
|
+
part for part in (KIND_STYLES[kind][2] + (" · mixed" if block and block.mixed else ""),
|
|
1007
|
+
detail) if part))
|
|
1008
|
+
|
|
1009
|
+
if block is None:
|
|
1010
|
+
ttk.Label(self.body, text="This element is not described by the schema.",
|
|
1011
|
+
foreground=ISSUE_TEXT["error"], wraplength=280).pack(anchor="w", padx=2)
|
|
1012
|
+
self._add_generic_attributes(element)
|
|
1013
|
+
self._add_value_editor(element, None)
|
|
1014
|
+
return
|
|
1015
|
+
|
|
1016
|
+
if block.attributes:
|
|
1017
|
+
frame = self._section("Attributes")
|
|
1018
|
+
for index, attr in enumerate(block.attributes):
|
|
1019
|
+
self._add_attribute_row(frame, index * 2, element, attr)
|
|
1020
|
+
self._add_value_editor(element, block)
|
|
1021
|
+
self._set_schema_text(describe(block))
|
|
1022
|
+
|
|
1023
|
+
def set_issues(self, issues) -> None:
|
|
1024
|
+
"""Refresh only the problem list (used after in-place edits)."""
|
|
1025
|
+
for child in list(self.issue_box.winfo_children()):
|
|
1026
|
+
child.destroy()
|
|
1027
|
+
seen = set()
|
|
1028
|
+
for issue in issues or []:
|
|
1029
|
+
if issue.message in seen:
|
|
1030
|
+
continue
|
|
1031
|
+
seen.add(issue.message)
|
|
1032
|
+
ttk.Label(self.issue_box,
|
|
1033
|
+
text="{} {}".format(ISSUE_MARKS.get(issue.severity, "•"), issue.message),
|
|
1034
|
+
foreground=ISSUE_TEXT.get(issue.severity, "#202124"),
|
|
1035
|
+
wraplength=300, justify="left").pack(anchor="w", fill="x", pady=(3, 0))
|
|
1036
|
+
|
|
1037
|
+
def _section(self, title: str) -> ttk.LabelFrame:
|
|
1038
|
+
frame = ttk.LabelFrame(self.body, text=title, padding=(8, 4, 8, 6))
|
|
1039
|
+
frame.pack(fill="x", padx=2, pady=(0, 8))
|
|
1040
|
+
frame.columnconfigure(1, weight=1)
|
|
1041
|
+
return frame
|
|
1042
|
+
|
|
1043
|
+
def _add_generic_attributes(self, element) -> None:
|
|
1044
|
+
for name, value in element.attrib.items():
|
|
1045
|
+
if name.startswith("{"):
|
|
1046
|
+
continue
|
|
1047
|
+
row = ttk.Frame(self.body)
|
|
1048
|
+
row.pack(fill="x", pady=1)
|
|
1049
|
+
ttk.Label(row, text=name, width=15).pack(side="left")
|
|
1050
|
+
ttk.Label(row, text=value or "(empty)", style="Hint.TLabel").pack(side="left")
|
|
1051
|
+
|
|
1052
|
+
# -- field builders --------------------------------------------------
|
|
1053
|
+
|
|
1054
|
+
def _add_attribute_row(self, frame, row: int, element, spec) -> None:
|
|
1055
|
+
missing = spec.required and not spec.read_only and not element.get(spec.name)
|
|
1056
|
+
label = ttk.Label(frame, text=spec.name + (" *" if spec.required else ""))
|
|
1057
|
+
if missing:
|
|
1058
|
+
label.configure(foreground=ISSUE_TEXT["error"])
|
|
1059
|
+
label.grid(row=row, column=0, sticky="w", padx=(0, 8), pady=2)
|
|
1060
|
+
self._attr_labels[spec.name] = (label, spec)
|
|
1061
|
+
|
|
1062
|
+
value = (spec.fixed or "") if spec.read_only else (element.get(spec.name) or "")
|
|
1063
|
+
var = tk.StringVar(value=value)
|
|
1064
|
+
commit = lambda _e=None, n=spec.name, v=var, el=element: self._commit(el, n, v.get())
|
|
1065
|
+
|
|
1066
|
+
if spec.enumerations or spec.is_boolean:
|
|
1067
|
+
choices = [""] + (list(spec.enumerations) if spec.enumerations else ["true", "false"])
|
|
1068
|
+
widget = ttk.Combobox(frame, textvariable=var, values=choices,
|
|
1069
|
+
state="disabled" if spec.read_only else "readonly")
|
|
1070
|
+
if not spec.read_only:
|
|
1071
|
+
widget.bind("<<ComboboxSelected>>", commit)
|
|
1072
|
+
else:
|
|
1073
|
+
widget = ttk.Entry(frame, textvariable=var,
|
|
1074
|
+
state="readonly" if spec.read_only else "normal")
|
|
1075
|
+
if not spec.read_only:
|
|
1076
|
+
widget.bind("<Return>", commit)
|
|
1077
|
+
widget.bind("<FocusOut>", commit)
|
|
1078
|
+
widget.grid(row=row, column=1, sticky="ew", pady=2)
|
|
1079
|
+
|
|
1080
|
+
if not spec.required and not spec.read_only:
|
|
1081
|
+
ttk.Button(frame, text="✕", width=2, style="Toolbar.TButton",
|
|
1082
|
+
command=lambda: (var.set(""), commit())).grid(
|
|
1083
|
+
row=row, column=2, padx=(3, 0))
|
|
1084
|
+
|
|
1085
|
+
hints = []
|
|
1086
|
+
if spec.fixed is not None:
|
|
1087
|
+
hints.append("fixed")
|
|
1088
|
+
elif spec.default is not None:
|
|
1089
|
+
hints.append(f"default {spec.default}")
|
|
1090
|
+
if spec.documentation:
|
|
1091
|
+
hints.append(spec.documentation)
|
|
1092
|
+
if hints:
|
|
1093
|
+
ttk.Label(frame, text=" · ".join(hints), style="Hint.TLabel",
|
|
1094
|
+
wraplength=250, justify="left").grid(
|
|
1095
|
+
row=row + 1, column=0, columnspan=3, sticky="w")
|
|
1096
|
+
|
|
1097
|
+
def _add_value_editor(self, element, block: BlockSpec | None) -> None:
|
|
1098
|
+
if block is not None and block.leaf is None and not block.mixed:
|
|
1099
|
+
return
|
|
1100
|
+
frame = self._section("Value")
|
|
1101
|
+
frame.columnconfigure(0, weight=1)
|
|
1102
|
+
leaf = block.leaf if block is not None else None
|
|
1103
|
+
if leaf is not None and leaf.enumerations:
|
|
1104
|
+
var = tk.StringVar(value=(element.text or "").strip())
|
|
1105
|
+
combo = ttk.Combobox(frame, textvariable=var, state="readonly",
|
|
1106
|
+
values=[""] + list(leaf.enumerations))
|
|
1107
|
+
combo.grid(row=0, column=0, sticky="ew")
|
|
1108
|
+
combo.bind("<<ComboboxSelected>>",
|
|
1109
|
+
lambda _e, v=var, el=element: self._commit_text(el, v.get()))
|
|
1110
|
+
return
|
|
1111
|
+
editor = ResizableText(frame, height=4)
|
|
1112
|
+
editor.insert(element.text or "")
|
|
1113
|
+
editor.grid(row=0, column=0, sticky="ew")
|
|
1114
|
+
editor.bind("<FocusOut>",
|
|
1115
|
+
lambda _e, el=element: self._commit_text(el, editor.get("1.0", "end-1c")))
|
|
1116
|
+
ttk.Button(frame, text="Apply value", style="Toolbar.TButton",
|
|
1117
|
+
command=lambda el=element: self._commit_text(
|
|
1118
|
+
el, editor.get("1.0", "end-1c"))).grid(row=1, column=0, sticky="e", pady=(4, 0))
|
|
1119
|
+
|
|
1120
|
+
# -- commits ---------------------------------------------------------
|
|
1121
|
+
|
|
1122
|
+
def _commit(self, element, name: str, value: str) -> None:
|
|
1123
|
+
if element is not self._element:
|
|
1124
|
+
return
|
|
1125
|
+
self.on_change(element, "attribute", name, value)
|
|
1126
|
+
entry = self._attr_labels.get(name)
|
|
1127
|
+
if entry is not None:
|
|
1128
|
+
label, spec = entry
|
|
1129
|
+
missing = spec.required and not spec.read_only and not element.get(name)
|
|
1130
|
+
label.configure(foreground=ISSUE_TEXT["error"] if missing else self._default_fg)
|
|
1131
|
+
|
|
1132
|
+
def _commit_text(self, element, value: str) -> None:
|
|
1133
|
+
if element is self._element:
|
|
1134
|
+
self.on_change(element, "text", "", value)
|
|
1135
|
+
|
|
1136
|
+
def _set_schema_text(self, text: str) -> None:
|
|
1137
|
+
self.schema_text.configure(state="normal")
|
|
1138
|
+
self.schema_text.delete("1.0", "end")
|
|
1139
|
+
self.schema_text.insert("1.0", text)
|
|
1140
|
+
self.schema_text.configure(state="disabled")
|
|
1141
|
+
|
|
1142
|
+
|
|
1143
|
+
# ---------------------------------------------------------------------------
|
|
1144
|
+
# Source view
|
|
1145
|
+
# ---------------------------------------------------------------------------
|
|
1146
|
+
|
|
1147
|
+
#: Above this many characters the source tab skips regex highlighting (tens
|
|
1148
|
+
#: of thousands of tag_add calls) and shows plain text instead — the content
|
|
1149
|
+
#: stays identical, only the colours are dropped for very large files.
|
|
1150
|
+
SOURCE_HIGHLIGHT_LIMIT = 200_000
|
|
1151
|
+
|
|
1152
|
+
class SourceView(ttk.Frame):
|
|
1153
|
+
"""Read-only, syntax-coloured XML of the live buffer (as it will be saved)."""
|
|
1154
|
+
|
|
1155
|
+
TAG_RE = re.compile(r"</?[\w:.\-]+|\??/?>")
|
|
1156
|
+
ATTR_RE = re.compile(r"""([\w:.\-]+)(\s*=\s*)("[^"]*"|'[^']*')""")
|
|
1157
|
+
COMMENT_RE = re.compile(r"<!--.*?-->")
|
|
1158
|
+
|
|
1159
|
+
def __init__(self, master: tk.Misc) -> None:
|
|
1160
|
+
super().__init__(master)
|
|
1161
|
+
bar = ttk.Frame(self)
|
|
1162
|
+
bar.grid(row=0, column=0, columnspan=2, sticky="ew", padx=4, pady=4)
|
|
1163
|
+
copy = ttk.Button(bar, text="Copy XML", style="Toolbar.TButton", command=self._copy)
|
|
1164
|
+
copy.pack(side="left")
|
|
1165
|
+
self.info = ttk.Label(bar, text="", style="Hint.TLabel")
|
|
1166
|
+
self.info.pack(side="right")
|
|
1167
|
+
|
|
1168
|
+
mono = tkfont.nametofont("TkFixedFont").copy()
|
|
1169
|
+
mono.configure(size=10)
|
|
1170
|
+
self.text = tk.Text(self, wrap="none", font=mono, background="#fbfbfb",
|
|
1171
|
+
foreground="#202124", relief="flat", borderwidth=0, padx=8, pady=6)
|
|
1172
|
+
scroll_y = ttk.Scrollbar(self, orient="vertical", command=self.text.yview)
|
|
1173
|
+
scroll_x = ttk.Scrollbar(self, orient="horizontal", command=self.text.xview)
|
|
1174
|
+
self.text.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
|
|
1175
|
+
self.text.grid(row=1, column=0, sticky="nsew")
|
|
1176
|
+
scroll_y.grid(row=1, column=1, sticky="ns")
|
|
1177
|
+
scroll_x.grid(row=2, column=0, sticky="ew")
|
|
1178
|
+
self.rowconfigure(1, weight=1)
|
|
1179
|
+
self.columnconfigure(0, weight=1)
|
|
1180
|
+
self.text.tag_configure("tag", foreground="#1a73e8")
|
|
1181
|
+
self.text.tag_configure("attr", foreground="#b06000")
|
|
1182
|
+
self.text.tag_configure("value", foreground="#188038")
|
|
1183
|
+
self.text.tag_configure("comment", foreground="#80868b")
|
|
1184
|
+
self.text.configure(state="disabled")
|
|
1185
|
+
|
|
1186
|
+
def show(self, content: str) -> None:
|
|
1187
|
+
# The source tab is usually hidden while editing: skip the expensive
|
|
1188
|
+
# regex highlighting until the user actually opens it (see
|
|
1189
|
+
# editor._on_tab_changed). Plain insert keeps edits cheap; the full
|
|
1190
|
+
# refresh happens on tab switch.
|
|
1191
|
+
if self.winfo_viewable():
|
|
1192
|
+
self._show_highlighted(content)
|
|
1193
|
+
else:
|
|
1194
|
+
self._pending = content
|
|
1195
|
+
self.info.configure(text="")
|
|
1196
|
+
|
|
1197
|
+
def refresh_if_visible(self) -> None:
|
|
1198
|
+
"""Apply a deferred paint if the Source tab is currently showing."""
|
|
1199
|
+
pending = getattr(self, "_pending", None)
|
|
1200
|
+
if pending is None or not self.winfo_viewable():
|
|
1201
|
+
return
|
|
1202
|
+
self._pending = None
|
|
1203
|
+
self._show_highlighted(pending)
|
|
1204
|
+
|
|
1205
|
+
def _show_highlighted(self, content: str) -> None:
|
|
1206
|
+
top = self.text.yview()[0]
|
|
1207
|
+
self.text.configure(state="normal")
|
|
1208
|
+
self.text.delete("1.0", "end")
|
|
1209
|
+
self.text.insert("1.0", content)
|
|
1210
|
+
if len(content) <= SOURCE_HIGHLIGHT_LIMIT:
|
|
1211
|
+
for number, line in enumerate(content.split("\n"), 1):
|
|
1212
|
+
if "<" not in line:
|
|
1213
|
+
continue
|
|
1214
|
+
for match in self.TAG_RE.finditer(line):
|
|
1215
|
+
self.text.tag_add("tag", f"{number}.{match.start()}", f"{number}.{match.end()}")
|
|
1216
|
+
for match in self.ATTR_RE.finditer(line):
|
|
1217
|
+
self.text.tag_add("attr", f"{number}.{match.start(1)}", f"{number}.{match.end(1)}")
|
|
1218
|
+
self.text.tag_add("value", f"{number}.{match.start(3)}", f"{number}.{match.end(3)}")
|
|
1219
|
+
for match in self.COMMENT_RE.finditer(line):
|
|
1220
|
+
self.text.tag_add("comment", f"{number}.{match.start()}", f"{number}.{match.end()}")
|
|
1221
|
+
self.info.configure(text=f"{content.count(chr(10)) + 1 if content else 0} lines")
|
|
1222
|
+
else:
|
|
1223
|
+
shown_kb = len(content.encode("utf-8", "replace")) // 1024
|
|
1224
|
+
self.info.configure(text=f"{content.count(chr(10)) + 1} lines · {shown_kb} KB — "
|
|
1225
|
+
"highlighting off for large files")
|
|
1226
|
+
self.text.configure(state="disabled")
|
|
1227
|
+
self.text.yview_moveto(top)
|
|
1228
|
+
|
|
1229
|
+
def _copy(self) -> None:
|
|
1230
|
+
self.clipboard_clear()
|
|
1231
|
+
self.clipboard_append(self.text.get("1.0", "end-1c"))
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
# ---------------------------------------------------------------------------
|
|
1235
|
+
# Diagram
|
|
1236
|
+
# ---------------------------------------------------------------------------
|
|
1237
|
+
|
|
1238
|
+
#: Files this size (or larger) open with the diagram pre-folded: one card per
|
|
1239
|
+
#: top-level section instead of one card per element, so the first paint is
|
|
1240
|
+
#: fast and the user unfolds only what they need.
|
|
1241
|
+
LARGE_DIAGRAM_ELEMENTS = 120
|
|
1242
|
+
|
|
1243
|
+
NODE_H, HEAD_H = 50, 26
|
|
1244
|
+
GAP_X, GAP_Y, MARGIN = 70, 12, 28
|
|
1245
|
+
MIN_W, MAX_W = 160, 320
|
|
1246
|
+
TOGGLE_R = 9
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
@dataclass(eq=False)
|
|
1250
|
+
class _Node:
|
|
1251
|
+
nid: int
|
|
1252
|
+
element: object
|
|
1253
|
+
depth: int
|
|
1254
|
+
path: tuple
|
|
1255
|
+
title: str
|
|
1256
|
+
subtitle: str
|
|
1257
|
+
kind: str
|
|
1258
|
+
occurs: str
|
|
1259
|
+
optional: bool
|
|
1260
|
+
severity: str
|
|
1261
|
+
has_children: bool
|
|
1262
|
+
block: object = None
|
|
1263
|
+
children: list = field(default_factory=list)
|
|
1264
|
+
hidden: int = 0
|
|
1265
|
+
x: float = 0.0
|
|
1266
|
+
y: float = 0.0
|
|
1267
|
+
w: float = MIN_W
|
|
1268
|
+
|
|
1269
|
+
|
|
1270
|
+
class BlockDiagram(ttk.Frame):
|
|
1271
|
+
"""Colour-coded, foldable left-to-right graph of the document.
|
|
1272
|
+
|
|
1273
|
+
* one card per block: coloured header (kind), name, occurrences badge,
|
|
1274
|
+
key attributes / value underneath, ✖/⚠ badge when it has problems;
|
|
1275
|
+
* dashed connectors = optional blocks;
|
|
1276
|
+
* ⊖ / ⊕n button on the card edge folds/unfolds a whole branch
|
|
1277
|
+
(the number is how many blocks are hidden);
|
|
1278
|
+
* click = select (synced with the tree and the inspector),
|
|
1279
|
+
double-click = fold/unfold, right-click = action menu,
|
|
1280
|
+
hover = tooltip, Ctrl+wheel = zoom, drag background = pan.
|
|
1281
|
+
"""
|
|
1282
|
+
|
|
1283
|
+
def __init__(self, master: tk.Misc, on_select: Callable[[object], None],
|
|
1284
|
+
on_context: Callable | None = None) -> None:
|
|
1285
|
+
super().__init__(master)
|
|
1286
|
+
self.on_select = on_select
|
|
1287
|
+
self.on_context = on_context
|
|
1288
|
+
self._doc: DocumentModel | None = None
|
|
1289
|
+
self._issues: list[Issue] = []
|
|
1290
|
+
self._nodes: list[_Node] = []
|
|
1291
|
+
self._items: dict[int, dict] = {}
|
|
1292
|
+
self._hit: dict[int, tuple] = {}
|
|
1293
|
+
self._collapsed: set[tuple] = set()
|
|
1294
|
+
self._selected = None
|
|
1295
|
+
self._selected_nid: int | None = None
|
|
1296
|
+
self._hover: int | None = None
|
|
1297
|
+
self._panning = False
|
|
1298
|
+
self.zoom = 1.0
|
|
1299
|
+
self._size = (1.0, 1.0)
|
|
1300
|
+
self._zoom_var = tk.StringVar(value="100%")
|
|
1301
|
+
self._severity: dict[int, str] = {}
|
|
1302
|
+
self._dirty = True # _redraw() is deferred until the tab shows
|
|
1303
|
+
self._needs_fit = True # "fit on first visible paint" for this doc
|
|
1304
|
+
|
|
1305
|
+
self._family = tkfont.nametofont("TkDefaultFont").actual("family")
|
|
1306
|
+
self._m_title = tkfont.Font(family=self._family, size=-13, weight="bold")
|
|
1307
|
+
self._m_sub = tkfont.Font(family=self._family, size=-11)
|
|
1308
|
+
self._make_fonts()
|
|
1309
|
+
|
|
1310
|
+
self._build_toolbar()
|
|
1311
|
+
self.canvas = tk.Canvas(self, background="#f6f8fb", highlightthickness=0, takefocus=1)
|
|
1312
|
+
scroll_y = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
|
|
1313
|
+
scroll_x = ttk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
|
|
1314
|
+
self.canvas.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
|
|
1315
|
+
self.canvas.grid(row=1, column=0, sticky="nsew")
|
|
1316
|
+
scroll_y.grid(row=1, column=1, sticky="ns")
|
|
1317
|
+
scroll_x.grid(row=2, column=0, sticky="ew")
|
|
1318
|
+
ttk.Label(self, style="Hint.TLabel", text=(
|
|
1319
|
+
"Click: select · Double-click: fold/unfold · Right-click: actions · "
|
|
1320
|
+
"Ctrl+wheel: zoom · Drag the background: pan · dashed link = optional block")
|
|
1321
|
+
).grid(row=3, column=0, columnspan=2, sticky="w", padx=6, pady=3)
|
|
1322
|
+
self.rowconfigure(1, weight=1)
|
|
1323
|
+
self.columnconfigure(0, weight=1)
|
|
1324
|
+
|
|
1325
|
+
self._tip = Tip(self.canvas)
|
|
1326
|
+
c = self.canvas
|
|
1327
|
+
c.bind("<ButtonPress-1>", self._on_press)
|
|
1328
|
+
c.bind("<B1-Motion>", self._on_drag)
|
|
1329
|
+
c.bind("<ButtonRelease-1>", self._on_release)
|
|
1330
|
+
c.bind("<Double-Button-1>", self._on_double)
|
|
1331
|
+
c.bind("<Motion>", self._on_motion)
|
|
1332
|
+
c.bind("<Leave>", self._on_leave)
|
|
1333
|
+
c.bind("<MouseWheel>", self._on_wheel)
|
|
1334
|
+
c.bind("<Button-4>", self._on_wheel)
|
|
1335
|
+
c.bind("<Button-5>", self._on_wheel)
|
|
1336
|
+
c.bind("<Map>", lambda _e: self.redraw_if_visible())
|
|
1337
|
+
for sequence in context_sequences(c):
|
|
1338
|
+
c.bind(sequence, self._on_context)
|
|
1339
|
+
|
|
1340
|
+
# -- toolbar ---------------------------------------------------------
|
|
1341
|
+
|
|
1342
|
+
def _build_toolbar(self) -> None:
|
|
1343
|
+
bar = ttk.Frame(self, padding=(6, 4))
|
|
1344
|
+
bar.grid(row=0, column=0, columnspan=2, sticky="ew")
|
|
1345
|
+
|
|
1346
|
+
def button(text: str, command, tip: str) -> None:
|
|
1347
|
+
widget = ttk.Button(bar, text=text, command=command, style="Toolbar.TButton")
|
|
1348
|
+
widget.pack(side="left", padx=1)
|
|
1349
|
+
Tip(widget, tip)
|
|
1350
|
+
|
|
1351
|
+
button("Expand all", self.expand_all, "Unfold every block")
|
|
1352
|
+
button("Collapse all", self.collapse_all, "Fold everything below the first level")
|
|
1353
|
+
ttk.Separator(bar, orient="vertical").pack(side="left", fill="y", padx=8)
|
|
1354
|
+
button("−", lambda: self.set_zoom(self.zoom / 1.2), "Zoom out (Ctrl+wheel)")
|
|
1355
|
+
ttk.Label(bar, textvariable=self._zoom_var, width=5, anchor="center").pack(side="left")
|
|
1356
|
+
button("+", lambda: self.set_zoom(self.zoom * 1.2), "Zoom in (Ctrl+wheel)")
|
|
1357
|
+
button("Fit", self.fit, "Fit the whole diagram in the view")
|
|
1358
|
+
button("100%", lambda: self.set_zoom(1.0), "Reset the zoom")
|
|
1359
|
+
|
|
1360
|
+
for kind in reversed(("root", "container", "value", "text", "freeform")):
|
|
1361
|
+
accent, _tint, label = KIND_STYLES[kind]
|
|
1362
|
+
ttk.Label(bar, text=label, style="Hint.TLabel").pack(side="right", padx=(0, 10))
|
|
1363
|
+
tk.Frame(bar, width=12, height=12, background=accent).pack(side="right", padx=(0, 3))
|
|
1364
|
+
|
|
1365
|
+
def _make_fonts(self) -> None:
|
|
1366
|
+
def px(size: int) -> int:
|
|
1367
|
+
return -max(7, round(size * self.zoom))
|
|
1368
|
+
self._f_title = tkfont.Font(family=self._family, size=px(13), weight="bold")
|
|
1369
|
+
self._f_sub = tkfont.Font(family=self._family, size=px(11))
|
|
1370
|
+
self._f_badge = tkfont.Font(family=self._family, size=px(10), weight="bold")
|
|
1371
|
+
|
|
1372
|
+
# -- public API ------------------------------------------------------
|
|
1373
|
+
|
|
1374
|
+
def render(self, doc: DocumentModel | None, issues: list[Issue] | None = None) -> None:
|
|
1375
|
+
if doc is not self._doc:
|
|
1376
|
+
self._collapsed.clear()
|
|
1377
|
+
self._selected = None
|
|
1378
|
+
self._needs_fit = True
|
|
1379
|
+
if doc is not None:
|
|
1380
|
+
# Large documents (documentation.xml, …): fold every first-level
|
|
1381
|
+
# branch so the first paint draws a handful of cards instead of
|
|
1382
|
+
# the whole tree. Unfolding is one click per section.
|
|
1383
|
+
count = sum(1 for node in doc.root.iter() if isinstance(node.tag, str))
|
|
1384
|
+
if count >= LARGE_DIAGRAM_ELEMENTS:
|
|
1385
|
+
kids = [c for c in doc.root if isinstance(c.tag, str)]
|
|
1386
|
+
self._collapsed = {(index,) for index in range(len(kids))}
|
|
1387
|
+
self._doc = doc
|
|
1388
|
+
self._issues = list(issues or [])
|
|
1389
|
+
self._severity = {id(issue.element): issue.severity for issue in self._issues
|
|
1390
|
+
if issue.element is not None}
|
|
1391
|
+
if self._visible():
|
|
1392
|
+
self._redraw()
|
|
1393
|
+
self._dirty = False
|
|
1394
|
+
else:
|
|
1395
|
+
# Off-screen redraws only burn time: remember the state, paint when
|
|
1396
|
+
# the user actually switches to the Diagram tab.
|
|
1397
|
+
self._dirty = True
|
|
1398
|
+
|
|
1399
|
+
def _visible(self) -> bool:
|
|
1400
|
+
try:
|
|
1401
|
+
return bool(self.winfo_viewable() and self.canvas.winfo_width() >= 60)
|
|
1402
|
+
except tk.TclError:
|
|
1403
|
+
return False
|
|
1404
|
+
|
|
1405
|
+
def redraw_if_visible(self) -> bool:
|
|
1406
|
+
"""Paint a deferred redraw if the tab is showing; True when painted."""
|
|
1407
|
+
if self._doc is None or not self._visible():
|
|
1408
|
+
return False
|
|
1409
|
+
if not self._dirty:
|
|
1410
|
+
return False
|
|
1411
|
+
self._redraw()
|
|
1412
|
+
self._dirty = False
|
|
1413
|
+
if self._needs_fit:
|
|
1414
|
+
self._needs_fit = False
|
|
1415
|
+
self.fit()
|
|
1416
|
+
self._scroll_to(self._selected)
|
|
1417
|
+
return True
|
|
1418
|
+
|
|
1419
|
+
def select_element(self, element, reveal: bool = True) -> None:
|
|
1420
|
+
"""Highlight *element* (unfolding its ancestors and scrolling to it)."""
|
|
1421
|
+
self._selected = element
|
|
1422
|
+
if element is not None and self._doc is not None and reveal:
|
|
1423
|
+
path = self._path_of(element)
|
|
1424
|
+
if path is not None:
|
|
1425
|
+
changed = False
|
|
1426
|
+
for depth in range(len(path)):
|
|
1427
|
+
if path[:depth] in self._collapsed:
|
|
1428
|
+
self._collapsed.discard(path[:depth])
|
|
1429
|
+
changed = True
|
|
1430
|
+
if changed:
|
|
1431
|
+
self._redraw()
|
|
1432
|
+
self._apply_selection()
|
|
1433
|
+
if reveal:
|
|
1434
|
+
self._scroll_to(element)
|
|
1435
|
+
|
|
1436
|
+
def expand_all(self) -> None:
|
|
1437
|
+
self._collapsed.clear()
|
|
1438
|
+
self._redraw()
|
|
1439
|
+
|
|
1440
|
+
def collapse_all(self) -> None:
|
|
1441
|
+
if self._doc is None:
|
|
1442
|
+
return
|
|
1443
|
+
self._collapsed = {path for path in self._container_paths() if path}
|
|
1444
|
+
self._redraw()
|
|
1445
|
+
|
|
1446
|
+
def toggle(self, node: _Node) -> None:
|
|
1447
|
+
if not node.has_children:
|
|
1448
|
+
return
|
|
1449
|
+
if node.path in self._collapsed:
|
|
1450
|
+
self._collapsed.discard(node.path)
|
|
1451
|
+
else:
|
|
1452
|
+
self._collapsed.add(node.path)
|
|
1453
|
+
self._redraw()
|
|
1454
|
+
|
|
1455
|
+
def set_zoom(self, value: float, anchor=None, reset_view: bool = False) -> None:
|
|
1456
|
+
value = max(0.35, min(2.0, value))
|
|
1457
|
+
if abs(value - self.zoom) < 1e-3 and not reset_view:
|
|
1458
|
+
return
|
|
1459
|
+
c = self.canvas
|
|
1460
|
+
ax, ay = anchor if anchor else (c.winfo_width() / 2, c.winfo_height() / 2)
|
|
1461
|
+
mx, my = c.canvasx(ax) / self.zoom, c.canvasy(ay) / self.zoom
|
|
1462
|
+
self.zoom = value
|
|
1463
|
+
self._make_fonts()
|
|
1464
|
+
self._zoom_var.set(f"{round(value * 100)}%")
|
|
1465
|
+
self._redraw(view=(0.0, 0.0) if reset_view else (mx * value - ax, my * value - ay))
|
|
1466
|
+
|
|
1467
|
+
def fit(self) -> None:
|
|
1468
|
+
if self._doc is None:
|
|
1469
|
+
return
|
|
1470
|
+
self.update_idletasks()
|
|
1471
|
+
avail_w = max(200, self.canvas.winfo_width())
|
|
1472
|
+
avail_h = max(200, self.canvas.winfo_height())
|
|
1473
|
+
zoom = min(avail_w / self._size[0], avail_h / self._size[1])
|
|
1474
|
+
self.set_zoom(max(0.35, min(1.0, zoom)), reset_view=True)
|
|
1475
|
+
|
|
1476
|
+
# -- model helpers ---------------------------------------------------
|
|
1477
|
+
|
|
1478
|
+
def _container_paths(self) -> list[tuple]:
|
|
1479
|
+
result: list[tuple] = []
|
|
1480
|
+
|
|
1481
|
+
def walk(element, path: tuple) -> None:
|
|
1482
|
+
kids = [c for c in element if isinstance(c.tag, str)]
|
|
1483
|
+
if kids:
|
|
1484
|
+
result.append(path)
|
|
1485
|
+
for index, kid in enumerate(kids):
|
|
1486
|
+
walk(kid, path + (index,))
|
|
1487
|
+
|
|
1488
|
+
walk(self._doc.root, ())
|
|
1489
|
+
return result
|
|
1490
|
+
|
|
1491
|
+
@staticmethod
|
|
1492
|
+
def _path_of(element):
|
|
1493
|
+
parts = []
|
|
1494
|
+
node = element
|
|
1495
|
+
while node is not None and node.getparent() is not None:
|
|
1496
|
+
siblings = [c for c in node.getparent() if isinstance(c.tag, str)]
|
|
1497
|
+
if node not in siblings:
|
|
1498
|
+
return None
|
|
1499
|
+
parts.append(siblings.index(node))
|
|
1500
|
+
node = node.getparent()
|
|
1501
|
+
return tuple(reversed(parts))
|
|
1502
|
+
|
|
1503
|
+
@staticmethod
|
|
1504
|
+
def _subtitle(element, block, kids: list) -> str:
|
|
1505
|
+
# Captions stay short on purpose: the diagram measures every caption
|
|
1506
|
+
# with the Tk text engine, so a 6 000-char markdown body here used to
|
|
1507
|
+
# cost tens of seconds per redraw on documentation.xml.
|
|
1508
|
+
parts = [f"{k}={v[:60]}" for k, v in element.attrib.items()
|
|
1509
|
+
if not k.startswith("{") and v][:2]
|
|
1510
|
+
text = re.sub(r"\s+", " ", element.text or "").strip()
|
|
1511
|
+
if text and not kids:
|
|
1512
|
+
parts.append(f"“{text[:160]}{'…' if len(text) > 160 else ''}”")
|
|
1513
|
+
if not parts:
|
|
1514
|
+
parts.append(f"{len(kids)} block(s)" if kids else
|
|
1515
|
+
(KIND_STYLES[kind_of(block)][2].lower()))
|
|
1516
|
+
return " · ".join(parts)
|
|
1517
|
+
|
|
1518
|
+
def _fit(self, text: str, font: tkfont.Font, max_width: float) -> str:
|
|
1519
|
+
# Binary search on the prefix length: the old char-by-char loop
|
|
1520
|
+
# called font.measure() once per character (~6 000 calls for one
|
|
1521
|
+
# documentation chapter), which dominated large-file redraws.
|
|
1522
|
+
if font.measure(text) <= max_width:
|
|
1523
|
+
return text
|
|
1524
|
+
if font.measure("…") > max_width:
|
|
1525
|
+
return "…"
|
|
1526
|
+
lo, hi = 0, len(text)
|
|
1527
|
+
while lo < hi:
|
|
1528
|
+
mid = (lo + hi + 1) // 2
|
|
1529
|
+
if font.measure(text[:mid] + "…") <= max_width:
|
|
1530
|
+
lo = mid
|
|
1531
|
+
else:
|
|
1532
|
+
hi = mid - 1
|
|
1533
|
+
return text[:lo] + "…"
|
|
1534
|
+
|
|
1535
|
+
# -- layout ----------------------------------------------------------
|
|
1536
|
+
|
|
1537
|
+
def _collect(self, element, depth: int, path: tuple) -> _Node:
|
|
1538
|
+
doc = self._doc
|
|
1539
|
+
block = doc.block_of(element)
|
|
1540
|
+
particle = doc.particle_of(element)
|
|
1541
|
+
kids = [c for c in element if isinstance(c.tag, str)]
|
|
1542
|
+
node = _Node(
|
|
1543
|
+
nid=len(self._nodes), element=element, depth=depth, path=path,
|
|
1544
|
+
title=localname(str(element.tag)),
|
|
1545
|
+
subtitle=self._subtitle(element, block, kids),
|
|
1546
|
+
kind=kind_of(block),
|
|
1547
|
+
occurs=particle.occurs_label if particle is not None else "",
|
|
1548
|
+
optional=particle is not None and particle.min_occurs == 0,
|
|
1549
|
+
severity=self._severity.get(id(element), "") if self._severity else "",
|
|
1550
|
+
has_children=bool(kids), block=block)
|
|
1551
|
+
self._nodes.append(node)
|
|
1552
|
+
if kids:
|
|
1553
|
+
if path in self._collapsed:
|
|
1554
|
+
node.hidden = sum(1 for d in element.iterdescendants() if isinstance(d.tag, str))
|
|
1555
|
+
else:
|
|
1556
|
+
for index, child in enumerate(kids):
|
|
1557
|
+
node.children.append(self._collect(child, depth + 1, path + (index,)))
|
|
1558
|
+
head_w = (self._m_title.measure(node.title) + 20
|
|
1559
|
+
+ (self._m_sub.measure(node.occurs) + 16 if node.occurs else 0)
|
|
1560
|
+
+ (26 if node.severity else 0))
|
|
1561
|
+
sub_w = self._m_sub.measure(node.subtitle) + 34
|
|
1562
|
+
node.w = max(MIN_W, min(MAX_W, max(head_w, sub_w)))
|
|
1563
|
+
return node
|
|
1564
|
+
|
|
1565
|
+
def _place(self, node: _Node) -> None:
|
|
1566
|
+
if not node.children:
|
|
1567
|
+
node.y = self._cursor
|
|
1568
|
+
self._cursor += NODE_H + GAP_Y
|
|
1569
|
+
return
|
|
1570
|
+
for child in node.children:
|
|
1571
|
+
self._place(child)
|
|
1572
|
+
node.y = (node.children[0].y + node.children[-1].y) / 2
|
|
1573
|
+
|
|
1574
|
+
def _layout(self) -> None:
|
|
1575
|
+
self._nodes = []
|
|
1576
|
+
root = self._collect(self._doc.root, 0, ())
|
|
1577
|
+
col_w: dict[int, float] = {}
|
|
1578
|
+
for node in self._nodes:
|
|
1579
|
+
col_w[node.depth] = max(col_w.get(node.depth, 0), node.w)
|
|
1580
|
+
xs, x = {}, float(MARGIN)
|
|
1581
|
+
for depth in range(max(col_w) + 1):
|
|
1582
|
+
xs[depth] = x
|
|
1583
|
+
x += col_w[depth] + GAP_X
|
|
1584
|
+
for node in self._nodes:
|
|
1585
|
+
node.x, node.w = xs[node.depth], col_w[node.depth]
|
|
1586
|
+
self._cursor = float(MARGIN)
|
|
1587
|
+
self._place(root)
|
|
1588
|
+
self._size = (x - GAP_X + MARGIN, self._cursor - GAP_Y + MARGIN)
|
|
1589
|
+
|
|
1590
|
+
# -- painting --------------------------------------------------------
|
|
1591
|
+
|
|
1592
|
+
def _redraw(self, view=None) -> None:
|
|
1593
|
+
c = self.canvas
|
|
1594
|
+
if view is None:
|
|
1595
|
+
view = (c.canvasx(0), c.canvasy(0))
|
|
1596
|
+
self._tip.hide()
|
|
1597
|
+
c.delete("all")
|
|
1598
|
+
self._hit.clear()
|
|
1599
|
+
self._items.clear()
|
|
1600
|
+
self._nodes = []
|
|
1601
|
+
self._hover = None
|
|
1602
|
+
self._selected_nid = None
|
|
1603
|
+
if self._doc is None:
|
|
1604
|
+
c.configure(scrollregion=(0, 0, 1, 1))
|
|
1605
|
+
c.create_text(24, 24, anchor="nw", text="No document", fill="#80868b",
|
|
1606
|
+
font=self._f_title)
|
|
1607
|
+
return
|
|
1608
|
+
self._layout()
|
|
1609
|
+
for node in self._nodes:
|
|
1610
|
+
for child in node.children:
|
|
1611
|
+
self._connector(node, child)
|
|
1612
|
+
for node in self._nodes:
|
|
1613
|
+
self._card(node)
|
|
1614
|
+
for node in self._nodes:
|
|
1615
|
+
if node.has_children:
|
|
1616
|
+
self._toggle_button(node)
|
|
1617
|
+
width, height = self._size[0] * self.zoom, self._size[1] * self.zoom
|
|
1618
|
+
c.configure(scrollregion=(0, 0, width, height))
|
|
1619
|
+
c.xview_moveto(max(0.0, min(1.0, view[0] / width)))
|
|
1620
|
+
c.yview_moveto(max(0.0, min(1.0, view[1] / height)))
|
|
1621
|
+
self._apply_selection()
|
|
1622
|
+
|
|
1623
|
+
def _rrect(self, x1, y1, x2, y2, r, **kw) -> int:
|
|
1624
|
+
points = [x1 + r, y1, x2 - r, y1, x2, y1, x2, y1 + r, x2, y2 - r, x2, y2,
|
|
1625
|
+
x2 - r, y2, x1 + r, y2, x1, y2, x1, y2 - r, x1, y1 + r, x1, y1]
|
|
1626
|
+
return self.canvas.create_polygon(points, smooth=True, **kw)
|
|
1627
|
+
|
|
1628
|
+
def _connector(self, parent: _Node, child: _Node) -> None:
|
|
1629
|
+
z = self.zoom
|
|
1630
|
+
x1, y1 = (parent.x + parent.w) * z, (parent.y + NODE_H / 2) * z
|
|
1631
|
+
x2, y2 = child.x * z, (child.y + NODE_H / 2) * z
|
|
1632
|
+
mid = x1 + (x2 - x1) * 0.5
|
|
1633
|
+
options = {"fill": KIND_STYLES[parent.kind][0], "width": max(1.2, 1.6 * z),
|
|
1634
|
+
"smooth": True, "splinesteps": 20, "arrow": "last",
|
|
1635
|
+
"arrowshape": (7 * z, 8 * z, 3 * z)}
|
|
1636
|
+
if child.optional:
|
|
1637
|
+
options["dash"] = (5, 4)
|
|
1638
|
+
self.canvas.create_line(x1, y1, mid, y1, mid, y2, x2, y2, **options)
|
|
1639
|
+
|
|
1640
|
+
def _card(self, node: _Node) -> None:
|
|
1641
|
+
c, z = self.canvas, self.zoom
|
|
1642
|
+
head, tint, _label = KIND_STYLES[node.kind]
|
|
1643
|
+
x, y = node.x * z, node.y * z
|
|
1644
|
+
w, h, hh, r = node.w * z, NODE_H * z, HEAD_H * z, 8 * z
|
|
1645
|
+
|
|
1646
|
+
halo = self._rrect(x - 4 * z, y - 4 * z, x + w + 4 * z, y + h + 4 * z, 11 * z,
|
|
1647
|
+
fill="#fdd663", outline="", state="hidden")
|
|
1648
|
+
self._rrect(x + 1.5 * z, y + 2.5 * z, x + w + 1.5 * z, y + h + 2.5 * z, r,
|
|
1649
|
+
fill="#dadce0", outline="")
|
|
1650
|
+
parts = [
|
|
1651
|
+
self._rrect(x, y, x + w, y + h, r, fill=tint, outline=""),
|
|
1652
|
+
self._rrect(x, y, x + w, y + hh, r, fill=head, outline=""),
|
|
1653
|
+
c.create_rectangle(x, y + hh / 2, x + w, y + hh, fill=head, outline=""),
|
|
1654
|
+
]
|
|
1655
|
+
right = 10 * z
|
|
1656
|
+
if node.severity:
|
|
1657
|
+
cx, cy = x + w - 14 * z, y + hh / 2
|
|
1658
|
+
parts.append(c.create_oval(cx - 8 * z, cy - 8 * z, cx + 8 * z, cy + 8 * z,
|
|
1659
|
+
fill="#ffffff", outline=""))
|
|
1660
|
+
parts.append(c.create_text(cx, cy, text=ISSUE_MARKS[node.severity],
|
|
1661
|
+
fill=ISSUE_COLOURS[node.severity], font=self._f_badge))
|
|
1662
|
+
right = 28 * z
|
|
1663
|
+
if node.occurs:
|
|
1664
|
+
parts.append(c.create_text(x + w - right, y + hh / 2, anchor="e", text=node.occurs,
|
|
1665
|
+
fill=tint, font=self._f_badge))
|
|
1666
|
+
right += self._f_badge.measure(node.occurs) + 8 * z
|
|
1667
|
+
parts.append(c.create_text(
|
|
1668
|
+
x + 10 * z, y + hh / 2, anchor="w", fill="#ffffff", font=self._f_title,
|
|
1669
|
+
text=self._fit(node.title, self._f_title, w - 10 * z - right)))
|
|
1670
|
+
sub_room = w - 20 * z - ((TOGGLE_R + 2) * z if node.has_children else 0)
|
|
1671
|
+
parts.append(c.create_text(
|
|
1672
|
+
x + 10 * z, y + hh + (h - hh) / 2, anchor="w", fill="#3c4043", font=self._f_sub,
|
|
1673
|
+
text=self._fit(node.subtitle, self._f_sub, sub_room)))
|
|
1674
|
+
frame = self._rrect(x, y, x + w, y + h, r, fill="", outline=head, width=1)
|
|
1675
|
+
parts.append(frame)
|
|
1676
|
+
for item in parts:
|
|
1677
|
+
self._hit[item] = ("node", node.nid)
|
|
1678
|
+
self._items[node.nid] = {"frame": frame, "halo": halo}
|
|
1679
|
+
|
|
1680
|
+
def _toggle_button(self, node: _Node) -> None:
|
|
1681
|
+
c, z = self.canvas, self.zoom
|
|
1682
|
+
head = KIND_STYLES[node.kind][0]
|
|
1683
|
+
cx, cy, r = (node.x + node.w) * z, (node.y + NODE_H / 2) * z, TOGGLE_R * z
|
|
1684
|
+
collapsed = node.path in self._collapsed
|
|
1685
|
+
oval = c.create_oval(cx - r, cy - r, cx + r, cy + r,
|
|
1686
|
+
fill=head if collapsed else "#ffffff", outline=head,
|
|
1687
|
+
width=max(1.5, 1.5 * z))
|
|
1688
|
+
label = c.create_text(cx, cy, text=str(min(node.hidden, 99)) if collapsed else "−",
|
|
1689
|
+
fill="#ffffff" if collapsed else head, font=self._f_badge)
|
|
1690
|
+
self._hit[oval] = ("toggle", node.nid)
|
|
1691
|
+
self._hit[label] = ("toggle", node.nid)
|
|
1692
|
+
|
|
1693
|
+
# -- selection / hover styling ---------------------------------------
|
|
1694
|
+
|
|
1695
|
+
def _style_node(self, node: _Node) -> None:
|
|
1696
|
+
items = self._items.get(node.nid)
|
|
1697
|
+
if not items:
|
|
1698
|
+
return
|
|
1699
|
+
selected = node.nid == self._selected_nid
|
|
1700
|
+
colour, width = KIND_STYLES[node.kind][0], 1
|
|
1701
|
+
if node.severity:
|
|
1702
|
+
colour, width = ISSUE_COLOURS[node.severity], 2
|
|
1703
|
+
if node.nid == self._hover:
|
|
1704
|
+
width = max(width, 2)
|
|
1705
|
+
if selected:
|
|
1706
|
+
colour, width = "#202124", 3
|
|
1707
|
+
self.canvas.itemconfigure(items["frame"], outline=colour, width=max(1.0, width * self.zoom))
|
|
1708
|
+
self.canvas.itemconfigure(items["halo"], state="normal" if selected else "hidden")
|
|
1709
|
+
|
|
1710
|
+
def _apply_selection(self) -> None:
|
|
1711
|
+
self._selected_nid = None
|
|
1712
|
+
for node in self._nodes:
|
|
1713
|
+
if node.element is self._selected:
|
|
1714
|
+
self._selected_nid = node.nid
|
|
1715
|
+
break
|
|
1716
|
+
for node in self._nodes:
|
|
1717
|
+
self._style_node(node)
|
|
1718
|
+
|
|
1719
|
+
def _scroll_to(self, element) -> None:
|
|
1720
|
+
c = self.canvas
|
|
1721
|
+
if element is None or self._doc is None or c.winfo_width() < 60 or c.winfo_height() < 60:
|
|
1722
|
+
return
|
|
1723
|
+
node = next((n for n in self._nodes if n.element is element), None)
|
|
1724
|
+
if node is None:
|
|
1725
|
+
return
|
|
1726
|
+
z = self.zoom
|
|
1727
|
+
left, right = node.x * z, (node.x + node.w) * z
|
|
1728
|
+
top, bottom = node.y * z, (node.y + NODE_H) * z
|
|
1729
|
+
total_w, total_h = self._size[0] * z, self._size[1] * z
|
|
1730
|
+
width, height = c.winfo_width(), c.winfo_height()
|
|
1731
|
+
if left < c.canvasx(0) + 10 or right > c.canvasx(width) - 10:
|
|
1732
|
+
c.xview_moveto(max(0.0, (left + right) / 2 - width / 2) / total_w)
|
|
1733
|
+
if top < c.canvasy(0) + 10 or bottom > c.canvasy(height) - 10:
|
|
1734
|
+
c.yview_moveto(max(0.0, (top + bottom) / 2 - height / 2) / total_h)
|
|
1735
|
+
|
|
1736
|
+
# -- events ----------------------------------------------------------
|
|
1737
|
+
|
|
1738
|
+
def _hit_at(self, event):
|
|
1739
|
+
cx, cy = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
|
|
1740
|
+
for item in reversed(self.canvas.find_overlapping(cx, cy, cx, cy)):
|
|
1741
|
+
hit = self._hit.get(item)
|
|
1742
|
+
if hit is not None:
|
|
1743
|
+
return hit
|
|
1744
|
+
return None
|
|
1745
|
+
|
|
1746
|
+
def _on_press(self, event) -> None:
|
|
1747
|
+
self.canvas.focus_set()
|
|
1748
|
+
self._tip.hide()
|
|
1749
|
+
hit = self._hit_at(event)
|
|
1750
|
+
if hit is None:
|
|
1751
|
+
self._panning = True
|
|
1752
|
+
self.canvas.scan_mark(event.x, event.y)
|
|
1753
|
+
self.canvas.configure(cursor="fleur")
|
|
1754
|
+
return
|
|
1755
|
+
kind, nid = hit
|
|
1756
|
+
node = self._nodes[nid]
|
|
1757
|
+
if kind == "toggle":
|
|
1758
|
+
self.toggle(node)
|
|
1759
|
+
else:
|
|
1760
|
+
self.on_select(node.element)
|
|
1761
|
+
|
|
1762
|
+
def _on_drag(self, event) -> None:
|
|
1763
|
+
if self._panning:
|
|
1764
|
+
self.canvas.scan_dragto(event.x, event.y, gain=1)
|
|
1765
|
+
|
|
1766
|
+
def _on_release(self, event) -> None:
|
|
1767
|
+
if self._panning:
|
|
1768
|
+
self._panning = False
|
|
1769
|
+
self.canvas.configure(cursor="hand2" if self._hit_at(event) else "")
|
|
1770
|
+
|
|
1771
|
+
def _on_double(self, event) -> None:
|
|
1772
|
+
hit = self._hit_at(event)
|
|
1773
|
+
if hit is not None:
|
|
1774
|
+
self.toggle(self._nodes[hit[1]])
|
|
1775
|
+
|
|
1776
|
+
def _on_motion(self, event) -> None:
|
|
1777
|
+
if self._panning:
|
|
1778
|
+
return
|
|
1779
|
+
hit = self._hit_at(event)
|
|
1780
|
+
nid = hit[1] if hit else None
|
|
1781
|
+
self.canvas.configure(cursor="hand2" if hit else "")
|
|
1782
|
+
if nid != self._hover:
|
|
1783
|
+
old, self._hover = self._hover, nid
|
|
1784
|
+
for index in (old, nid):
|
|
1785
|
+
if index is not None and index < len(self._nodes):
|
|
1786
|
+
self._style_node(self._nodes[index])
|
|
1787
|
+
self._tip.hide()
|
|
1788
|
+
if nid is not None:
|
|
1789
|
+
self._tip.arm(self._tip_text(self._nodes[nid]))
|
|
1790
|
+
|
|
1791
|
+
def _on_leave(self, _event) -> None:
|
|
1792
|
+
self._tip.hide()
|
|
1793
|
+
if self._hover is not None:
|
|
1794
|
+
old, self._hover = self._hover, None
|
|
1795
|
+
if old < len(self._nodes):
|
|
1796
|
+
self._style_node(self._nodes[old])
|
|
1797
|
+
|
|
1798
|
+
def _on_context(self, event) -> None:
|
|
1799
|
+
hit = self._hit_at(event)
|
|
1800
|
+
if hit is None or self.on_context is None:
|
|
1801
|
+
return
|
|
1802
|
+
node = self._nodes[hit[1]]
|
|
1803
|
+
self.on_select(node.element)
|
|
1804
|
+
self.on_context(node.element, event)
|
|
1805
|
+
|
|
1806
|
+
def _on_wheel(self, event) -> None:
|
|
1807
|
+
self._tip.hide()
|
|
1808
|
+
delta = event.delta if event.delta else (120 if event.num == 4 else -120)
|
|
1809
|
+
if event.state & 0x4: # Ctrl -> zoom around the pointer
|
|
1810
|
+
self.set_zoom(self.zoom * (1.1 if delta > 0 else 1 / 1.1), anchor=(event.x, event.y))
|
|
1811
|
+
elif event.state & 0x1: # Shift -> horizontal scroll
|
|
1812
|
+
self.canvas.xview_scroll(-1 if delta > 0 else 1, "units")
|
|
1813
|
+
else:
|
|
1814
|
+
self.canvas.yview_scroll(-1 if delta > 0 else 1, "units")
|
|
1815
|
+
|
|
1816
|
+
def _tip_text(self, node: _Node) -> str:
|
|
1817
|
+
block = node.block
|
|
1818
|
+
title = node.title + (f" ({block.type_name})" if block is not None and block.type_name else "")
|
|
1819
|
+
lines = [title, KIND_STYLES[node.kind][2] + (f" · {node.occurs}" if node.occurs else "")]
|
|
1820
|
+
for name, value in list(node.element.attrib.items())[:8]:
|
|
1821
|
+
if not name.startswith("{"):
|
|
1822
|
+
shown = value if len(value) <= 80 else value[:79] + "…"
|
|
1823
|
+
lines.append(f" {name} = {shown}")
|
|
1824
|
+
for issue in self._issues:
|
|
1825
|
+
if issue.element is node.element:
|
|
1826
|
+
lines.append(f"{ISSUE_MARKS.get(issue.severity, '•')} {issue.message}")
|
|
1827
|
+
if block is not None and block.documentation:
|
|
1828
|
+
doc = block.documentation.strip()
|
|
1829
|
+
lines += ["", doc if len(doc) < 260 else doc[:259] + "…"]
|
|
1830
|
+
if node.has_children:
|
|
1831
|
+
lines += ["", "Double-click to fold / unfold"]
|
|
1832
|
+
return "\n".join(lines)
|