mitk-python 2026.6__-cp312-cp312-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mitk/MitkCore/MitkDICOMImageIO.dll +0 -0
- mitk/MitkCore/MitkDICOMPMIO.dll +0 -0
- mitk/MitkCore/MitkDICOMRTIO.dll +0 -0
- mitk/MitkCore/MitkDICOMSegIO.dll +0 -0
- mitk/MitkCore/MitkIOExt.dll +0 -0
- mitk/MitkCore/MitkModelFitIOServices.dll +0 -0
- mitk/MitkCore/MitkMultilabelIO.dll +0 -0
- mitk/MitkCore/MitkPlanarFigureIO.dll +0 -0
- mitk/MitkCore/MitkROIIO.dll +0 -0
- mitk/MitkCore/MitkSceneSerializationIO.dll +0 -0
- mitk/MitkCore/MitkSegmentationIO.dll +0 -0
- mitk/MitkDICOM/MitkCESTIO.dll +0 -0
- mitk/MitkModelFit/MitkModelFitModelsServices.dll +0 -0
- mitk/MitkModelFit/MitkPharmacokineticModelsServices.dll +0 -0
- mitk/__init__.py +68 -0
- mitk/mitk.cp312-win_amd64.pyd +0 -0
- mitk/mxn/__init__.py +17 -0
- mitk/mxn/layout/__init__.py +106 -0
- mitk/mxn/layout/_builders.py +220 -0
- mitk/mxn/layout/_io.py +65 -0
- mitk/mxn/layout/_model.py +848 -0
- mitk/mxn/layout/_presets.py +71 -0
- mitk/mxn/layout/_repr.py +170 -0
- mitk/mxn/layout/_selector.py +271 -0
- mitk/mxn/layout/_validation.py +122 -0
- mitk/mxn/layout/_vocabulary.py +59 -0
- mitk/property_view.py +123 -0
- mitk_python-2026.06.dist-info/DELVEWHEEL +2 -0
- mitk_python-2026.06.dist-info/METADATA +67 -0
- mitk_python-2026.06.dist-info/RECORD +190 -0
- mitk_python-2026.06.dist-info/WHEEL +4 -0
- mitk_python-2026.06.dist-info/top_level.txt +1 -0
- mitk_python.libs/ITKCommon-5.4.dll +0 -0
- mitk_python.libs/ITKIOBMP-5.4.dll +0 -0
- mitk_python.libs/ITKIOBioRad-5.4.dll +0 -0
- mitk_python.libs/ITKIOBruker-5.4.dll +0 -0
- mitk_python.libs/ITKIOGDCM-5.4.dll +0 -0
- mitk_python.libs/ITKIOGE-5.4.dll +0 -0
- mitk_python.libs/ITKIOGIPL-5.4.dll +0 -0
- mitk_python.libs/ITKIOHDF5-5.4.dll +0 -0
- mitk_python.libs/ITKIOIPL-5.4.dll +0 -0
- mitk_python.libs/ITKIOImageBase-5.4.dll +0 -0
- mitk_python.libs/ITKIOJPEG-5.4.dll +0 -0
- mitk_python.libs/ITKIOJPEG2000-5.4.dll +0 -0
- mitk_python.libs/ITKIOLSM-5.4.dll +0 -0
- mitk_python.libs/ITKIOMINC-5.4.dll +0 -0
- mitk_python.libs/ITKIOMRC-5.4.dll +0 -0
- mitk_python.libs/ITKIOMeta-5.4.dll +0 -0
- mitk_python.libs/ITKIONIFTI-5.4.dll +0 -0
- mitk_python.libs/ITKIONRRD-5.4.dll +0 -0
- mitk_python.libs/ITKIOPNG-5.4.dll +0 -0
- mitk_python.libs/ITKIOStimulate-5.4.dll +0 -0
- mitk_python.libs/ITKIOTIFF-5.4.dll +0 -0
- mitk_python.libs/ITKIOVTK-5.4.dll +0 -0
- mitk_python.libs/ITKLabelMap-5.4.dll +0 -0
- mitk_python.libs/ITKMathematicalMorphology-5.4.dll +0 -0
- mitk_python.libs/ITKOptimizers-5.4.dll +0 -0
- mitk_python.libs/ITKQuadEdgeMesh-5.4.dll +0 -0
- mitk_python.libs/ITKRegionGrowing-5.4.dll +0 -0
- mitk_python.libs/ITKSmoothing-5.4.dll +0 -0
- mitk_python.libs/ITKStatistics-5.4.dll +0 -0
- mitk_python.libs/ITKTransform-5.4.dll +0 -0
- mitk_python.libs/MitkAlgorithmsExt.dll +0 -0
- mitk_python.libs/MitkAnnotation.dll +0 -0
- mitk_python.libs/MitkCEST.dll +0 -0
- mitk_python.libs/MitkContourModel.dll +0 -0
- mitk_python.libs/MitkCore.dll +0 -0
- mitk_python.libs/MitkCppMicroServices.dll +0 -0
- mitk_python.libs/MitkDICOM.dll +0 -0
- mitk_python.libs/MitkDICOMPM.dll +0 -0
- mitk_python.libs/MitkDICOMQI.dll +0 -0
- mitk_python.libs/MitkDataTypesExt.dll +0 -0
- mitk_python.libs/MitkLog.dll +0 -0
- mitk_python.libs/MitkMapperExt.dll +0 -0
- mitk_python.libs/MitkModelFit.dll +0 -0
- mitk_python.libs/MitkMultilabel.dll +0 -0
- mitk_python.libs/MitkPharmacokinetics.dll +0 -0
- mitk_python.libs/MitkPlanarFigure.dll +0 -0
- mitk_python.libs/MitkROI.dll +0 -0
- mitk_python.libs/MitkRT.dll +0 -0
- mitk_python.libs/MitkSceneSerialization.dll +0 -0
- mitk_python.libs/MitkSceneSerializationBase.dll +0 -0
- mitk_python.libs/MitkSegmentation.dll +0 -0
- mitk_python.libs/MitkSurfaceInterpolation.dll +0 -0
- mitk_python.libs/PocoFoundation.dll +0 -0
- mitk_python.libs/PocoZip.dll +0 -0
- mitk_python.libs/ann.dll +0 -0
- mitk_python.libs/dcmdata.dll +0 -0
- mitk_python.libs/dcmfg.dll +0 -0
- mitk_python.libs/dcmimage.dll +0 -0
- mitk_python.libs/dcmimgle.dll +0 -0
- mitk_python.libs/dcmiod.dll +0 -0
- mitk_python.libs/dcmpmap.dll +0 -0
- mitk_python.libs/dcmrt.dll +0 -0
- mitk_python.libs/dcmseg.dll +0 -0
- mitk_python.libs/dcmsr.dll +0 -0
- mitk_python.libs/gdcmCommon.dll +0 -0
- mitk_python.libs/gdcmDICT.dll +0 -0
- mitk_python.libs/gdcmDSED.dll +0 -0
- mitk_python.libs/gdcmIOD.dll +0 -0
- mitk_python.libs/gdcmMSFF.dll +0 -0
- mitk_python.libs/gdcmcharls.dll +0 -0
- mitk_python.libs/gdcmexpat.dll +0 -0
- mitk_python.libs/gdcmjpeg12.dll +0 -0
- mitk_python.libs/gdcmjpeg16.dll +0 -0
- mitk_python.libs/gdcmjpeg8.dll +0 -0
- mitk_python.libs/gdcmopenjp2.dll +0 -0
- mitk_python.libs/gdcmzlib.dll +0 -0
- mitk_python.libs/itkGrowCut-5.4.dll +0 -0
- mitk_python.libs/itkhdf5-shared-5.4.dll +0 -0
- mitk_python.libs/itkhdf5_cpp-shared-5.4.dll +0 -0
- mitk_python.libs/lz4.dll +0 -0
- mitk_python.libs/msvcp140.dll +0 -0
- mitk_python.libs/oficonv.dll +0 -0
- mitk_python.libs/oflog.dll +0 -0
- mitk_python.libs/ofstd.dll +0 -0
- mitk_python.libs/tbb12.dll +0 -0
- mitk_python.libs/vcomp140.dll +0 -0
- mitk_python.libs/vtkCommonColor-9.5.dll +0 -0
- mitk_python.libs/vtkCommonComputationalGeometry-9.5.dll +0 -0
- mitk_python.libs/vtkCommonCore-9.5.dll +0 -0
- mitk_python.libs/vtkCommonDataModel-9.5.dll +0 -0
- mitk_python.libs/vtkCommonExecutionModel-9.5.dll +0 -0
- mitk_python.libs/vtkCommonMath-9.5.dll +0 -0
- mitk_python.libs/vtkCommonMisc-9.5.dll +0 -0
- mitk_python.libs/vtkCommonSystem-9.5.dll +0 -0
- mitk_python.libs/vtkCommonTransforms-9.5.dll +0 -0
- mitk_python.libs/vtkDICOMParser-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersCellGrid-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersCore-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersExtraction-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersGeneral-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersGeometry-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersHybrid-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersHyperTree-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersModeling-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersParallel-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersReduction-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersSources-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersStatistics-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersTexture-9.5.dll +0 -0
- mitk_python.libs/vtkFiltersVerdict-9.5.dll +0 -0
- mitk_python.libs/vtkIOCellGrid-9.5.dll +0 -0
- mitk_python.libs/vtkIOCore-9.5.dll +0 -0
- mitk_python.libs/vtkIOGeometry-9.5.dll +0 -0
- mitk_python.libs/vtkIOImage-9.5.dll +0 -0
- mitk_python.libs/vtkIOLegacy-9.5.dll +0 -0
- mitk_python.libs/vtkIOPLY-9.5.dll +0 -0
- mitk_python.libs/vtkIOXML-9.5.dll +0 -0
- mitk_python.libs/vtkIOXMLParser-9.5.dll +0 -0
- mitk_python.libs/vtkImagingColor-9.5.dll +0 -0
- mitk_python.libs/vtkImagingCore-9.5.dll +0 -0
- mitk_python.libs/vtkImagingGeneral-9.5.dll +0 -0
- mitk_python.libs/vtkImagingHybrid-9.5.dll +0 -0
- mitk_python.libs/vtkImagingMath-9.5.dll +0 -0
- mitk_python.libs/vtkImagingSources-9.5.dll +0 -0
- mitk_python.libs/vtkImagingStencil-9.5.dll +0 -0
- mitk_python.libs/vtkInteractionStyle-9.5.dll +0 -0
- mitk_python.libs/vtkInteractionWidgets-9.5.dll +0 -0
- mitk_python.libs/vtkParallelCore-9.5.dll +0 -0
- mitk_python.libs/vtkParallelDIY-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingAnnotation-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingContext2D-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingContextOpenGL2-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingCore-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingFreeType-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingHyperTreeGrid-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingLabel-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingOpenGL2-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingUI-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingVolume-9.5.dll +0 -0
- mitk_python.libs/vtkRenderingVolumeOpenGL2-9.5.dll +0 -0
- mitk_python.libs/vtkdoubleconversion-9.5.dll +0 -0
- mitk_python.libs/vtkexpat-9.5.dll +0 -0
- mitk_python.libs/vtkfmt-9.5.dll +0 -0
- mitk_python.libs/vtkfreetype-9.5.dll +0 -0
- mitk_python.libs/vtkglad-9.5.dll +0 -0
- mitk_python.libs/vtkjpeg-9.5.dll +0 -0
- mitk_python.libs/vtkkissfft-9.5.dll +0 -0
- mitk_python.libs/vtkloguru-9.5.dll +0 -0
- mitk_python.libs/vtklz4-9.5.dll +0 -0
- mitk_python.libs/vtklzma-9.5.dll +0 -0
- mitk_python.libs/vtkmetaio-9.5.dll +0 -0
- mitk_python.libs/vtkpng-9.5.dll +0 -0
- mitk_python.libs/vtkpugixml-9.5.dll +0 -0
- mitk_python.libs/vtksys-9.5.dll +0 -0
- mitk_python.libs/vtktiff-9.5.dll +0 -0
- mitk_python.libs/vtktoken-9.5.dll +0 -0
- mitk_python.libs/vtkverdict-9.5.dll +0 -0
- mitk_python.libs/vtkzlib-9.5.dll +0 -0
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
# ============================================================================
|
|
2
|
+
#
|
|
3
|
+
# The Medical Imaging Interaction Toolkit (MITK)
|
|
4
|
+
#
|
|
5
|
+
# Copyright (c) German Cancer Research Center (DKFZ)
|
|
6
|
+
# All rights reserved.
|
|
7
|
+
#
|
|
8
|
+
# Use of this source code is governed by a 3-clause BSD license that can be
|
|
9
|
+
# found in the LICENSE file.
|
|
10
|
+
#
|
|
11
|
+
# ============================================================================
|
|
12
|
+
|
|
13
|
+
"""Dataclass model for the `mitk.mxn.layout` DSL.
|
|
14
|
+
|
|
15
|
+
Mirrors the v2.0 schema (`Modules/QtWidgets/resource/mxn-layout-v2.schema.json`)
|
|
16
|
+
1:1 in attribute names. All dataclasses are frozen and hashable so callers can
|
|
17
|
+
use documents as dict keys, in sets, or memoise builder output.
|
|
18
|
+
|
|
19
|
+
Storage shapes:
|
|
20
|
+
- ``LayoutWindow._links`` is a sorted ``tuple[tuple[str, LinkValue], ...]`` so
|
|
21
|
+
the dataclass remains hashable and equality is order-insensitive.
|
|
22
|
+
- ``MxNLayoutDocument._groups`` is a sorted ``tuple[tuple[str, Group], ...]``
|
|
23
|
+
for the same reason.
|
|
24
|
+
|
|
25
|
+
The friendly ``Mapping`` views are exposed via ``links`` / ``groups``
|
|
26
|
+
properties.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import json
|
|
32
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
33
|
+
from dataclasses import dataclass, replace
|
|
34
|
+
from itertools import count
|
|
35
|
+
from types import MappingProxyType
|
|
36
|
+
from typing import (
|
|
37
|
+
Any,
|
|
38
|
+
Literal,
|
|
39
|
+
TYPE_CHECKING,
|
|
40
|
+
Union,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
from . import _validation as _v
|
|
44
|
+
from ._vocabulary import (
|
|
45
|
+
DEFAULT_EDITOR_NAME,
|
|
46
|
+
DEFAULT_GROUP_NAME,
|
|
47
|
+
LAYOUT_VERSION,
|
|
48
|
+
NAMESPACE_DELIMITER,
|
|
49
|
+
LinkDimension,
|
|
50
|
+
ViewDirection,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
if TYPE_CHECKING:
|
|
55
|
+
from ._selector import MxNWindowSelector
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# --------------------------------------------------------------------------- #
|
|
59
|
+
# Group
|
|
60
|
+
# --------------------------------------------------------------------------- #
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Group:
|
|
65
|
+
"""Synchronization group: a named entry holding shared state for cells
|
|
66
|
+
that link to it. v2.0 carries one property (``select_all``); v3.0 will
|
|
67
|
+
add further per-group properties additively as defaulted fields.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
name: str
|
|
71
|
+
select_all: bool = True
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
DEFAULT_GROUP: Group = Group(DEFAULT_GROUP_NAME, select_all=True)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# --------------------------------------------------------------------------- #
|
|
78
|
+
# Link value type -- v3-modifier-ready from day one
|
|
79
|
+
# --------------------------------------------------------------------------- #
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class Link:
|
|
84
|
+
"""Per-cell link to a synchronisation group on a single dimension.
|
|
85
|
+
|
|
86
|
+
v2 has no modifiers; the bare-string form (``selection="main"``) is
|
|
87
|
+
sufficient and is the canonical wire shape. v3 will additively
|
|
88
|
+
introduce modifier fields (offset, polarity, ...) as defaulted
|
|
89
|
+
optional members; callers compose ``Link(...)`` only when a modifier
|
|
90
|
+
needs to be non-default.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
group: str
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# Stored or wire shape of a link: bare group name (v2) or full `Link` (v3+).
|
|
97
|
+
LinkValue = Union[str, Link]
|
|
98
|
+
|
|
99
|
+
# Accepted at API boundaries (`LayoutWindow.create`, selectors): a bare
|
|
100
|
+
# group name, a full `Link`, or a `Group` (whose `name` is used as the
|
|
101
|
+
# group target). Normalised to `LinkValue` (today: `str`) before storage.
|
|
102
|
+
LinkLike = Union[str, Link, Group]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _normalise_link_value(value: LinkLike) -> str:
|
|
106
|
+
"""Coerce an API-boundary ``LinkLike`` to its v2 wire-shape string.
|
|
107
|
+
|
|
108
|
+
v2 stores bare group names. ``Link`` instances are unwrapped to their
|
|
109
|
+
``.group`` member; ``Group`` instances contribute their ``.name``. The
|
|
110
|
+
function validates the resulting group name against the schema pattern
|
|
111
|
+
so a bad token is caught at the cell-construction boundary.
|
|
112
|
+
|
|
113
|
+
When v3 dimensions with modifiers land, this helper becomes
|
|
114
|
+
dimension-aware: dimensions that carry modifiers will keep the
|
|
115
|
+
``Link`` shape on storage; dimensions without modifiers stay as
|
|
116
|
+
strings.
|
|
117
|
+
"""
|
|
118
|
+
if isinstance(value, Link):
|
|
119
|
+
group = value.group
|
|
120
|
+
elif isinstance(value, Group):
|
|
121
|
+
group = value.name
|
|
122
|
+
elif isinstance(value, str):
|
|
123
|
+
group = value
|
|
124
|
+
else:
|
|
125
|
+
raise ValueError(
|
|
126
|
+
f"link value must be str, Link, or Group, got {type(value).__name__}"
|
|
127
|
+
)
|
|
128
|
+
_v.validate_group_name(group)
|
|
129
|
+
return group
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# --------------------------------------------------------------------------- #
|
|
133
|
+
# LayoutWindow
|
|
134
|
+
# --------------------------------------------------------------------------- #
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
_DEFAULT_LINKS: tuple[tuple[str, str], ...] = (
|
|
138
|
+
(LinkDimension.SELECTION.value, DEFAULT_GROUP_NAME),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _coerce_view_direction(value: ViewDirection | str) -> ViewDirection:
|
|
143
|
+
if isinstance(value, ViewDirection):
|
|
144
|
+
return value
|
|
145
|
+
if isinstance(value, str):
|
|
146
|
+
return ViewDirection(value)
|
|
147
|
+
raise ValueError(
|
|
148
|
+
f"view_direction must be ViewDirection or str, got {type(value).__name__}"
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@dataclass(frozen=True)
|
|
153
|
+
class LayoutWindow:
|
|
154
|
+
"""A leaf render-window. Routing identity (``id``) is required and
|
|
155
|
+
schema-pattern checked; ``name`` is an optional free-form display
|
|
156
|
+
label and is omitted from JSON when ``None``.
|
|
157
|
+
|
|
158
|
+
Direct dataclass init is the *private* form: it sorts ``_links`` to
|
|
159
|
+
keep equality order-insensitive but does **not** re-run regex / length
|
|
160
|
+
/ link checks. Always go through :meth:`create` for input from
|
|
161
|
+
user-controlled sources.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
id: str
|
|
165
|
+
view_direction: ViewDirection
|
|
166
|
+
_links: tuple[tuple[str, LinkValue], ...] = _DEFAULT_LINKS
|
|
167
|
+
name: str | None = None
|
|
168
|
+
size: int = 1
|
|
169
|
+
|
|
170
|
+
def __post_init__(self) -> None:
|
|
171
|
+
# Structural normalisation only -- make storage canonical so that
|
|
172
|
+
# equality and hashing are order-insensitive on the link map. No
|
|
173
|
+
# validation; that lives in `create()`.
|
|
174
|
+
# Use object.__setattr__ to write through the frozen dataclass.
|
|
175
|
+
if not isinstance(self._links, tuple):
|
|
176
|
+
object.__setattr__(self, "_links", tuple(self._links))
|
|
177
|
+
if any(self._links[i] > self._links[i + 1] for i in range(len(self._links) - 1)):
|
|
178
|
+
object.__setattr__(self, "_links", tuple(sorted(self._links)))
|
|
179
|
+
if isinstance(self.view_direction, str) and not isinstance(
|
|
180
|
+
self.view_direction, ViewDirection
|
|
181
|
+
):
|
|
182
|
+
object.__setattr__(
|
|
183
|
+
self, "view_direction", ViewDirection(self.view_direction)
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
# ---- friendly construction -------------------------------------------
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def create(
|
|
190
|
+
cls,
|
|
191
|
+
id: str,
|
|
192
|
+
view_direction: ViewDirection | str,
|
|
193
|
+
*,
|
|
194
|
+
name: str | None = None,
|
|
195
|
+
selection: LinkLike | None = None,
|
|
196
|
+
links: Mapping[LinkDimension | str, LinkLike] | None = None,
|
|
197
|
+
size: int = 1,
|
|
198
|
+
) -> LayoutWindow:
|
|
199
|
+
"""Primary, validating constructor.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
id: Routing identity. Must match ``WINDOW_ID_PATTERN`` (qualified form).
|
|
203
|
+
view_direction: ``ViewDirection`` enum or matching string.
|
|
204
|
+
name: Optional human-readable display label. Omitted from JSON
|
|
205
|
+
when ``None``. Tools should pass ``None`` unless authoring
|
|
206
|
+
for humans.
|
|
207
|
+
selection: Common-case shorthand for the only v2 link
|
|
208
|
+
dimension. Pass any ``LinkLike`` (group name string,
|
|
209
|
+
``Link``, or ``Group``).
|
|
210
|
+
links: Power-user form for setting multiple link dimensions
|
|
211
|
+
at once. Values share the ``LinkLike`` accept-set. Passing
|
|
212
|
+
both ``selection`` and ``links`` raises ``ValueError``.
|
|
213
|
+
size: Splitter weight; only ratios matter. Defaults to 1.
|
|
214
|
+
"""
|
|
215
|
+
_v.validate_window_id(id)
|
|
216
|
+
_v.validate_window_name(name)
|
|
217
|
+
_v.validate_size(size)
|
|
218
|
+
view_direction = _coerce_view_direction(view_direction)
|
|
219
|
+
|
|
220
|
+
if selection is not None and links is not None:
|
|
221
|
+
raise ValueError(
|
|
222
|
+
"pass either 'selection' or 'links', not both: "
|
|
223
|
+
"'selection' is shorthand for links={LinkDimension.SELECTION: ...}"
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
normalised: dict[str, LinkValue] = {}
|
|
227
|
+
if links is not None:
|
|
228
|
+
for raw_key, raw_value in links.items():
|
|
229
|
+
key = _v.validate_dimension_key(raw_key)
|
|
230
|
+
normalised[key] = _normalise_link_value(raw_value)
|
|
231
|
+
else:
|
|
232
|
+
sel_value = DEFAULT_GROUP if selection is None else selection
|
|
233
|
+
normalised[LinkDimension.SELECTION.value] = _normalise_link_value(sel_value)
|
|
234
|
+
|
|
235
|
+
if LinkDimension.SELECTION.value not in normalised:
|
|
236
|
+
raise ValueError(
|
|
237
|
+
"links must include the required 'selection' dimension "
|
|
238
|
+
"(schema v2.0 mandates it on every window)"
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
# Sorted-tuple storage so equality and hashing are order-insensitive.
|
|
242
|
+
stored = tuple(sorted(normalised.items()))
|
|
243
|
+
return cls(id=id, view_direction=view_direction, _links=stored, name=name, size=size)
|
|
244
|
+
|
|
245
|
+
# ---- introspection ---------------------------------------------------
|
|
246
|
+
|
|
247
|
+
@property
|
|
248
|
+
def links(self) -> dict[str, LinkValue]:
|
|
249
|
+
"""Fresh dict ``{dimension: link_value}``. Mutations to the
|
|
250
|
+
returned dict do not affect the window. Under v2 every value is
|
|
251
|
+
``str``; v3 may surface ``Link`` for modifier-bearing dimensions.
|
|
252
|
+
"""
|
|
253
|
+
return dict(self._links)
|
|
254
|
+
|
|
255
|
+
@property
|
|
256
|
+
def selection(self) -> str:
|
|
257
|
+
"""Group name linked on ``LinkDimension.SELECTION``.
|
|
258
|
+
|
|
259
|
+
v2 has no modifiers on the selection dimension, so the return is
|
|
260
|
+
always a bare string. Raises ``KeyError`` if a malformed window
|
|
261
|
+
somehow lacks the selection link (should be impossible for objects
|
|
262
|
+
produced via :meth:`create`).
|
|
263
|
+
"""
|
|
264
|
+
for dim, value in self._links:
|
|
265
|
+
if dim == LinkDimension.SELECTION.value:
|
|
266
|
+
return value if isinstance(value, str) else value.group
|
|
267
|
+
raise KeyError("selection link is missing on this window")
|
|
268
|
+
|
|
269
|
+
def linked_to(
|
|
270
|
+
self,
|
|
271
|
+
group: str | Group,
|
|
272
|
+
*,
|
|
273
|
+
dim: LinkDimension | str = LinkDimension.SELECTION,
|
|
274
|
+
) -> bool:
|
|
275
|
+
"""Whether this window is linked to the given group on the given dimension."""
|
|
276
|
+
target = group.name if isinstance(group, Group) else group
|
|
277
|
+
dim_key = _v.validate_dimension_key(dim)
|
|
278
|
+
for d, value in self._links:
|
|
279
|
+
if d == dim_key:
|
|
280
|
+
stored = value if isinstance(value, str) else value.group
|
|
281
|
+
return stored == target
|
|
282
|
+
return False
|
|
283
|
+
|
|
284
|
+
# ---- transformations -------------------------------------------------
|
|
285
|
+
|
|
286
|
+
def with_link(
|
|
287
|
+
self,
|
|
288
|
+
dimension: LinkDimension | str,
|
|
289
|
+
link: LinkLike,
|
|
290
|
+
) -> LayoutWindow:
|
|
291
|
+
"""Return a copy with the given dimension linked to the given group."""
|
|
292
|
+
dim_key = _v.validate_dimension_key(dimension)
|
|
293
|
+
new_value = _normalise_link_value(link)
|
|
294
|
+
new_links = {k: v for k, v in self._links}
|
|
295
|
+
new_links[dim_key] = new_value
|
|
296
|
+
return replace(self, _links=tuple(sorted(new_links.items())))
|
|
297
|
+
|
|
298
|
+
def with_id(self, new_id: str) -> LayoutWindow:
|
|
299
|
+
"""Return a copy with a new id.
|
|
300
|
+
|
|
301
|
+
WARNING: ids are routing identities; renaming an id that has
|
|
302
|
+
already been served via REST or saved to a session breaks every
|
|
303
|
+
cached reference (persisted session state, REST URL bookmarks,
|
|
304
|
+
per-renderer DataNode property context keys). Safe on in-memory
|
|
305
|
+
documents that have not yet been published.
|
|
306
|
+
"""
|
|
307
|
+
_v.validate_window_id(new_id)
|
|
308
|
+
return replace(self, id=new_id)
|
|
309
|
+
|
|
310
|
+
def with_name(self, new_name: str | None) -> LayoutWindow:
|
|
311
|
+
"""Return a copy with a new display name (None to clear it).
|
|
312
|
+
|
|
313
|
+
Free of the caveats on :meth:`with_id` -- ``name`` is pure metadata.
|
|
314
|
+
"""
|
|
315
|
+
_v.validate_window_name(new_name)
|
|
316
|
+
return replace(self, name=new_name)
|
|
317
|
+
|
|
318
|
+
# ---- repr -----------------------------------------------------------
|
|
319
|
+
|
|
320
|
+
def __repr__(self) -> str:
|
|
321
|
+
from ._repr import window_repr
|
|
322
|
+
|
|
323
|
+
return window_repr(self)
|
|
324
|
+
|
|
325
|
+
def _repr_html_(self) -> str:
|
|
326
|
+
from ._repr import window_html
|
|
327
|
+
|
|
328
|
+
return window_html(self)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# --------------------------------------------------------------------------- #
|
|
332
|
+
# Split
|
|
333
|
+
# --------------------------------------------------------------------------- #
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
SplitOrientation = Literal["horizontal", "vertical"]
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
@dataclass(frozen=True)
|
|
340
|
+
class Split:
|
|
341
|
+
"""An interior splitter dividing its area among children. Maps to QSplitter."""
|
|
342
|
+
|
|
343
|
+
orientation: SplitOrientation
|
|
344
|
+
children: tuple[Union["Split", LayoutWindow], ...]
|
|
345
|
+
size: int = 1
|
|
346
|
+
|
|
347
|
+
def __post_init__(self) -> None:
|
|
348
|
+
if self.orientation not in ("horizontal", "vertical"):
|
|
349
|
+
raise ValueError(
|
|
350
|
+
f"orientation must be 'horizontal' or 'vertical', got {self.orientation!r}"
|
|
351
|
+
)
|
|
352
|
+
if not isinstance(self.children, tuple):
|
|
353
|
+
object.__setattr__(self, "children", tuple(self.children))
|
|
354
|
+
if not self.children:
|
|
355
|
+
raise ValueError("split.children must contain at least one node (schema minItems: 1)")
|
|
356
|
+
for child in self.children:
|
|
357
|
+
if not isinstance(child, (Split, LayoutWindow)):
|
|
358
|
+
raise ValueError(
|
|
359
|
+
f"split children must be Split or LayoutWindow, got {type(child).__name__}"
|
|
360
|
+
)
|
|
361
|
+
_v.validate_size(self.size)
|
|
362
|
+
|
|
363
|
+
# ---- vararg builders -------------------------------------------------
|
|
364
|
+
|
|
365
|
+
@classmethod
|
|
366
|
+
def horizontal(
|
|
367
|
+
cls,
|
|
368
|
+
*children: "Split | LayoutWindow",
|
|
369
|
+
size: int = 1,
|
|
370
|
+
) -> Split:
|
|
371
|
+
"""Build a left-to-right split from a vararg of child nodes."""
|
|
372
|
+
return cls(orientation="horizontal", children=tuple(children), size=size)
|
|
373
|
+
|
|
374
|
+
@classmethod
|
|
375
|
+
def vertical(
|
|
376
|
+
cls,
|
|
377
|
+
*children: "Split | LayoutWindow",
|
|
378
|
+
size: int = 1,
|
|
379
|
+
) -> Split:
|
|
380
|
+
"""Build a top-to-bottom split from a vararg of child nodes."""
|
|
381
|
+
return cls(orientation="vertical", children=tuple(children), size=size)
|
|
382
|
+
|
|
383
|
+
# ---- tree iteration (pre-order) -------------------------------------
|
|
384
|
+
|
|
385
|
+
def windows(self) -> Iterator[LayoutWindow]:
|
|
386
|
+
"""Pre-order iterator over the leaf windows."""
|
|
387
|
+
for child in self.children:
|
|
388
|
+
if isinstance(child, LayoutWindow):
|
|
389
|
+
yield child
|
|
390
|
+
else:
|
|
391
|
+
yield from child.windows()
|
|
392
|
+
|
|
393
|
+
def window_ids(self) -> list[str]:
|
|
394
|
+
"""Pre-order list of window ids (routing identities)."""
|
|
395
|
+
return [w.id for w in self.windows()]
|
|
396
|
+
|
|
397
|
+
def splits(self) -> Iterator[Split]:
|
|
398
|
+
"""Pre-order iterator over the interior splits, including ``self``."""
|
|
399
|
+
yield self
|
|
400
|
+
for child in self.children:
|
|
401
|
+
if isinstance(child, Split):
|
|
402
|
+
yield from child.splits()
|
|
403
|
+
|
|
404
|
+
def find_window(self, id: str) -> LayoutWindow | None:
|
|
405
|
+
"""Return the leaf window with the given id, or ``None`` if no
|
|
406
|
+
such window exists in this subtree.
|
|
407
|
+
"""
|
|
408
|
+
for window in self.windows():
|
|
409
|
+
if window.id == id:
|
|
410
|
+
return window
|
|
411
|
+
return None
|
|
412
|
+
|
|
413
|
+
# ---- selector entry point -------------------------------------------
|
|
414
|
+
|
|
415
|
+
@property
|
|
416
|
+
def select_windows(self) -> "MxNWindowSelector[Split]":
|
|
417
|
+
"""Entry point for the fluent
|
|
418
|
+
:class:`MxNWindowSelector` filter and bulk-transform API rooted at
|
|
419
|
+
this subtree.
|
|
420
|
+
"""
|
|
421
|
+
from ._selector import MxNWindowSelector
|
|
422
|
+
|
|
423
|
+
return MxNWindowSelector(self)
|
|
424
|
+
|
|
425
|
+
# ---- repr -----------------------------------------------------------
|
|
426
|
+
|
|
427
|
+
def __repr__(self) -> str:
|
|
428
|
+
from ._repr import split_repr
|
|
429
|
+
|
|
430
|
+
return split_repr(self)
|
|
431
|
+
|
|
432
|
+
def _repr_html_(self) -> str:
|
|
433
|
+
from ._repr import split_html
|
|
434
|
+
|
|
435
|
+
return split_html(self)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
# --------------------------------------------------------------------------- #
|
|
439
|
+
# MxNLayoutDocument
|
|
440
|
+
# --------------------------------------------------------------------------- #
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _collect_referenced_group_names(root: Split) -> list[str]:
|
|
444
|
+
"""Pre-order list of group names referenced by any window's links.
|
|
445
|
+
|
|
446
|
+
Order is significant for seeding rules (matches the schema's
|
|
447
|
+
document-order seeding convention) but the function only deduplicates
|
|
448
|
+
based on first encounter.
|
|
449
|
+
"""
|
|
450
|
+
seen: dict[str, None] = {}
|
|
451
|
+
for window in root.windows():
|
|
452
|
+
for _, value in window._links:
|
|
453
|
+
name = value if isinstance(value, str) else value.group
|
|
454
|
+
seen.setdefault(name, None)
|
|
455
|
+
return list(seen)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _materialise_groups(
|
|
459
|
+
root: Split,
|
|
460
|
+
raw: Mapping[str, Group] | Iterable[Group] | None,
|
|
461
|
+
) -> tuple[tuple[str, Group], ...]:
|
|
462
|
+
"""Resolve ``MxNLayoutDocument.create``'s ``groups`` argument to the
|
|
463
|
+
sorted-tuple storage shape, validating consistency.
|
|
464
|
+
|
|
465
|
+
``None`` -> auto-materialise an entry with property defaults for every
|
|
466
|
+
label referenced from any window's links.
|
|
467
|
+
"""
|
|
468
|
+
if raw is None:
|
|
469
|
+
materialised: dict[str, Group] = {}
|
|
470
|
+
for name in _collect_referenced_group_names(root):
|
|
471
|
+
_v.validate_group_name(name)
|
|
472
|
+
materialised[name] = Group(name)
|
|
473
|
+
return tuple(sorted(materialised.items()))
|
|
474
|
+
|
|
475
|
+
# `str` / `bytes` are technically `Iterable`, but iterating them
|
|
476
|
+
# yields characters and produces a confusing downstream error.
|
|
477
|
+
# Reject early.
|
|
478
|
+
if isinstance(raw, (str, bytes)):
|
|
479
|
+
raise ValueError(
|
|
480
|
+
f"groups must be Mapping[str, Group], Iterable[Group], or None; "
|
|
481
|
+
f"got {type(raw).__name__}"
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
if isinstance(raw, Mapping):
|
|
485
|
+
materialised = {}
|
|
486
|
+
for key, group in raw.items():
|
|
487
|
+
if not isinstance(group, Group):
|
|
488
|
+
raise ValueError(
|
|
489
|
+
f"groups[{key!r}] must be a Group, got {type(group).__name__}"
|
|
490
|
+
)
|
|
491
|
+
if key != group.name:
|
|
492
|
+
raise ValueError(
|
|
493
|
+
f"groups key {key!r} does not match Group.name {group.name!r}"
|
|
494
|
+
)
|
|
495
|
+
_v.validate_group_name(key)
|
|
496
|
+
materialised[key] = group
|
|
497
|
+
return tuple(sorted(materialised.items()))
|
|
498
|
+
|
|
499
|
+
if isinstance(raw, Iterable):
|
|
500
|
+
materialised = {}
|
|
501
|
+
for group in raw:
|
|
502
|
+
if not isinstance(group, Group):
|
|
503
|
+
raise ValueError(
|
|
504
|
+
f"groups iterable must yield Group instances, got {type(group).__name__}"
|
|
505
|
+
)
|
|
506
|
+
_v.validate_group_name(group.name)
|
|
507
|
+
if group.name in materialised:
|
|
508
|
+
raise ValueError(f"duplicate group name {group.name!r} in iterable")
|
|
509
|
+
materialised[group.name] = group
|
|
510
|
+
return tuple(sorted(materialised.items()))
|
|
511
|
+
|
|
512
|
+
raise ValueError(
|
|
513
|
+
f"groups must be Mapping[str, Group], Iterable[Group], or None; "
|
|
514
|
+
f"got {type(raw).__name__}"
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
@dataclass(frozen=True)
|
|
519
|
+
class MxNLayoutDocument:
|
|
520
|
+
"""A complete MxN layout document. In-memory documents are always
|
|
521
|
+
strict: ``groups`` covers every label any window references.
|
|
522
|
+
"""
|
|
523
|
+
|
|
524
|
+
root: Split
|
|
525
|
+
name: str | None = None
|
|
526
|
+
_groups: tuple[tuple[str, Group], ...] = ()
|
|
527
|
+
version: str = LAYOUT_VERSION
|
|
528
|
+
|
|
529
|
+
def __post_init__(self) -> None:
|
|
530
|
+
if not isinstance(self.root, Split):
|
|
531
|
+
raise ValueError(
|
|
532
|
+
f"root must be a Split, got {type(self.root).__name__}"
|
|
533
|
+
)
|
|
534
|
+
if not isinstance(self._groups, tuple):
|
|
535
|
+
object.__setattr__(self, "_groups", tuple(self._groups))
|
|
536
|
+
|
|
537
|
+
# ---- friendly construction -------------------------------------------
|
|
538
|
+
|
|
539
|
+
@classmethod
|
|
540
|
+
def create(
|
|
541
|
+
cls,
|
|
542
|
+
root: Split,
|
|
543
|
+
*,
|
|
544
|
+
name: str | None = None,
|
|
545
|
+
groups: Mapping[str, Group] | Iterable[Group] | None = None,
|
|
546
|
+
version: str = LAYOUT_VERSION,
|
|
547
|
+
) -> MxNLayoutDocument:
|
|
548
|
+
"""Primary constructor. Always materialises a strict-mode document.
|
|
549
|
+
|
|
550
|
+
Args:
|
|
551
|
+
root: Tree root. Always a Split (matches schema).
|
|
552
|
+
name: Optional preset display label.
|
|
553
|
+
groups: Group registry. ``Mapping[str, Group]`` (key must equal
|
|
554
|
+
``Group.name``), ``Iterable[Group]`` (uniqueness enforced),
|
|
555
|
+
or ``None`` to auto-materialise: every label referenced
|
|
556
|
+
in any window's ``links`` becomes a ``Group`` with
|
|
557
|
+
property defaults.
|
|
558
|
+
"""
|
|
559
|
+
if name is not None and (not isinstance(name, str) or len(name) < 1):
|
|
560
|
+
raise ValueError("document name must be a non-empty string when set; pass None to omit")
|
|
561
|
+
_v.validate_layout_version(version)
|
|
562
|
+
groups_storage = _materialise_groups(root, groups)
|
|
563
|
+
doc = cls(root=root, name=name, _groups=groups_storage, version=version)
|
|
564
|
+
doc.validate()
|
|
565
|
+
return doc
|
|
566
|
+
|
|
567
|
+
# ---- introspection ---------------------------------------------------
|
|
568
|
+
|
|
569
|
+
@property
|
|
570
|
+
def groups(self) -> Mapping[str, Group]:
|
|
571
|
+
"""Read-only ``Mapping`` view; mutations to the returned object do
|
|
572
|
+
not affect the document.
|
|
573
|
+
"""
|
|
574
|
+
return MappingProxyType(dict(self._groups))
|
|
575
|
+
|
|
576
|
+
def windows(self) -> Iterator[LayoutWindow]:
|
|
577
|
+
"""Pre-order iterator over every leaf window in the document."""
|
|
578
|
+
return self.root.windows()
|
|
579
|
+
|
|
580
|
+
def window_ids(self) -> list[str]:
|
|
581
|
+
"""Pre-order list of window ids (the routing identities)."""
|
|
582
|
+
return self.root.window_ids()
|
|
583
|
+
|
|
584
|
+
def find_window(self, id: str) -> LayoutWindow | None:
|
|
585
|
+
"""Return the leaf window with the given id, or ``None`` if the
|
|
586
|
+
document does not contain one.
|
|
587
|
+
"""
|
|
588
|
+
return self.root.find_window(id)
|
|
589
|
+
|
|
590
|
+
@property
|
|
591
|
+
def select_windows(self) -> "MxNWindowSelector[MxNLayoutDocument]":
|
|
592
|
+
"""Entry point for the fluent
|
|
593
|
+
:class:`MxNWindowSelector` filter and bulk-transform API. Selector
|
|
594
|
+
terminals return a fresh :class:`MxNLayoutDocument` (the original
|
|
595
|
+
is left untouched).
|
|
596
|
+
"""
|
|
597
|
+
from ._selector import MxNWindowSelector
|
|
598
|
+
|
|
599
|
+
return MxNWindowSelector(self)
|
|
600
|
+
|
|
601
|
+
# ---- transformations -------------------------------------------------
|
|
602
|
+
|
|
603
|
+
def with_default_ids(
|
|
604
|
+
self,
|
|
605
|
+
*,
|
|
606
|
+
editor_name: str = DEFAULT_EDITOR_NAME,
|
|
607
|
+
bare_id_stem: str = "widget",
|
|
608
|
+
start_index: int = 0,
|
|
609
|
+
) -> MxNLayoutDocument:
|
|
610
|
+
"""Re-number all leaves in pre-order to qualified form.
|
|
611
|
+
|
|
612
|
+
Produces ``f"{editor_name}__{bare_id_stem}{i}"`` for ``i`` starting
|
|
613
|
+
at ``start_index``. Display names (``.name``) are preserved; only
|
|
614
|
+
ids change.
|
|
615
|
+
|
|
616
|
+
WARNING: same caveat as :meth:`LayoutWindow.with_id` -- re-numbering
|
|
617
|
+
an already-published document invalidates persisted references.
|
|
618
|
+
Intended for use on freshly-built or freshly-loaded documents
|
|
619
|
+
prior to PUT.
|
|
620
|
+
"""
|
|
621
|
+
if isinstance(start_index, bool) or not isinstance(start_index, int) or start_index < 0:
|
|
622
|
+
raise ValueError(f"start_index must be a non-negative int, got {start_index!r}")
|
|
623
|
+
|
|
624
|
+
counter = count(start_index)
|
|
625
|
+
|
|
626
|
+
def renumber(node: Split | LayoutWindow) -> Split | LayoutWindow:
|
|
627
|
+
if isinstance(node, LayoutWindow):
|
|
628
|
+
new_id = f"{editor_name}{NAMESPACE_DELIMITER}{bare_id_stem}{next(counter)}"
|
|
629
|
+
_v.validate_window_id(new_id)
|
|
630
|
+
return replace(node, id=new_id)
|
|
631
|
+
new_children = tuple(renumber(c) for c in node.children)
|
|
632
|
+
return replace(node, children=new_children)
|
|
633
|
+
|
|
634
|
+
new_root = renumber(self.root)
|
|
635
|
+
assert isinstance(new_root, Split)
|
|
636
|
+
return replace(self, root=new_root)
|
|
637
|
+
|
|
638
|
+
# ---- JSON I/O -------------------------------------------------------
|
|
639
|
+
|
|
640
|
+
@classmethod
|
|
641
|
+
def from_json(cls, doc: Mapping[str, Any] | str) -> MxNLayoutDocument:
|
|
642
|
+
"""Parse a v2.0 JSON document.
|
|
643
|
+
|
|
644
|
+
Accepts either a parsed mapping or a JSON-string. Up-front version
|
|
645
|
+
check raises ``ValueError`` *before* any structural parsing when
|
|
646
|
+
the document's ``version`` is not :data:`LAYOUT_VERSION`. Lazy-mode
|
|
647
|
+
input (no top-level ``groups``) is materialised to strict eagerly
|
|
648
|
+
during parse -- the in-memory document never represents lazy state.
|
|
649
|
+
"""
|
|
650
|
+
if isinstance(doc, str):
|
|
651
|
+
try:
|
|
652
|
+
doc = json.loads(doc)
|
|
653
|
+
except json.JSONDecodeError as exc:
|
|
654
|
+
raise ValueError(f"document is not valid JSON: {exc}") from exc
|
|
655
|
+
if not isinstance(doc, Mapping):
|
|
656
|
+
raise ValueError(
|
|
657
|
+
f"document must be a Mapping or JSON string, got {type(doc).__name__}"
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
version = doc.get("version")
|
|
661
|
+
if not isinstance(version, str):
|
|
662
|
+
raise ValueError("document is missing a 'version' string field")
|
|
663
|
+
_v.validate_layout_version(version)
|
|
664
|
+
|
|
665
|
+
if "root" not in doc:
|
|
666
|
+
raise ValueError("document is missing the required 'root' field")
|
|
667
|
+
root = _split_from_json(doc["root"], is_root=True)
|
|
668
|
+
|
|
669
|
+
groups: tuple[tuple[str, Group], ...]
|
|
670
|
+
if "groups" in doc:
|
|
671
|
+
raw_groups = doc["groups"]
|
|
672
|
+
if not isinstance(raw_groups, Mapping):
|
|
673
|
+
raise ValueError("'groups' must be an object/Mapping")
|
|
674
|
+
parsed: dict[str, Group] = {}
|
|
675
|
+
for key, raw_entry in raw_groups.items():
|
|
676
|
+
if not isinstance(raw_entry, Mapping):
|
|
677
|
+
raise ValueError(
|
|
678
|
+
f"groups[{key!r}] must be an object, got {type(raw_entry).__name__}"
|
|
679
|
+
)
|
|
680
|
+
_v.validate_group_name(key)
|
|
681
|
+
select_all = raw_entry.get("select_all", True)
|
|
682
|
+
if not isinstance(select_all, bool):
|
|
683
|
+
raise ValueError(
|
|
684
|
+
f"groups[{key!r}].select_all must be a boolean, "
|
|
685
|
+
f"got {type(select_all).__name__}"
|
|
686
|
+
)
|
|
687
|
+
parsed[key] = Group(name=key, select_all=select_all)
|
|
688
|
+
groups = tuple(sorted(parsed.items()))
|
|
689
|
+
else:
|
|
690
|
+
# Lazy mode: materialise referenced labels with property defaults.
|
|
691
|
+
groups = _materialise_groups(root, None)
|
|
692
|
+
|
|
693
|
+
name = doc.get("name")
|
|
694
|
+
if name is not None and (not isinstance(name, str) or len(name) < 1):
|
|
695
|
+
raise ValueError("'name' must be a non-empty string when present")
|
|
696
|
+
|
|
697
|
+
instance = cls(root=root, name=name, _groups=groups, version=version)
|
|
698
|
+
instance.validate()
|
|
699
|
+
return instance
|
|
700
|
+
|
|
701
|
+
def to_json(self) -> dict[str, Any]:
|
|
702
|
+
"""Emit a strict-mode v2.0 JSON document with stable key ordering.
|
|
703
|
+
|
|
704
|
+
Key order follows the schema's example ordering:
|
|
705
|
+
- top-level: ``version``, ``name?``, ``groups``, ``root``
|
|
706
|
+
- per window: ``type``, ``id``, ``name?``, ``view_direction``, ``links``, ``size``
|
|
707
|
+
- per split: ``type``, ``orientation``, ``children``, ``size?``
|
|
708
|
+
``size`` on the document root is always omitted (no parent splitter).
|
|
709
|
+
"""
|
|
710
|
+
out: dict[str, Any] = {"version": self.version}
|
|
711
|
+
if self.name is not None:
|
|
712
|
+
out["name"] = self.name
|
|
713
|
+
out["groups"] = {name: _group_to_json(g) for name, g in self._groups}
|
|
714
|
+
out["root"] = _split_to_json(self.root, is_root=True)
|
|
715
|
+
return out
|
|
716
|
+
|
|
717
|
+
# ---- validation -----------------------------------------------------
|
|
718
|
+
|
|
719
|
+
def validate(self) -> None:
|
|
720
|
+
"""Run cross-document checks on ``self``.
|
|
721
|
+
|
|
722
|
+
Raises ``ValueError`` with a message that names the offending
|
|
723
|
+
element. Per-window structural checks are not re-run here --
|
|
724
|
+
those are enforced once in :meth:`LayoutWindow.create`.
|
|
725
|
+
"""
|
|
726
|
+
_v.validate_layout_version(self.version)
|
|
727
|
+
|
|
728
|
+
seen_ids: set[str] = set()
|
|
729
|
+
for window in self.root.windows():
|
|
730
|
+
if window.id in seen_ids:
|
|
731
|
+
raise ValueError(f"duplicate window id {window.id!r} in document")
|
|
732
|
+
seen_ids.add(window.id)
|
|
733
|
+
|
|
734
|
+
group_names = {name for name, _ in self._groups}
|
|
735
|
+
for name in group_names:
|
|
736
|
+
_v.validate_group_name(name)
|
|
737
|
+
|
|
738
|
+
for window in self.root.windows():
|
|
739
|
+
for dim, value in window._links:
|
|
740
|
+
target = value if isinstance(value, str) else value.group
|
|
741
|
+
if target not in group_names:
|
|
742
|
+
raise ValueError(
|
|
743
|
+
f"window {window.id!r} links {dim!r} to unknown group {target!r}; "
|
|
744
|
+
f"declare it in groups or rely on auto-materialisation"
|
|
745
|
+
)
|
|
746
|
+
|
|
747
|
+
# ---- repr -----------------------------------------------------------
|
|
748
|
+
|
|
749
|
+
def __repr__(self) -> str:
|
|
750
|
+
from ._repr import document_repr
|
|
751
|
+
|
|
752
|
+
return document_repr(self)
|
|
753
|
+
|
|
754
|
+
def _repr_html_(self) -> str:
|
|
755
|
+
from ._repr import document_html
|
|
756
|
+
|
|
757
|
+
return document_html(self)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
# --------------------------------------------------------------------------- #
|
|
761
|
+
# JSON helpers (free functions to keep parse/emit local to the model module)
|
|
762
|
+
# --------------------------------------------------------------------------- #
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def _node_from_json(node: Any) -> Split | LayoutWindow:
|
|
766
|
+
if not isinstance(node, Mapping):
|
|
767
|
+
raise ValueError(f"node must be an object, got {type(node).__name__}")
|
|
768
|
+
node_type = node.get("type")
|
|
769
|
+
if node_type == "split":
|
|
770
|
+
return _split_from_json(node, is_root=False)
|
|
771
|
+
if node_type == "window":
|
|
772
|
+
return _window_from_json(node)
|
|
773
|
+
raise ValueError(f"unknown node type {node_type!r}; expected 'split' or 'window'")
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def _split_from_json(node: Any, *, is_root: bool) -> Split:
|
|
777
|
+
if not isinstance(node, Mapping):
|
|
778
|
+
raise ValueError(f"split must be an object, got {type(node).__name__}")
|
|
779
|
+
if node.get("type") != "split":
|
|
780
|
+
raise ValueError(
|
|
781
|
+
f"split node must have type='split', got type={node.get('type')!r}"
|
|
782
|
+
)
|
|
783
|
+
orientation = node.get("orientation")
|
|
784
|
+
if orientation not in ("horizontal", "vertical"):
|
|
785
|
+
raise ValueError(
|
|
786
|
+
f"split orientation must be 'horizontal' or 'vertical', got {orientation!r}"
|
|
787
|
+
)
|
|
788
|
+
raw_children = node.get("children")
|
|
789
|
+
if not isinstance(raw_children, list) or not raw_children:
|
|
790
|
+
raise ValueError("split must declare a non-empty 'children' array")
|
|
791
|
+
children = tuple(_node_from_json(c) for c in raw_children)
|
|
792
|
+
size = node.get("size", 1)
|
|
793
|
+
return Split(orientation=orientation, children=children, size=size)
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def _window_from_json(node: Mapping[str, Any]) -> LayoutWindow:
|
|
797
|
+
raw_id = node.get("id")
|
|
798
|
+
if not isinstance(raw_id, str):
|
|
799
|
+
raise ValueError("window must declare a string 'id'")
|
|
800
|
+
raw_view = node.get("view_direction")
|
|
801
|
+
if not isinstance(raw_view, str):
|
|
802
|
+
raise ValueError(f"window {raw_id!r} must declare a string 'view_direction'")
|
|
803
|
+
raw_links = node.get("links")
|
|
804
|
+
if not isinstance(raw_links, Mapping):
|
|
805
|
+
raise ValueError(f"window {raw_id!r} must declare a 'links' object")
|
|
806
|
+
raw_name = node.get("name")
|
|
807
|
+
raw_size = node.get("size", 1)
|
|
808
|
+
return LayoutWindow.create(
|
|
809
|
+
id=raw_id,
|
|
810
|
+
view_direction=raw_view,
|
|
811
|
+
name=raw_name,
|
|
812
|
+
links=raw_links,
|
|
813
|
+
size=raw_size,
|
|
814
|
+
)
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def _group_to_json(group: Group) -> dict[str, Any]:
|
|
818
|
+
return {"select_all": group.select_all}
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def _split_to_json(split: Split, *, is_root: bool) -> dict[str, Any]:
|
|
822
|
+
out: dict[str, Any] = {
|
|
823
|
+
"type": "split",
|
|
824
|
+
"orientation": split.orientation,
|
|
825
|
+
"children": [_node_to_json(c) for c in split.children],
|
|
826
|
+
}
|
|
827
|
+
if not is_root:
|
|
828
|
+
out["size"] = split.size
|
|
829
|
+
return out
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def _node_to_json(node: Split | LayoutWindow) -> dict[str, Any]:
|
|
833
|
+
if isinstance(node, Split):
|
|
834
|
+
return _split_to_json(node, is_root=False)
|
|
835
|
+
return _window_to_json(node)
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def _window_to_json(window: LayoutWindow) -> dict[str, Any]:
|
|
839
|
+
out: dict[str, Any] = {"type": "window", "id": window.id}
|
|
840
|
+
if window.name is not None:
|
|
841
|
+
out["name"] = window.name
|
|
842
|
+
out["view_direction"] = window.view_direction.value
|
|
843
|
+
out["links"] = {
|
|
844
|
+
dim: (value if isinstance(value, str) else value.group)
|
|
845
|
+
for dim, value in window._links
|
|
846
|
+
}
|
|
847
|
+
out["size"] = window.size
|
|
848
|
+
return out
|