mitk-python 2026.12rc1__cp314-cp314-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.
Files changed (193) hide show
  1. mitk/MitkCore/MitkDICOMImageIO.dll +0 -0
  2. mitk/MitkCore/MitkDICOMPMIO.dll +0 -0
  3. mitk/MitkCore/MitkDICOMRTIO.dll +0 -0
  4. mitk/MitkCore/MitkDICOMSegIO.dll +0 -0
  5. mitk/MitkCore/MitkIOExt.dll +0 -0
  6. mitk/MitkCore/MitkModelFitIOServices.dll +0 -0
  7. mitk/MitkCore/MitkMultilabelIO.dll +0 -0
  8. mitk/MitkCore/MitkPlanarFigureIO.dll +0 -0
  9. mitk/MitkCore/MitkROIIO.dll +0 -0
  10. mitk/MitkCore/MitkSceneSerializationIO.dll +0 -0
  11. mitk/MitkCore/MitkSegmentationIO.dll +0 -0
  12. mitk/MitkDICOM/MitkCESTIO.dll +0 -0
  13. mitk/MitkModelFit/MitkModelFitModelsServices.dll +0 -0
  14. mitk/MitkModelFit/MitkPharmacokineticModelsServices.dll +0 -0
  15. mitk/__init__.py +78 -0
  16. mitk/mitk.cp314-win_amd64.pyd +0 -0
  17. mitk/mxn/__init__.py +17 -0
  18. mitk/mxn/layout/__init__.py +115 -0
  19. mitk/mxn/layout/_builders.py +239 -0
  20. mitk/mxn/layout/_io.py +66 -0
  21. mitk/mxn/layout/_model.py +1204 -0
  22. mitk/mxn/layout/_presets.py +93 -0
  23. mitk/mxn/layout/_repr.py +205 -0
  24. mitk/mxn/layout/_selector.py +363 -0
  25. mitk/mxn/layout/_validation.py +348 -0
  26. mitk/mxn/layout/_vocabulary.py +100 -0
  27. mitk/property_view.py +123 -0
  28. mitk_python-2026.12rc1.dist-info/DELVEWHEEL +2 -0
  29. mitk_python-2026.12rc1.dist-info/METADATA +67 -0
  30. mitk_python-2026.12rc1.dist-info/RECORD +193 -0
  31. mitk_python-2026.12rc1.dist-info/WHEEL +4 -0
  32. mitk_python-2026.12rc1.dist-info/top_level.txt +1 -0
  33. mitk_python.libs/ITKCommon-5.4.dll +0 -0
  34. mitk_python.libs/ITKIOBMP-5.4.dll +0 -0
  35. mitk_python.libs/ITKIOBioRad-5.4.dll +0 -0
  36. mitk_python.libs/ITKIOBruker-5.4.dll +0 -0
  37. mitk_python.libs/ITKIOGDCM-5.4.dll +0 -0
  38. mitk_python.libs/ITKIOGE-5.4.dll +0 -0
  39. mitk_python.libs/ITKIOGIPL-5.4.dll +0 -0
  40. mitk_python.libs/ITKIOHDF5-5.4.dll +0 -0
  41. mitk_python.libs/ITKIOIPL-5.4.dll +0 -0
  42. mitk_python.libs/ITKIOImageBase-5.4.dll +0 -0
  43. mitk_python.libs/ITKIOJPEG-5.4.dll +0 -0
  44. mitk_python.libs/ITKIOJPEG2000-5.4.dll +0 -0
  45. mitk_python.libs/ITKIOLSM-5.4.dll +0 -0
  46. mitk_python.libs/ITKIOMINC-5.4.dll +0 -0
  47. mitk_python.libs/ITKIOMRC-5.4.dll +0 -0
  48. mitk_python.libs/ITKIOMeta-5.4.dll +0 -0
  49. mitk_python.libs/ITKIONIFTI-5.4.dll +0 -0
  50. mitk_python.libs/ITKIONRRD-5.4.dll +0 -0
  51. mitk_python.libs/ITKIOPNG-5.4.dll +0 -0
  52. mitk_python.libs/ITKIOStimulate-5.4.dll +0 -0
  53. mitk_python.libs/ITKIOTIFF-5.4.dll +0 -0
  54. mitk_python.libs/ITKIOVTK-5.4.dll +0 -0
  55. mitk_python.libs/ITKLabelMap-5.4.dll +0 -0
  56. mitk_python.libs/ITKOptimizers-5.4.dll +0 -0
  57. mitk_python.libs/ITKQuadEdgeMesh-5.4.dll +0 -0
  58. mitk_python.libs/ITKRegionGrowing-5.4.dll +0 -0
  59. mitk_python.libs/ITKSmoothing-5.4.dll +0 -0
  60. mitk_python.libs/ITKStatistics-5.4.dll +0 -0
  61. mitk_python.libs/ITKTransform-5.4.dll +0 -0
  62. mitk_python.libs/MitkAlgorithmsExt.dll +0 -0
  63. mitk_python.libs/MitkCEST.dll +0 -0
  64. mitk_python.libs/MitkContourModel.dll +0 -0
  65. mitk_python.libs/MitkCore.dll +0 -0
  66. mitk_python.libs/MitkCppMicroServices.dll +0 -0
  67. mitk_python.libs/MitkDICOM.dll +0 -0
  68. mitk_python.libs/MitkDICOMPM.dll +0 -0
  69. mitk_python.libs/MitkDICOMQI.dll +0 -0
  70. mitk_python.libs/MitkDataTypesExt.dll +0 -0
  71. mitk_python.libs/MitkLog.dll +0 -0
  72. mitk_python.libs/MitkMapperExt.dll +0 -0
  73. mitk_python.libs/MitkModelFit.dll +0 -0
  74. mitk_python.libs/MitkMultilabel.dll +0 -0
  75. mitk_python.libs/MitkPharmacokinetics.dll +0 -0
  76. mitk_python.libs/MitkPlanarFigure.dll +0 -0
  77. mitk_python.libs/MitkROI.dll +0 -0
  78. mitk_python.libs/MitkRT.dll +0 -0
  79. mitk_python.libs/MitkSceneSerialization.dll +0 -0
  80. mitk_python.libs/MitkSceneSerializationBase.dll +0 -0
  81. mitk_python.libs/MitkSegmentation.dll +0 -0
  82. mitk_python.libs/MitkSurfaceInterpolation.dll +0 -0
  83. mitk_python.libs/MitkVolumeVisualization.dll +0 -0
  84. mitk_python.libs/PocoFoundation.dll +0 -0
  85. mitk_python.libs/PocoZip.dll +0 -0
  86. mitk_python.libs/ann.dll +0 -0
  87. mitk_python.libs/dcmdata.dll +0 -0
  88. mitk_python.libs/dcmfg.dll +0 -0
  89. mitk_python.libs/dcmimage.dll +0 -0
  90. mitk_python.libs/dcmimgle.dll +0 -0
  91. mitk_python.libs/dcmiod.dll +0 -0
  92. mitk_python.libs/dcmpmap.dll +0 -0
  93. mitk_python.libs/dcmrt.dll +0 -0
  94. mitk_python.libs/dcmseg.dll +0 -0
  95. mitk_python.libs/dcmsr.dll +0 -0
  96. mitk_python.libs/gdcmCommon.dll +0 -0
  97. mitk_python.libs/gdcmDICT.dll +0 -0
  98. mitk_python.libs/gdcmDSED.dll +0 -0
  99. mitk_python.libs/gdcmIOD.dll +0 -0
  100. mitk_python.libs/gdcmMSFF.dll +0 -0
  101. mitk_python.libs/gdcmcharls.dll +0 -0
  102. mitk_python.libs/gdcmexpat.dll +0 -0
  103. mitk_python.libs/gdcmjpeg12.dll +0 -0
  104. mitk_python.libs/gdcmjpeg16.dll +0 -0
  105. mitk_python.libs/gdcmjpeg8.dll +0 -0
  106. mitk_python.libs/gdcmopenjp2.dll +0 -0
  107. mitk_python.libs/gdcmzlib.dll +0 -0
  108. mitk_python.libs/itkGrowCut-5.4.dll +0 -0
  109. mitk_python.libs/itkhdf5-shared-5.4.dll +0 -0
  110. mitk_python.libs/itkhdf5_cpp-shared-5.4.dll +0 -0
  111. mitk_python.libs/lz4.dll +0 -0
  112. mitk_python.libs/msvcp140.dll +0 -0
  113. mitk_python.libs/oficonv.dll +0 -0
  114. mitk_python.libs/oflog.dll +0 -0
  115. mitk_python.libs/ofstd.dll +0 -0
  116. mitk_python.libs/tbb12.dll +0 -0
  117. mitk_python.libs/vcomp140.dll +0 -0
  118. mitk_python.libs/vtkCommonCache-9.7.dll +0 -0
  119. mitk_python.libs/vtkCommonColor-9.7.dll +0 -0
  120. mitk_python.libs/vtkCommonComputationalGeometry-9.7.dll +0 -0
  121. mitk_python.libs/vtkCommonCore-9.7.dll +4 -0
  122. mitk_python.libs/vtkCommonDataModel-9.7.dll +0 -0
  123. mitk_python.libs/vtkCommonExecutionModel-9.7.dll +0 -0
  124. mitk_python.libs/vtkCommonMath-9.7.dll +0 -0
  125. mitk_python.libs/vtkCommonMisc-9.7.dll +0 -0
  126. mitk_python.libs/vtkCommonSystem-9.7.dll +0 -0
  127. mitk_python.libs/vtkCommonTransforms-9.7.dll +0 -0
  128. mitk_python.libs/vtkDICOMParser-9.7.dll +0 -0
  129. mitk_python.libs/vtkFiltersCellGrid-9.7.dll +0 -0
  130. mitk_python.libs/vtkFiltersCore-9.7.dll +0 -0
  131. mitk_python.libs/vtkFiltersExtraction-9.7.dll +0 -0
  132. mitk_python.libs/vtkFiltersGeneral-9.7.dll +0 -0
  133. mitk_python.libs/vtkFiltersGeneric-9.7.dll +0 -0
  134. mitk_python.libs/vtkFiltersGeometry-9.7.dll +0 -0
  135. mitk_python.libs/vtkFiltersHybrid-9.7.dll +0 -0
  136. mitk_python.libs/vtkFiltersHyperTree-9.7.dll +0 -0
  137. mitk_python.libs/vtkFiltersModeling-9.7.dll +0 -0
  138. mitk_python.libs/vtkFiltersParallel-9.7.dll +0 -0
  139. mitk_python.libs/vtkFiltersReduction-9.7.dll +0 -0
  140. mitk_python.libs/vtkFiltersSources-9.7.dll +0 -0
  141. mitk_python.libs/vtkFiltersStatistics-9.7.dll +0 -0
  142. mitk_python.libs/vtkFiltersTexture-9.7.dll +0 -0
  143. mitk_python.libs/vtkFiltersVerdict-9.7.dll +0 -0
  144. mitk_python.libs/vtkIOCellGrid-9.7.dll +0 -0
  145. mitk_python.libs/vtkIOCore-9.7.dll +0 -0
  146. mitk_python.libs/vtkIOGeometry-9.7.dll +0 -0
  147. mitk_python.libs/vtkIOHDF-9.7.dll +0 -0
  148. mitk_python.libs/vtkIOImage-9.7.dll +0 -0
  149. mitk_python.libs/vtkIOLegacy-9.7.dll +0 -0
  150. mitk_python.libs/vtkIOPLY-9.7.dll +0 -0
  151. mitk_python.libs/vtkIOXML-9.7.dll +0 -0
  152. mitk_python.libs/vtkIOXMLParser-9.7.dll +0 -0
  153. mitk_python.libs/vtkImagingColor-9.7.dll +0 -0
  154. mitk_python.libs/vtkImagingCore-9.7.dll +0 -0
  155. mitk_python.libs/vtkImagingGeneral-9.7.dll +0 -0
  156. mitk_python.libs/vtkImagingMath-9.7.dll +0 -0
  157. mitk_python.libs/vtkImagingSources-9.7.dll +0 -0
  158. mitk_python.libs/vtkImagingStencil-9.7.dll +0 -0
  159. mitk_python.libs/vtkInteractionStyle-9.7.dll +0 -0
  160. mitk_python.libs/vtkParallelCore-9.7.dll +0 -0
  161. mitk_python.libs/vtkParallelDIY-9.7.dll +0 -0
  162. mitk_python.libs/vtkRenderingAnnotation-9.7.dll +0 -0
  163. mitk_python.libs/vtkRenderingContext2D-9.7.dll +0 -0
  164. mitk_python.libs/vtkRenderingContextOpenGL2-9.7.dll +0 -0
  165. mitk_python.libs/vtkRenderingCore-9.7.dll +0 -0
  166. mitk_python.libs/vtkRenderingFreeType-9.7.dll +0 -0
  167. mitk_python.libs/vtkRenderingHyperTreeGrid-9.7.dll +0 -0
  168. mitk_python.libs/vtkRenderingLabel-9.7.dll +0 -0
  169. mitk_python.libs/vtkRenderingOpenGL2-9.7.dll +0 -0
  170. mitk_python.libs/vtkRenderingUI-9.7.dll +0 -0
  171. mitk_python.libs/vtkRenderingVolume-9.7.dll +0 -0
  172. mitk_python.libs/vtkRenderingVolumeOpenGL2-9.7.dll +0 -0
  173. mitk_python.libs/vtkexpat-9.7.dll +0 -0
  174. mitk_python.libs/vtkfmt-9.7.dll +0 -0
  175. mitk_python.libs/vtkfreetype-9.7.dll +0 -0
  176. mitk_python.libs/vtkglad-9.7.dll +0 -0
  177. mitk_python.libs/vtkhdf5-9.7.dll +0 -0
  178. mitk_python.libs/vtkhdf5_hl-9.7.dll +0 -0
  179. mitk_python.libs/vtkjpeg-9.7.dll +0 -0
  180. mitk_python.libs/vtkjsoncpp-9.7.dll +0 -0
  181. mitk_python.libs/vtkkissfft-9.7.dll +0 -0
  182. mitk_python.libs/vtkloguru-9.7.dll +0 -0
  183. mitk_python.libs/vtklz4-9.7.dll +0 -0
  184. mitk_python.libs/vtklzma-9.7.dll +0 -0
  185. mitk_python.libs/vtkmetaio-9.7.dll +0 -0
  186. mitk_python.libs/vtkpng-9.7.dll +0 -0
  187. mitk_python.libs/vtkpugixml-9.7.dll +0 -0
  188. mitk_python.libs/vtkscn-9.7.dll +0 -0
  189. mitk_python.libs/vtksys-9.7.dll +0 -0
  190. mitk_python.libs/vtktiff-9.7.dll +0 -0
  191. mitk_python.libs/vtktoken-9.7.dll +0 -0
  192. mitk_python.libs/vtkverdict-9.7.dll +0 -0
  193. mitk_python.libs/vtkzlib-9.7.dll +0 -0
@@ -0,0 +1,1204 @@
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 v3.0 schema (`Modules/QtWidgets/resource/mxn-layout-v3.schema.json`).
16
+ All dataclasses are frozen and hashable so callers can use documents as dict
17
+ keys, in sets, or memoise builder output.
18
+
19
+ Storage shapes:
20
+ - ``LayoutWindow._links`` is a ``tuple[tuple[str, LinkValue], ...]`` sorted
21
+ by dimension key so the dataclass remains hashable and equality is
22
+ order-insensitive.
23
+ - ``MxNLayoutDocument._groups`` is a sorted ``tuple[tuple[str, Group], ...]``
24
+ for the same reason.
25
+
26
+ The friendly ``Mapping`` views are exposed via ``links`` / ``groups``
27
+ properties.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ from collections.abc import Iterable, Iterator, Mapping
34
+ from dataclasses import dataclass, replace
35
+ from itertools import count
36
+ from types import MappingProxyType
37
+ from typing import (
38
+ Any,
39
+ Literal,
40
+ TYPE_CHECKING,
41
+ Union,
42
+ )
43
+
44
+ from . import _validation as _v
45
+ from ._vocabulary import (
46
+ DEFAULT_EDITOR_NAME,
47
+ DEFAULT_GROUP_NAME,
48
+ GLOBAL_GROUP_NAME,
49
+ LAYOUT_VERSION,
50
+ NAMESPACE_DELIMITER,
51
+ LinkDimension,
52
+ RenderMode,
53
+ ViewDirection,
54
+ )
55
+
56
+
57
+ if TYPE_CHECKING:
58
+ from ._selector import MxNWindowSelector
59
+
60
+
61
+ _SELECTION = LinkDimension.SELECTION.value
62
+ _TIME = LinkDimension.TIME.value
63
+ _ORIENTATION = LinkDimension.ORIENTATION.value
64
+ _DIMENSION_RANK = {dimension.value: rank for rank, dimension in enumerate(LinkDimension)}
65
+
66
+
67
+ # --------------------------------------------------------------------------- #
68
+ # Group
69
+ # --------------------------------------------------------------------------- #
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Group:
74
+ """Synchronization group entry: state shared by the windows that link to
75
+ the group.
76
+
77
+ ``name`` is the group id, the key in a document's groups;
78
+ ``display_name`` is the optional human-readable label, written as the
79
+ entry's ``name``; ``color`` is an optional hex RGB hue
80
+ (:data:`GROUP_COLOR_PATTERN`) at a CIE76 distance of at least 15 from the
81
+ reserved group's colours, ``#c7c7c7`` and black; the editor would ignore
82
+ a closer one.
83
+
84
+ ``select_all`` is ``None`` when the entry carries no ``select_all`` key.
85
+ The editor then treats a group a selection link names as select-all, a
86
+ group only navigation links name as link-only, and a group no window
87
+ links as a registered, empty group. A link-only group exists only while
88
+ a window links it; it is not one of the editor's groups, so it shows no
89
+ group card and is never the default group. The editor fixes a group's
90
+ role when it loads the document and keeps a registered group, so
91
+ :meth:`MxNWindowSelector.link_to` gives an entry ``select_all=True``
92
+ when a selection link starts or stops naming its group. A declared group
93
+ no window links becomes link-only once only navigation links name it.
94
+ Give a group ``select_all=True`` to keep it registered whatever links it
95
+ gets.
96
+ """
97
+
98
+ name: str
99
+ select_all: bool | None = None
100
+ color: str | None = None
101
+ display_name: str | None = None
102
+
103
+
104
+ DEFAULT_GROUP: Group = Group(DEFAULT_GROUP_NAME, select_all=True)
105
+
106
+
107
+ # --------------------------------------------------------------------------- #
108
+ # Link
109
+ # --------------------------------------------------------------------------- #
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class Link:
114
+ """Link to a group on one dimension, with an optional offset.
115
+
116
+ ``group`` is the target group, written as the link object's ``target``.
117
+ ``offset`` is accepted on slice (an int, in displayed slices), zoom (a
118
+ number > 0, a multiplicative factor) and pan (two numbers, in-plane world
119
+ mm). ``None`` or the identity (slice 0, zoom 1.0, pan (0, 0)) means no
120
+ offset; such a link is stored and written as the bare group name.
121
+ """
122
+
123
+ group: str
124
+ offset: int | float | tuple[float, float] | None = None
125
+
126
+
127
+ # Stored shape of a link: the bare group name, or a `Link` that carries a
128
+ # non-identity offset.
129
+ LinkValue = Union[str, Link]
130
+
131
+ # Accepted at API boundaries (`LayoutWindow.create`, selectors): a bare
132
+ # group name, a `Link`, or a `Group` (whose `name` is used as the target).
133
+ # Normalised to `LinkValue` before storage.
134
+ LinkLike = Union[str, Link, Group]
135
+
136
+
137
+ def _link_target(value: LinkValue) -> str:
138
+ return value if isinstance(value, str) else value.group
139
+
140
+
141
+ def _normalise_link_value(dimension: str, value: LinkLike) -> LinkValue:
142
+ """The stored form of ``value`` as a link on ``dimension``: the target
143
+ checked against the dimension (the reserved group, in any spelling, is
144
+ stored as ``global`` where the dimension accepts it), the offset checked
145
+ and made canonical."""
146
+ if isinstance(value, Link):
147
+ target, offset = value.group, value.offset
148
+ elif isinstance(value, Group):
149
+ target, offset = value.name, None
150
+ elif isinstance(value, str):
151
+ target, offset = value, None
152
+ else:
153
+ raise ValueError(
154
+ f"'links.{dimension}' must be str, Link, or Group, got {type(value).__name__}"
155
+ )
156
+ target = _v.validate_link_target(dimension, target)
157
+ offset = _v.validate_offset(dimension, offset)
158
+ return target if offset is None else Link(target, offset)
159
+
160
+
161
+ def _in_dimension_order(
162
+ links: Iterable[tuple[str, LinkValue]],
163
+ ) -> list[tuple[str, LinkValue]]:
164
+ return sorted(links, key=lambda item: (_DIMENSION_RANK.get(item[0], len(_DIMENSION_RANK)), item[0]))
165
+
166
+
167
+ # --------------------------------------------------------------------------- #
168
+ # LayoutWindow
169
+ # --------------------------------------------------------------------------- #
170
+
171
+
172
+ _DEFAULT_LINKS: tuple[tuple[str, LinkValue], ...] = (
173
+ (_SELECTION, DEFAULT_GROUP_NAME),
174
+ (_TIME, GLOBAL_GROUP_NAME),
175
+ )
176
+
177
+
178
+ def _coerce_view_direction(value: ViewDirection | str) -> ViewDirection:
179
+ if isinstance(value, ViewDirection):
180
+ return value
181
+ if isinstance(value, str):
182
+ return ViewDirection(value)
183
+ raise ValueError(
184
+ f"view_direction must be ViewDirection or str, got {type(value).__name__}"
185
+ )
186
+
187
+
188
+ def _coerce_render_mode(value: RenderMode | str) -> RenderMode:
189
+ if isinstance(value, RenderMode):
190
+ return value
191
+ if isinstance(value, str):
192
+ return RenderMode(value)
193
+ raise ValueError(
194
+ f"render_mode must be RenderMode or str, got {type(value).__name__}"
195
+ )
196
+
197
+
198
+ @dataclass(frozen=True)
199
+ class LayoutWindow:
200
+ """A leaf render-window. Routing identity (``id``) is required and
201
+ schema-pattern checked; ``name`` is an optional free-form display
202
+ label and is omitted from JSON when ``None``.
203
+
204
+ Direct dataclass init is the *private* form: it sorts ``_links`` to
205
+ keep equality order-insensitive but does **not** check the values.
206
+ :meth:`MxNLayoutDocument.validate` checks them before a document is
207
+ written. Always go through :meth:`create` for input from user-controlled
208
+ sources.
209
+ """
210
+
211
+ id: str
212
+ view_direction: ViewDirection
213
+ _links: tuple[tuple[str, LinkValue], ...] = _DEFAULT_LINKS
214
+ name: str | None = None
215
+ size: int = 1
216
+ render_mode: RenderMode = RenderMode.TWO_D
217
+
218
+ def __post_init__(self) -> None:
219
+ # Structural normalisation only -- make storage canonical so that
220
+ # equality and hashing are order-insensitive on the link map.
221
+ # Use object.__setattr__ to write through the frozen dataclass.
222
+ links = tuple(self._links)
223
+ if any(links[i][0] > links[i + 1][0] for i in range(len(links) - 1)):
224
+ links = tuple(sorted(links, key=lambda item: item[0]))
225
+ object.__setattr__(self, "_links", links)
226
+ if isinstance(self.view_direction, str) and not isinstance(
227
+ self.view_direction, ViewDirection
228
+ ):
229
+ object.__setattr__(
230
+ self, "view_direction", ViewDirection(self.view_direction)
231
+ )
232
+ if isinstance(self.render_mode, str) and not isinstance(self.render_mode, RenderMode):
233
+ object.__setattr__(self, "render_mode", RenderMode(self.render_mode))
234
+
235
+ # ---- friendly construction -------------------------------------------
236
+
237
+ @classmethod
238
+ def create(
239
+ cls,
240
+ id: str,
241
+ view_direction: ViewDirection | str,
242
+ *,
243
+ name: str | None = None,
244
+ render_mode: RenderMode | str = RenderMode.TWO_D,
245
+ selection: LinkLike | None = None,
246
+ slice: LinkLike | None = None,
247
+ zoom: LinkLike | None = None,
248
+ pan: LinkLike | None = None,
249
+ crosshair: LinkLike | None = None,
250
+ orientation: LinkLike | None = None,
251
+ windowing: LinkLike | None = None,
252
+ lut: LinkLike | None = None,
253
+ links: Mapping[LinkDimension | str, LinkLike] | None = None,
254
+ size: int = 1,
255
+ ) -> LayoutWindow:
256
+ """Primary, validating constructor.
257
+
258
+ Args:
259
+ id: Routing identity. Must match ``WINDOW_ID_PATTERN`` (qualified form).
260
+ view_direction: ``ViewDirection`` enum or matching string.
261
+ ``free`` requires ``render_mode`` 3D.
262
+ name: Optional human-readable display label. Omitted from JSON
263
+ when ``None``. Tools should pass ``None`` unless authoring
264
+ for humans.
265
+ render_mode: ``RenderMode`` enum or matching string; 2D by default.
266
+ selection, slice, zoom, pan, crosshair, orientation, windowing, lut:
267
+ The link on that dimension, as a group name, a ``Group``, or
268
+ a ``Link`` with an offset (slice, zoom and pan). ``selection``
269
+ defaults to the default group; an omitted navigation keyword
270
+ leaves the window unlinked on that dimension. ``slice`` and
271
+ ``crosshair`` accept :data:`GLOBAL_GROUP_NAME`, which follows
272
+ the application's position.
273
+ links: All links as one mapping from dimension to link. Exclusive
274
+ with the per-dimension keywords; must contain ``selection``.
275
+ size: Splitter weight; only ratios matter. Defaults to 1.
276
+
277
+ Both forms add ``time`` linked to :data:`GLOBAL_GROUP_NAME` when it is
278
+ absent. ``time`` has no keyword because that is its only legal value;
279
+ a mapping may name it only with that target.
280
+ """
281
+ _v.validate_window_id(id)
282
+ _v.validate_window_name(name)
283
+ _v.validate_size(size)
284
+ view_direction = _coerce_view_direction(view_direction)
285
+ render_mode = _coerce_render_mode(render_mode)
286
+ _v.validate_view_for_render_mode(id, view_direction, render_mode)
287
+
288
+ keywords = {
289
+ dimension: value
290
+ for dimension, value in (
291
+ (LinkDimension.SELECTION, selection),
292
+ (LinkDimension.SLICE, slice),
293
+ (LinkDimension.ZOOM, zoom),
294
+ (LinkDimension.PAN, pan),
295
+ (LinkDimension.CROSSHAIR, crosshair),
296
+ (LinkDimension.ORIENTATION, orientation),
297
+ (LinkDimension.WINDOWING, windowing),
298
+ (LinkDimension.LUT, lut),
299
+ )
300
+ if value is not None
301
+ }
302
+ if links is not None and keywords:
303
+ raise ValueError(
304
+ f"pass either 'links' or the per-dimension keywords, not both; got 'links' and "
305
+ f"{', '.join(repr(d.value) for d in keywords)}"
306
+ )
307
+ if links is None:
308
+ keywords.setdefault(LinkDimension.SELECTION, DEFAULT_GROUP)
309
+ links = keywords
310
+
311
+ normalised: dict[str, LinkValue] = {}
312
+ for raw_key, raw_value in links.items():
313
+ key = _v.validate_dimension_key(raw_key)
314
+ normalised[key] = _normalise_link_value(key, raw_value)
315
+ if _SELECTION not in normalised:
316
+ raise ValueError(
317
+ "links must include the required 'selection' dimension "
318
+ "(the format mandates it on every window)"
319
+ )
320
+ normalised.setdefault(_TIME, GLOBAL_GROUP_NAME)
321
+
322
+ return cls(
323
+ id=id,
324
+ view_direction=view_direction,
325
+ _links=tuple(sorted(normalised.items(), key=lambda item: item[0])),
326
+ name=name,
327
+ size=size,
328
+ render_mode=render_mode,
329
+ )
330
+
331
+ # ---- introspection ---------------------------------------------------
332
+
333
+ @property
334
+ def links(self) -> dict[str, LinkValue]:
335
+ """Fresh dict ``{dimension: link_value}`` in ``LinkDimension`` order.
336
+ Mutations to the returned dict do not affect the window. A value is
337
+ the bare group name, or a ``Link`` when the link carries an offset.
338
+ """
339
+ return dict(_in_dimension_order(self._links))
340
+
341
+ @property
342
+ def selection(self) -> str:
343
+ """Group name linked on ``LinkDimension.SELECTION``.
344
+
345
+ Raises ``KeyError`` if a malformed window somehow lacks the selection
346
+ link (impossible for objects produced via :meth:`create`).
347
+ """
348
+ for dim, value in self._links:
349
+ if dim == _SELECTION:
350
+ return _link_target(value)
351
+ raise KeyError("selection link is missing on this window")
352
+
353
+ def linked_to(
354
+ self,
355
+ group: str | Group,
356
+ *,
357
+ dim: LinkDimension | str = LinkDimension.SELECTION,
358
+ ) -> bool:
359
+ """Whether this window is linked to the given group on the given
360
+ dimension. Any spelling of :data:`GLOBAL_GROUP_NAME` names the
361
+ reserved group."""
362
+ target = group.name if isinstance(group, Group) else group
363
+ if _v.names_global_group(target):
364
+ target = GLOBAL_GROUP_NAME
365
+ dim_key = _v.validate_dimension_key(dim)
366
+ for d, value in self._links:
367
+ if d == dim_key:
368
+ return _link_target(value) == target
369
+ return False
370
+
371
+ # ---- transformations -------------------------------------------------
372
+
373
+ def with_link(
374
+ self,
375
+ dimension: LinkDimension | str,
376
+ link: LinkLike,
377
+ ) -> LayoutWindow:
378
+ """Return a copy with the given dimension linked to the given group."""
379
+ dim_key = _v.validate_dimension_key(dimension)
380
+ new_links = dict(self._links)
381
+ new_links[dim_key] = _normalise_link_value(dim_key, link)
382
+ return replace(self, _links=tuple(sorted(new_links.items(), key=lambda item: item[0])))
383
+
384
+ def without_link(self, dimension: LinkDimension | str) -> LayoutWindow:
385
+ """Return a copy without the link on ``dimension``, offset included;
386
+ a window not linked there comes back equal. What an unlinked window
387
+ shows is described at :meth:`MxNWindowSelector.unlink`.
388
+
389
+ Raises ``ValueError`` for ``selection`` and ``time``, which every
390
+ window links. A window does not know the document's groups: a group
391
+ without ``select_all`` that loses its last link here keeps its
392
+ entry, and the editor loads it as an empty group. On a document,
393
+ unlink through :meth:`MxNWindowSelector.unlink`, which drops that
394
+ entry.
395
+ """
396
+ dim_key = _v.validate_unlinkable_dimension(dimension)
397
+ return replace(self, _links=tuple(item for item in self._links if item[0] != dim_key))
398
+
399
+ def with_render_mode(
400
+ self,
401
+ mode: RenderMode | str,
402
+ *,
403
+ view_direction: ViewDirection | str | None = None,
404
+ ) -> LayoutWindow:
405
+ """Return a copy that renders ``mode`` and looks from
406
+ ``view_direction``, or from its current direction when that is
407
+ ``None``. Passing both turns a 2D window into a ``free`` 3D view, or
408
+ a ``free`` one into a 2D window, in one step.
409
+
410
+ The links stay as they are: a 3D window's links on slice, crosshair,
411
+ windowing and lut have no effect until it renders 2D again.
412
+
413
+ Raises ``ValueError`` if the copy would be ``free`` in 2D, so a
414
+ ``free`` window turned 2D needs a ``view_direction``. A ``free``
415
+ window shares an orientation group only with other ``free`` windows;
416
+ that rule spans windows and :meth:`MxNLayoutDocument.validate`
417
+ checks it, so change or unlink the orientation link along with the
418
+ render mode where needed.
419
+ """
420
+ new_mode = _coerce_render_mode(mode)
421
+ new_view = self.view_direction if view_direction is None else _coerce_view_direction(view_direction)
422
+ _v.validate_view_for_render_mode(self.id, new_view, new_mode)
423
+ return replace(self, render_mode=new_mode, view_direction=new_view)
424
+
425
+ def with_id(self, new_id: str) -> LayoutWindow:
426
+ """Return a copy with a new id.
427
+
428
+ WARNING: ids are routing identities; renaming an id that has
429
+ already been served via REST or saved to a session breaks every
430
+ cached reference (persisted session state, REST URL bookmarks,
431
+ per-renderer DataNode property context keys). Safe on in-memory
432
+ documents that have not yet been published.
433
+ """
434
+ _v.validate_window_id(new_id)
435
+ return replace(self, id=new_id)
436
+
437
+ def with_name(self, new_name: str | None) -> LayoutWindow:
438
+ """Return a copy with a new display name (None to clear it).
439
+
440
+ Free of the caveats on :meth:`with_id` -- ``name`` is pure metadata.
441
+ """
442
+ _v.validate_window_name(new_name)
443
+ return replace(self, name=new_name)
444
+
445
+ # ---- repr -----------------------------------------------------------
446
+
447
+ def __repr__(self) -> str:
448
+ from ._repr import window_repr
449
+
450
+ return window_repr(self)
451
+
452
+ def _repr_html_(self) -> str:
453
+ from ._repr import window_html
454
+
455
+ return window_html(self)
456
+
457
+
458
+ # --------------------------------------------------------------------------- #
459
+ # Split
460
+ # --------------------------------------------------------------------------- #
461
+
462
+
463
+ SplitOrientation = Literal["horizontal", "vertical"]
464
+
465
+
466
+ @dataclass(frozen=True)
467
+ class Split:
468
+ """An interior splitter dividing its area among children. Maps to QSplitter."""
469
+
470
+ orientation: SplitOrientation
471
+ children: tuple[Union["Split", LayoutWindow], ...]
472
+ size: int = 1
473
+
474
+ def __post_init__(self) -> None:
475
+ if self.orientation not in ("horizontal", "vertical"):
476
+ raise ValueError(
477
+ f"orientation must be 'horizontal' or 'vertical', got {self.orientation!r}"
478
+ )
479
+ if not isinstance(self.children, tuple):
480
+ object.__setattr__(self, "children", tuple(self.children))
481
+ if not self.children:
482
+ raise ValueError("split.children must contain at least one node (schema minItems: 1)")
483
+ for child in self.children:
484
+ if not isinstance(child, (Split, LayoutWindow)):
485
+ raise ValueError(
486
+ f"split children must be Split or LayoutWindow, got {type(child).__name__}"
487
+ )
488
+ _v.validate_size(self.size)
489
+
490
+ # ---- vararg builders -------------------------------------------------
491
+
492
+ @classmethod
493
+ def horizontal(
494
+ cls,
495
+ *children: "Split | LayoutWindow",
496
+ size: int = 1,
497
+ ) -> Split:
498
+ """Build a left-to-right split from a vararg of child nodes."""
499
+ return cls(orientation="horizontal", children=tuple(children), size=size)
500
+
501
+ @classmethod
502
+ def vertical(
503
+ cls,
504
+ *children: "Split | LayoutWindow",
505
+ size: int = 1,
506
+ ) -> Split:
507
+ """Build a top-to-bottom split from a vararg of child nodes."""
508
+ return cls(orientation="vertical", children=tuple(children), size=size)
509
+
510
+ # ---- tree iteration (pre-order) -------------------------------------
511
+
512
+ def windows(self) -> Iterator[LayoutWindow]:
513
+ """Pre-order iterator over the leaf windows."""
514
+ for child in self.children:
515
+ if isinstance(child, LayoutWindow):
516
+ yield child
517
+ else:
518
+ yield from child.windows()
519
+
520
+ def window_ids(self) -> list[str]:
521
+ """Pre-order list of window ids (routing identities)."""
522
+ return [w.id for w in self.windows()]
523
+
524
+ def splits(self) -> Iterator[Split]:
525
+ """Pre-order iterator over the interior splits, including ``self``."""
526
+ yield self
527
+ for child in self.children:
528
+ if isinstance(child, Split):
529
+ yield from child.splits()
530
+
531
+ def find_window(self, id: str) -> LayoutWindow | None:
532
+ """Return the leaf window with the given id, or ``None`` if no
533
+ such window exists in this subtree.
534
+ """
535
+ for window in self.windows():
536
+ if window.id == id:
537
+ return window
538
+ return None
539
+
540
+ # ---- selector entry point -------------------------------------------
541
+
542
+ @property
543
+ def select_windows(self) -> "MxNWindowSelector[Split]":
544
+ """Entry point for the fluent
545
+ :class:`MxNWindowSelector` filter and bulk-transform API rooted at
546
+ this subtree.
547
+ """
548
+ from ._selector import MxNWindowSelector
549
+
550
+ return MxNWindowSelector(self)
551
+
552
+ # ---- repr -----------------------------------------------------------
553
+
554
+ def __repr__(self) -> str:
555
+ from ._repr import split_repr
556
+
557
+ return split_repr(self)
558
+
559
+ def _repr_html_(self) -> str:
560
+ from ._repr import split_html
561
+
562
+ return split_html(self)
563
+
564
+
565
+ # --------------------------------------------------------------------------- #
566
+ # MxNLayoutDocument
567
+ # --------------------------------------------------------------------------- #
568
+
569
+
570
+ def _referenced_groups(root: Split) -> dict[str, bool]:
571
+ """The groups the windows' links name, in pre-order of first reference,
572
+ each mapped to whether a selection link names it. The reserved group
573
+ takes no entry in a document's groups and is left out."""
574
+ referenced: dict[str, bool] = {}
575
+ for window in root.windows():
576
+ for dim, value in window._links:
577
+ target = _link_target(value)
578
+ if _v.names_global_group(target):
579
+ continue
580
+ referenced[target] = referenced.get(target, False) or dim == _SELECTION
581
+ return referenced
582
+
583
+
584
+ def _link_only_groups(doc: MxNLayoutDocument) -> frozenset[str]:
585
+ """The groups the editor's loader holds as link-only: an entry without
586
+ ``select_all`` that only navigation links name. Such a group exists only
587
+ while a window links it."""
588
+ named = _referenced_groups(doc.root)
589
+ return frozenset(
590
+ name for name, group in doc._groups if group.select_all is None and named.get(name) is False
591
+ )
592
+
593
+
594
+ def _default_group(name: str, *, named_by_selection: bool) -> Group:
595
+ # The editor keeps a group whose entry has `select_all` after its last
596
+ # link is removed, so a group only navigation links name gets no
597
+ # `select_all` and stays link-only, as the editor writes it.
598
+ return Group(name, select_all=True) if named_by_selection else Group(name)
599
+
600
+
601
+ def _materialise_groups(
602
+ root: Split,
603
+ raw: Mapping[str, Group] | Iterable[Group] | None,
604
+ ) -> tuple[tuple[str, Group], ...]:
605
+ """Resolve ``MxNLayoutDocument.create``'s ``groups`` argument to the
606
+ sorted-tuple storage shape, validating consistency.
607
+
608
+ ``None`` -> auto-materialise an entry for every group any window's links
609
+ name (see ``_default_group``).
610
+ """
611
+ if raw is None:
612
+ return tuple(
613
+ sorted(
614
+ (name, _default_group(name, named_by_selection=by_selection))
615
+ for name, by_selection in _referenced_groups(root).items()
616
+ )
617
+ )
618
+
619
+ # `str` / `bytes` are technically `Iterable`, but iterating them
620
+ # yields characters and produces a confusing downstream error.
621
+ # Reject early.
622
+ if isinstance(raw, (str, bytes)):
623
+ raise ValueError(
624
+ f"groups must be Mapping[str, Group], Iterable[Group], or None; "
625
+ f"got {type(raw).__name__}"
626
+ )
627
+
628
+ if isinstance(raw, Mapping):
629
+ materialised = {}
630
+ for key, group in raw.items():
631
+ if not isinstance(group, Group):
632
+ raise ValueError(
633
+ f"groups[{key!r}] must be a Group, got {type(group).__name__}"
634
+ )
635
+ if key != group.name:
636
+ raise ValueError(
637
+ f"groups key {key!r} does not match Group.name {group.name!r}"
638
+ )
639
+ _v.validate_group_name(key)
640
+ materialised[key] = group
641
+ return tuple(sorted(materialised.items()))
642
+
643
+ if isinstance(raw, Iterable):
644
+ materialised = {}
645
+ for group in raw:
646
+ if not isinstance(group, Group):
647
+ raise ValueError(
648
+ f"groups iterable must yield Group instances, got {type(group).__name__}"
649
+ )
650
+ _v.validate_group_name(group.name)
651
+ if group.name in materialised:
652
+ raise ValueError(f"duplicate group name {group.name!r} in iterable")
653
+ materialised[group.name] = group
654
+ return tuple(sorted(materialised.items()))
655
+
656
+ raise ValueError(
657
+ f"groups must be Mapping[str, Group], Iterable[Group], or None; "
658
+ f"got {type(raw).__name__}"
659
+ )
660
+
661
+
662
+ def _validate_window(window: LayoutWindow) -> None:
663
+ """Every rule a single window has to meet."""
664
+ _v.validate_window_id(window.id)
665
+ _v.validate_window_name(window.name)
666
+ _v.validate_size(window.size)
667
+ if not isinstance(window.view_direction, ViewDirection):
668
+ raise ValueError(f"window {window.id!r}: view_direction must be a ViewDirection")
669
+ if not isinstance(window.render_mode, RenderMode):
670
+ raise ValueError(f"window {window.id!r}: render_mode must be a RenderMode")
671
+ _v.validate_view_for_render_mode(window.id, window.view_direction, window.render_mode)
672
+ dimensions = set()
673
+ for dim, value in window._links:
674
+ try:
675
+ key = _v.validate_dimension_key(dim)
676
+ _normalise_link_value(key, value)
677
+ except ValueError as error:
678
+ raise ValueError(f"window {window.id!r}: {error}") from error
679
+ dimensions.add(key)
680
+ if _SELECTION not in dimensions:
681
+ raise ValueError(f"window {window.id!r} is missing the required 'links.selection'")
682
+ if _TIME not in dimensions:
683
+ raise ValueError(
684
+ f"window {window.id!r} is missing the required 'links.time'; every window "
685
+ f"follows the application's time, linked as time: {GLOBAL_GROUP_NAME!r}"
686
+ )
687
+
688
+
689
+ def _validate_orientation_groups(root: Split) -> None:
690
+ """The members of an orientation group share one view direction, so a
691
+ ``free`` window, whose rotation only a 3D camera has, shares an
692
+ orientation group only with other ``free`` windows."""
693
+ members: dict[str, list[LayoutWindow]] = {}
694
+ for window in root.windows():
695
+ for dim, value in window._links:
696
+ if dim == _ORIENTATION:
697
+ members.setdefault(_link_target(value), []).append(window)
698
+ for group, windows in members.items():
699
+ free = next((w for w in windows if w.view_direction is ViewDirection.FREE), None)
700
+ if free is None:
701
+ continue
702
+ two_d = next((w for w in windows if w.render_mode is RenderMode.TWO_D), None)
703
+ if two_d is not None:
704
+ raise ValueError(
705
+ f"window {free.id!r} has view_direction 'free' and window {two_d.id!r} renders "
706
+ f"2D, but both link orientation group {group!r}; a 2D window cannot follow a "
707
+ f"freely rotated 3D view"
708
+ )
709
+ standard = next((w for w in windows if w.view_direction is not ViewDirection.FREE), None)
710
+ if standard is not None:
711
+ raise ValueError(
712
+ f"window {free.id!r} has view_direction 'free' and window {standard.id!r} has "
713
+ f"{standard.view_direction.value!r}, but both link orientation group {group!r}; "
714
+ f"the members of an orientation group share one view direction"
715
+ )
716
+
717
+
718
+ @dataclass(frozen=True)
719
+ class MxNLayoutDocument:
720
+ """A complete MxN layout document. In-memory documents are always
721
+ strict: ``groups`` covers every group any window references, except the
722
+ reserved group, which is never one of them.
723
+ """
724
+
725
+ root: Split
726
+ name: str | None = None
727
+ _groups: tuple[tuple[str, Group], ...] = ()
728
+
729
+ def __post_init__(self) -> None:
730
+ if not isinstance(self.root, Split):
731
+ raise ValueError(
732
+ f"root must be a Split, got {type(self.root).__name__}"
733
+ )
734
+ if not isinstance(self._groups, tuple):
735
+ object.__setattr__(self, "_groups", tuple(self._groups))
736
+
737
+ # ---- friendly construction -------------------------------------------
738
+
739
+ @classmethod
740
+ def create(
741
+ cls,
742
+ root: Split,
743
+ *,
744
+ name: str | None = None,
745
+ groups: Mapping[str, Group] | Iterable[Group] | None = None,
746
+ ) -> MxNLayoutDocument:
747
+ """Primary constructor. Always materialises a strict-mode document.
748
+
749
+ Args:
750
+ root: Tree root. Always a Split (matches schema).
751
+ name: Optional preset display label.
752
+ groups: Group registry. ``Mapping[str, Group]`` (key must equal
753
+ ``Group.name``), ``Iterable[Group]`` (uniqueness enforced),
754
+ or ``None`` to auto-materialise: every group a window's
755
+ links name becomes a ``Group``, with ``select_all=True``
756
+ when a selection link names it and without ``select_all``
757
+ when only navigation links do.
758
+ """
759
+ if name is not None and (not isinstance(name, str) or len(name) < 1):
760
+ raise ValueError("document name must be a non-empty string when set; pass None to omit")
761
+ groups_storage = _materialise_groups(root, groups)
762
+ doc = cls(root=root, name=name, _groups=groups_storage)
763
+ doc.validate()
764
+ return doc
765
+
766
+ # ---- introspection ---------------------------------------------------
767
+
768
+ @property
769
+ def version(self) -> str:
770
+ """The layout version the document is written as:
771
+ :data:`LAYOUT_VERSION`, whatever version it was read from."""
772
+ return LAYOUT_VERSION
773
+
774
+ @property
775
+ def groups(self) -> Mapping[str, Group]:
776
+ """Read-only ``Mapping`` view; mutations to the returned object do
777
+ not affect the document.
778
+ """
779
+ return MappingProxyType(dict(self._groups))
780
+
781
+ def windows(self) -> Iterator[LayoutWindow]:
782
+ """Pre-order iterator over every leaf window in the document."""
783
+ return self.root.windows()
784
+
785
+ def window_ids(self) -> list[str]:
786
+ """Pre-order list of window ids (the routing identities)."""
787
+ return self.root.window_ids()
788
+
789
+ def find_window(self, id: str) -> LayoutWindow | None:
790
+ """Return the leaf window with the given id, or ``None`` if the
791
+ document does not contain one.
792
+ """
793
+ return self.root.find_window(id)
794
+
795
+ @property
796
+ def select_windows(self) -> "MxNWindowSelector[MxNLayoutDocument]":
797
+ """Entry point for the fluent
798
+ :class:`MxNWindowSelector` filter and bulk-transform API. Selector
799
+ terminals return a fresh :class:`MxNLayoutDocument` (the original
800
+ is left untouched).
801
+ """
802
+ from ._selector import MxNWindowSelector
803
+
804
+ return MxNWindowSelector(self)
805
+
806
+ # ---- transformations -------------------------------------------------
807
+
808
+ def with_default_ids(
809
+ self,
810
+ *,
811
+ editor_name: str = DEFAULT_EDITOR_NAME,
812
+ bare_id_stem: str = "widget",
813
+ start_index: int = 0,
814
+ ) -> MxNLayoutDocument:
815
+ """Re-number all leaves in pre-order to qualified form.
816
+
817
+ Produces ``f"{editor_name}__{bare_id_stem}{i}"`` for ``i`` starting
818
+ at ``start_index``. Display names (``.name``) are preserved; only
819
+ ids change.
820
+
821
+ WARNING: same caveat as :meth:`LayoutWindow.with_id` -- re-numbering
822
+ an already-published document invalidates persisted references.
823
+ Intended for use on freshly-built or freshly-loaded documents
824
+ prior to PUT.
825
+ """
826
+ if isinstance(start_index, bool) or not isinstance(start_index, int) or start_index < 0:
827
+ raise ValueError(f"start_index must be a non-negative int, got {start_index!r}")
828
+
829
+ counter = count(start_index)
830
+
831
+ def renumber(node: Split | LayoutWindow) -> Split | LayoutWindow:
832
+ if isinstance(node, LayoutWindow):
833
+ new_id = f"{editor_name}{NAMESPACE_DELIMITER}{bare_id_stem}{next(counter)}"
834
+ _v.validate_window_id(new_id)
835
+ return replace(node, id=new_id)
836
+ new_children = tuple(renumber(c) for c in node.children)
837
+ return replace(node, children=new_children)
838
+
839
+ new_root = renumber(self.root)
840
+ assert isinstance(new_root, Split)
841
+ return replace(self, root=new_root)
842
+
843
+ # ---- JSON I/O -------------------------------------------------------
844
+
845
+ @classmethod
846
+ def from_json(cls, doc: Mapping[str, Any] | str) -> MxNLayoutDocument:
847
+ """Parse a version 3.0 or 2.0 JSON document.
848
+
849
+ Accepts either a parsed mapping or a JSON-string. The version is
850
+ checked before anything else. Each version is held to its closed
851
+ schema, except that a ``time``, ``slice`` or ``crosshair`` link may
852
+ name the reserved group in any spelling, as the editor's loader
853
+ allows, and is stored as ``global``. A 2.0 document is upgraded in
854
+ memory (every window gains ``time`` linked to the reserved group)
855
+ and written as 3.0. Lazy-mode
856
+ input (no top-level ``groups``) is materialised to strict eagerly
857
+ during parse -- the in-memory document never represents lazy state.
858
+ """
859
+ if isinstance(doc, str):
860
+ try:
861
+ doc = json.loads(doc)
862
+ except json.JSONDecodeError as exc:
863
+ raise ValueError(f"document is not valid JSON: {exc}") from exc
864
+ if not isinstance(doc, Mapping):
865
+ raise ValueError(
866
+ f"document must be a Mapping or JSON string, got {type(doc).__name__}"
867
+ )
868
+
869
+ version = doc.get("version")
870
+ if not isinstance(version, str):
871
+ raise ValueError("document is missing a 'version' string field")
872
+ _v.validate_layout_version(version)
873
+ shape = _INPUT_SHAPES[version]
874
+
875
+ # The raw shape is checked before any object is built, so that the
876
+ # defaults of `LayoutWindow.create` cannot repair a refused input.
877
+ _check_keys(doc, _TOP_LEVEL_KEYS, "document")
878
+ if "root" not in doc:
879
+ raise ValueError("document is missing the required 'root' field")
880
+ root = _split_from_json(doc["root"], shape)
881
+
882
+ if "groups" in doc:
883
+ groups = _groups_from_json(doc["groups"], shape)
884
+ else:
885
+ groups = _materialise_groups(root, None)
886
+
887
+ name = doc.get("name")
888
+ if "name" in doc and (not isinstance(name, str) or len(name) < 1):
889
+ raise ValueError("'name' must be a non-empty string when present")
890
+
891
+ instance = cls(root=root, name=name, _groups=groups)
892
+ instance.validate()
893
+ return instance
894
+
895
+ def to_json(self) -> dict[str, Any]:
896
+ """Emit a strict-mode 3.0 JSON document with stable key ordering.
897
+
898
+ Runs :meth:`validate` first, so a document the editor's loader would
899
+ refuse is never written, except for window ids without the loading
900
+ editor's prefix, which only that editor can check.
901
+
902
+ Key order:
903
+ - top-level: ``version``, ``name?``, ``groups``, ``root``
904
+ - per window: ``type``, ``id``, ``name?``, ``view_direction``,
905
+ ``render_mode?`` (only 3D), ``links``, ``size``
906
+ - per split: ``type``, ``orientation``, ``children``, ``size?``
907
+ - links in ``LinkDimension`` order
908
+ ``size`` on the document root is always omitted (no parent splitter).
909
+ """
910
+ self.validate()
911
+ out: dict[str, Any] = {"version": LAYOUT_VERSION}
912
+ if self.name is not None:
913
+ out["name"] = self.name
914
+ out["groups"] = {name: _group_to_json(g) for name, g in self._groups}
915
+ out["root"] = _split_to_json(self.root, is_root=True)
916
+ return out
917
+
918
+ # ---- validation -----------------------------------------------------
919
+
920
+ def validate(self) -> None:
921
+ """Check every rule for which the editor's loader refuses a
922
+ document, except the window-id prefix.
923
+
924
+ The loader also refuses window ids that do not start with its own
925
+ editor name and ``__``; the DSL knows no editor and leaves that check
926
+ to it.
927
+
928
+ Raises ``ValueError`` with a message that names the offending
929
+ element. Runs on construction through :meth:`create` and
930
+ :meth:`from_json` and again in :meth:`to_json`, which catches what a
931
+ selector update or direct dataclass init put together.
932
+ """
933
+ seen_ids: set[str] = set()
934
+ for window in self.root.windows():
935
+ _validate_window(window)
936
+ if window.id in seen_ids:
937
+ raise ValueError(f"duplicate window id {window.id!r} in document")
938
+ seen_ids.add(window.id)
939
+
940
+ group_names: set[str] = set()
941
+ for key, group in self._groups:
942
+ _v.validate_group_name(key)
943
+ if not isinstance(group, Group) or group.name != key:
944
+ raise ValueError(f"groups[{key!r}] must be a Group named {key!r}")
945
+ _v.validate_group_entry(key, group.select_all, group.color, group.display_name)
946
+ group_names.add(key)
947
+
948
+ for window in self.root.windows():
949
+ for dim, value in window._links:
950
+ target = _link_target(value)
951
+ if not _v.names_global_group(target) and target not in group_names:
952
+ raise ValueError(
953
+ f"window {window.id!r} links {dim!r} to unknown group {target!r}; "
954
+ f"declare it in groups or rely on auto-materialisation"
955
+ )
956
+
957
+ _validate_orientation_groups(self.root)
958
+
959
+ # ---- repr -----------------------------------------------------------
960
+
961
+ def __repr__(self) -> str:
962
+ from ._repr import document_repr
963
+
964
+ return document_repr(self)
965
+
966
+ def _repr_html_(self) -> str:
967
+ from ._repr import document_html
968
+
969
+ return document_html(self)
970
+
971
+
972
+ # --------------------------------------------------------------------------- #
973
+ # JSON helpers (free functions to keep parse/emit local to the model module)
974
+ # --------------------------------------------------------------------------- #
975
+
976
+
977
+ @dataclass(frozen=True)
978
+ class _InputShape:
979
+ """What a document of one version may contain beyond the common parts."""
980
+
981
+ is_v3: bool
982
+ window_keys: frozenset[str]
983
+ group_entry_keys: frozenset[str]
984
+
985
+
986
+ _TOP_LEVEL_KEYS = frozenset({"version", "name", "groups", "root"})
987
+ _SPLIT_KEYS = frozenset({"type", "orientation", "size", "children"})
988
+ _LINK_OBJECT_KEYS = frozenset({"target", "offset"})
989
+ _V2_WINDOW_KEYS = frozenset({"type", "id", "name", "size", "view_direction", "links"})
990
+ _INPUT_SHAPES = {
991
+ "2.0": _InputShape(
992
+ is_v3=False,
993
+ window_keys=_V2_WINDOW_KEYS,
994
+ group_entry_keys=frozenset({"select_all"}),
995
+ ),
996
+ "3.0": _InputShape(
997
+ is_v3=True,
998
+ window_keys=_V2_WINDOW_KEYS | {"render_mode"},
999
+ group_entry_keys=frozenset({"select_all", "color", "name"}),
1000
+ ),
1001
+ }
1002
+
1003
+
1004
+ def _check_keys(node: Mapping[str, Any], allowed: frozenset[str], where: str) -> None:
1005
+ for key in node:
1006
+ if key not in allowed:
1007
+ raise ValueError(f"{where} has unknown key {key!r}")
1008
+
1009
+
1010
+ def _node_from_json(node: Any, shape: _InputShape) -> Split | LayoutWindow:
1011
+ if not isinstance(node, Mapping):
1012
+ raise ValueError(f"node must be an object, got {type(node).__name__}")
1013
+ node_type = node.get("type")
1014
+ if node_type == "split":
1015
+ return _split_from_json(node, shape)
1016
+ if node_type == "window":
1017
+ return _window_from_json(node, shape)
1018
+ raise ValueError(f"unknown node type {node_type!r}; expected 'split' or 'window'")
1019
+
1020
+
1021
+ def _split_from_json(node: Any, shape: _InputShape) -> Split:
1022
+ if not isinstance(node, Mapping):
1023
+ raise ValueError(f"split must be an object, got {type(node).__name__}")
1024
+ if node.get("type") != "split":
1025
+ raise ValueError(
1026
+ f"split node must have type='split', got type={node.get('type')!r}"
1027
+ )
1028
+ _check_keys(node, _SPLIT_KEYS, "split")
1029
+ orientation = node.get("orientation")
1030
+ if orientation not in ("horizontal", "vertical"):
1031
+ raise ValueError(
1032
+ f"split orientation must be 'horizontal' or 'vertical', got {orientation!r}"
1033
+ )
1034
+ raw_children = node.get("children")
1035
+ if not isinstance(raw_children, list) or not raw_children:
1036
+ raise ValueError("split must declare a non-empty 'children' array")
1037
+ children = tuple(_node_from_json(c, shape) for c in raw_children)
1038
+ size = node.get("size", 1)
1039
+ return Split(orientation=orientation, children=children, size=size)
1040
+
1041
+
1042
+ def _links_from_json(window_id: str, raw_links: Mapping[str, Any], shape: _InputShape) -> dict[str, Any]:
1043
+ if not shape.is_v3:
1044
+ for key in raw_links:
1045
+ # The DSL of v2026.06 wrote such keys into 2.0 files. Relabelling
1046
+ # a file as 3.0 would switch on a link the editor ignores in 2.0,
1047
+ # so the message asks for deleting it instead.
1048
+ if key != _SELECTION:
1049
+ raise ValueError(
1050
+ f"window {window_id!r}: a version '2.0' document links only 'selection', and "
1051
+ f"the editor ignores 'links.{key}' in it; delete the link, and its group's "
1052
+ f"entry if no other link names it"
1053
+ )
1054
+ if not isinstance(raw_links.get(_SELECTION), str):
1055
+ raise ValueError(
1056
+ f"window {window_id!r}: 'links.selection' of a version '2.0' document must be a "
1057
+ f"group-name string"
1058
+ )
1059
+ return dict(raw_links)
1060
+
1061
+ parsed: dict[str, Any] = {}
1062
+ for key, raw in raw_links.items():
1063
+ try:
1064
+ _v.validate_dimension_key(key)
1065
+ except ValueError as error:
1066
+ raise ValueError(f"window {window_id!r}: {error}") from error
1067
+ if isinstance(raw, str):
1068
+ parsed[key] = raw
1069
+ continue
1070
+ if not isinstance(raw, Mapping):
1071
+ raise ValueError(
1072
+ f"window {window_id!r}: 'links.{key}' is neither a group-name string nor a link object"
1073
+ )
1074
+ for modifier in raw:
1075
+ if modifier not in _LINK_OBJECT_KEYS:
1076
+ raise ValueError(
1077
+ f"window {window_id!r} has unknown modifier {modifier!r} on 'links.{key}'"
1078
+ )
1079
+ if "target" not in raw:
1080
+ raise ValueError(f"window {window_id!r}: 'links.{key}' object has no 'target'")
1081
+ if "offset" in raw and raw["offset"] is None:
1082
+ raise ValueError(f"window {window_id!r}: 'links.{key}' offset must not be null")
1083
+ parsed[key] = Link(raw["target"], raw.get("offset"))
1084
+ if _TIME not in parsed:
1085
+ raise ValueError(
1086
+ f"window {window_id!r} is missing the required 'links.time'; every window follows "
1087
+ f"the application's time, written as \"time\": {GLOBAL_GROUP_NAME!r}"
1088
+ )
1089
+ return parsed
1090
+
1091
+
1092
+ def _window_from_json(node: Mapping[str, Any], shape: _InputShape) -> LayoutWindow:
1093
+ raw_id = node.get("id")
1094
+ if not isinstance(raw_id, str):
1095
+ raise ValueError("window must declare a string 'id'")
1096
+ if not shape.is_v3 and "render_mode" in node:
1097
+ raise ValueError(
1098
+ f"window {raw_id!r} has a 'render_mode', which requires a version '3.0' document"
1099
+ )
1100
+ _check_keys(node, shape.window_keys, f"window {raw_id!r}")
1101
+ raw_view = node.get("view_direction")
1102
+ if not isinstance(raw_view, str):
1103
+ raise ValueError(f"window {raw_id!r} must declare a string 'view_direction'")
1104
+ if not shape.is_v3 and raw_view == ViewDirection.FREE.value:
1105
+ raise ValueError(
1106
+ f"window {raw_id!r} has view_direction 'free', which requires a version '3.0' document"
1107
+ )
1108
+ for key in ("name", "render_mode"):
1109
+ if key in node and not isinstance(node[key], str):
1110
+ raise ValueError(f"window {raw_id!r}: {key!r} must be a string when present")
1111
+ raw_links = node.get("links")
1112
+ if not isinstance(raw_links, Mapping):
1113
+ raise ValueError(f"window {raw_id!r} must declare a 'links' object")
1114
+ links = _links_from_json(raw_id, raw_links, shape)
1115
+ try:
1116
+ return LayoutWindow.create(
1117
+ id=raw_id,
1118
+ view_direction=raw_view,
1119
+ name=node.get("name"),
1120
+ render_mode=node.get("render_mode", RenderMode.TWO_D),
1121
+ links=links,
1122
+ size=node.get("size", 1),
1123
+ )
1124
+ except ValueError as error:
1125
+ if f"window {raw_id!r}" in str(error):
1126
+ raise
1127
+ raise ValueError(f"window {raw_id!r}: {error}") from error
1128
+
1129
+
1130
+ def _groups_from_json(raw_groups: Any, shape: _InputShape) -> tuple[tuple[str, Group], ...]:
1131
+ if not isinstance(raw_groups, Mapping):
1132
+ raise ValueError("'groups' must be an object/Mapping")
1133
+ parsed: dict[str, Group] = {}
1134
+ for key, entry in raw_groups.items():
1135
+ _v.validate_group_name(key)
1136
+ if not isinstance(entry, Mapping):
1137
+ raise ValueError(
1138
+ f"groups[{key!r}] must be an object, got {type(entry).__name__}"
1139
+ )
1140
+ _check_keys(entry, shape.group_entry_keys, f"groups[{key!r}]")
1141
+ for field, value in entry.items():
1142
+ # `None` stands for an absent key in `Group`, so an explicit null
1143
+ # would otherwise pass as absent.
1144
+ if value is None:
1145
+ raise ValueError(f"groups[{key!r}].{field} must not be null; omit it instead")
1146
+ group = Group(
1147
+ name=key,
1148
+ select_all=entry.get("select_all"),
1149
+ color=entry.get("color"),
1150
+ display_name=entry.get("name"),
1151
+ )
1152
+ _v.validate_group_entry(key, group.select_all, group.color, group.display_name)
1153
+ parsed[key] = group
1154
+ return tuple(sorted(parsed.items()))
1155
+
1156
+
1157
+ def _group_to_json(group: Group) -> dict[str, Any]:
1158
+ out: dict[str, Any] = {}
1159
+ if group.select_all is not None:
1160
+ out["select_all"] = group.select_all
1161
+ if group.color is not None:
1162
+ out["color"] = group.color
1163
+ if group.display_name is not None:
1164
+ out["name"] = group.display_name
1165
+ return out
1166
+
1167
+
1168
+ def _split_to_json(split: Split, *, is_root: bool) -> dict[str, Any]:
1169
+ out: dict[str, Any] = {
1170
+ "type": "split",
1171
+ "orientation": split.orientation,
1172
+ "children": [_node_to_json(c) for c in split.children],
1173
+ }
1174
+ if not is_root:
1175
+ out["size"] = split.size
1176
+ return out
1177
+
1178
+
1179
+ def _node_to_json(node: Split | LayoutWindow) -> dict[str, Any]:
1180
+ if isinstance(node, Split):
1181
+ return _split_to_json(node, is_root=False)
1182
+ return _window_to_json(node)
1183
+
1184
+
1185
+ def _link_to_json(dimension: str, value: LinkValue) -> str | dict[str, Any]:
1186
+ canonical = _normalise_link_value(dimension, value)
1187
+ if isinstance(canonical, str):
1188
+ return canonical
1189
+ offset = canonical.offset
1190
+ return {"target": canonical.group, "offset": list(offset) if isinstance(offset, tuple) else offset}
1191
+
1192
+
1193
+ def _window_to_json(window: LayoutWindow) -> dict[str, Any]:
1194
+ out: dict[str, Any] = {"type": "window", "id": window.id}
1195
+ if window.name is not None:
1196
+ out["name"] = window.name
1197
+ out["view_direction"] = window.view_direction.value
1198
+ if window.render_mode is RenderMode.THREE_D:
1199
+ out["render_mode"] = window.render_mode.value
1200
+ out["links"] = {
1201
+ dim: _link_to_json(dim, value) for dim, value in _in_dimension_order(window._links)
1202
+ }
1203
+ out["size"] = window.size
1204
+ return out