pythonnative 0.19.0__py3-none-any.whl → 0.21.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,272 @@
1
+ """Embedded CPython runtime acquisition for iOS builds.
2
+
3
+ iOS apps can't rely on a system Python, so PythonNative bundles a copy of
4
+ CPython built for iOS by the excellent
5
+ [Python-Apple-support](https://github.com/beeware/Python-Apple-support)
6
+ project. This module downloads the pinned release asset, verifies it,
7
+ extracts it once (cached under the build directory), and exposes the
8
+ paths the [`ios`][pythonnative.project.ios] configurator needs:
9
+ ``Python.xcframework``, the simulator ``Python.framework``, the standard
10
+ library, and the simulator headers/static lib.
11
+
12
+ Android doesn't need any of this — Chaquopy ships its own CPython via
13
+ Gradle — so there's no Android equivalent here.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import tarfile
22
+ import urllib.request
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Callable, List, Optional
26
+
27
+ # Pinned, checksum-verified asset for the supported iOS Python version.
28
+ _PINNED_ASSETS = {
29
+ "3.11": (
30
+ "Python-3.11-iOS-support.b7.tar.gz",
31
+ "2b7d8589715b9890e8dd7e1bce91c210bb5287417e17b9af120fc577675ed28e",
32
+ ),
33
+ }
34
+
35
+ _RELEASES_API = "https://api.github.com/repos/beeware/Python-Apple-support/releases?per_page=100"
36
+ _USER_AGENT = "pythonnative-cli"
37
+
38
+ Logger = Callable[[str], None]
39
+
40
+
41
+ @dataclass
42
+ class IOSRuntime:
43
+ """Resolved paths to an extracted iOS CPython support package.
44
+
45
+ Attributes:
46
+ python_version: The CPython ``major.minor`` version.
47
+ xcframework_dir: Path to ``Python.xcframework``.
48
+ simulator_framework: Path to the simulator-slice
49
+ ``Python.framework`` (embedded into the simulator ``.app``).
50
+ stdlib_dir: Path to the simulator standard library directory.
51
+ simulator_headers: Path to the simulator-slice ``Headers``
52
+ directory (used when the project links the static lib).
53
+ simulator_static_lib: Path to the simulator ``libPythonX.Y.a``.
54
+ device_framework: Path to the device-slice ``Python.framework``
55
+ (embedded when archiving for a real device).
56
+ device_stdlib: Path to the device standard library directory.
57
+ """
58
+
59
+ python_version: str
60
+ xcframework_dir: Path
61
+ simulator_framework: Optional[Path]
62
+ stdlib_dir: Optional[Path]
63
+ simulator_headers: Optional[Path]
64
+ simulator_static_lib: Optional[Path]
65
+ device_framework: Optional[Path] = None
66
+ device_stdlib: Optional[Path] = None
67
+
68
+ def framework_for(self, destination: str) -> Optional[Path]:
69
+ """Return the ``Python.framework`` for a build destination.
70
+
71
+ Args:
72
+ destination: ``"simulator"`` or ``"device"``.
73
+
74
+ Returns:
75
+ The matching framework path, or ``None`` if unavailable.
76
+ """
77
+ return self.device_framework if destination == "device" else self.simulator_framework
78
+
79
+ def stdlib_for(self, destination: str) -> Optional[Path]:
80
+ """Return the standard library directory for a build destination.
81
+
82
+ Args:
83
+ destination: ``"simulator"`` or ``"device"``.
84
+
85
+ Returns:
86
+ The matching stdlib path, or ``None`` if unavailable.
87
+ """
88
+ return self.device_stdlib if destination == "device" else self.stdlib_dir
89
+
90
+
91
+ def _github_json(url: str) -> object:
92
+ headers = {"User-Agent": _USER_AGENT}
93
+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
94
+ if token:
95
+ headers["Authorization"] = f"Bearer {token}"
96
+ req = urllib.request.Request(url, headers=headers)
97
+ with urllib.request.urlopen(req) as response:
98
+ return json.loads(response.read().decode("utf-8"))
99
+
100
+
101
+ def resolve_asset_url(python_version: str, preferred_name: Optional[str] = None) -> Optional[str]:
102
+ """Resolve a download URL for a Python-Apple-support iOS release asset.
103
+
104
+ Prefers an exact ``preferred_name`` match across all releases, then
105
+ falls back to the newest asset whose name contains
106
+ ``Python-<version>-iOS-support`` and ends in ``.tar.gz``.
107
+
108
+ Args:
109
+ python_version: CPython ``major.minor`` (e.g., ``"3.11"``).
110
+ preferred_name: Exact asset filename to prefer.
111
+
112
+ Returns:
113
+ A ``browser_download_url``, or ``None`` if resolution fails.
114
+ """
115
+ try:
116
+ releases = _github_json(_RELEASES_API)
117
+ except Exception:
118
+ return None
119
+ if not isinstance(releases, list):
120
+ return None
121
+
122
+ if preferred_name:
123
+ for release in releases:
124
+ for asset in release.get("assets", []) or []:
125
+ if asset.get("name") == preferred_name:
126
+ return asset.get("browser_download_url")
127
+
128
+ needle = f"Python-{python_version}-iOS-support"
129
+ for release in releases:
130
+ for asset in release.get("assets", []) or []:
131
+ name = asset.get("name") or ""
132
+ if needle in name and name.endswith(".tar.gz"):
133
+ return asset.get("browser_download_url")
134
+ return None
135
+
136
+
137
+ def _sha256(path: Path) -> str:
138
+ digest = hashlib.sha256()
139
+ with open(path, "rb") as handle:
140
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
141
+ digest.update(chunk)
142
+ return digest.hexdigest()
143
+
144
+
145
+ def _safe_extract(tar_path: Path, dest: Path) -> None:
146
+ """Extract a tarball, refusing entries that escape ``dest``."""
147
+ dest = dest.resolve()
148
+ with tarfile.open(tar_path, "r:gz") as tar:
149
+ members = tar.getmembers()
150
+ for member in members:
151
+ target = (dest / member.name).resolve()
152
+ if not str(target).startswith(str(dest)):
153
+ raise RuntimeError(f"Refusing to extract unsafe path: {member.name}")
154
+ # ``filter='data'`` (3.12+) blocks unsafe members; older Pythons
155
+ # fall back to the manual check above.
156
+ try:
157
+ tar.extractall(dest, filter="data")
158
+ except TypeError:
159
+ tar.extractall(dest)
160
+
161
+
162
+ def _first_existing(candidates: List[Path]) -> Optional[Path]:
163
+ for candidate in candidates:
164
+ if candidate.exists():
165
+ return candidate
166
+ return None
167
+
168
+
169
+ def _locate_runtime(extract_root: Path, python_version: str) -> IOSRuntime:
170
+ xc_candidates = [
171
+ extract_root / "Python.xcframework",
172
+ extract_root / "support" / "Python.xcframework",
173
+ ]
174
+ xcframework = _first_existing(xc_candidates)
175
+ if xcframework is None:
176
+ raise RuntimeError("Python.xcframework not found in extracted Python-Apple-support package.")
177
+
178
+ sim_slice = xcframework / "ios-arm64_x86_64-simulator"
179
+ simulator_framework = _first_existing([sim_slice / "Python.framework"])
180
+ stdlib_dir = _first_existing([sim_slice / "lib" / f"python{python_version}"])
181
+ simulator_headers = _first_existing([sim_slice / "Headers"])
182
+ simulator_static_lib = _first_existing(
183
+ [
184
+ sim_slice / f"libPython{python_version}.a",
185
+ sim_slice / "libpython.a",
186
+ ]
187
+ )
188
+
189
+ device_slice = xcframework / "ios-arm64"
190
+ device_framework = _first_existing([device_slice / "Python.framework"])
191
+ device_stdlib = _first_existing([device_slice / "lib" / f"python{python_version}"])
192
+
193
+ return IOSRuntime(
194
+ python_version=python_version,
195
+ xcframework_dir=xcframework,
196
+ simulator_framework=simulator_framework,
197
+ stdlib_dir=stdlib_dir,
198
+ simulator_headers=simulator_headers,
199
+ simulator_static_lib=simulator_static_lib,
200
+ device_framework=device_framework,
201
+ device_stdlib=device_stdlib,
202
+ )
203
+
204
+
205
+ def prepare_ios_runtime(
206
+ cache_dir: Path,
207
+ python_version: str = "3.11",
208
+ *,
209
+ log: Optional[Logger] = None,
210
+ ) -> IOSRuntime:
211
+ """Download (if needed), verify, and extract the iOS CPython package.
212
+
213
+ The download and extraction are cached under ``cache_dir`` so repeat
214
+ builds are fast. For the pinned version the tarball checksum is
215
+ verified; for other versions the checksum is skipped with a warning.
216
+
217
+ Args:
218
+ cache_dir: Directory to store downloads and extractions in.
219
+ python_version: CPython ``major.minor`` to fetch.
220
+ log: Optional callback for progress messages.
221
+
222
+ Returns:
223
+ A resolved [`IOSRuntime`][pythonnative.project.runtime_assets.IOSRuntime].
224
+
225
+ Raises:
226
+ RuntimeError: If the asset URL can't be resolved, the checksum
227
+ doesn't match, or the package layout is unexpected.
228
+ """
229
+ emit: Logger = log or (lambda _message: None)
230
+ cache_dir.mkdir(parents=True, exist_ok=True)
231
+
232
+ pinned = _PINNED_ASSETS.get(python_version)
233
+ preferred_name = pinned[0] if pinned else None
234
+ expected_sha = pinned[1] if pinned else None
235
+
236
+ extract_root = cache_dir / f"python-{python_version}"
237
+ if extract_root.is_dir():
238
+ try:
239
+ return _locate_runtime(extract_root, python_version)
240
+ except RuntimeError:
241
+ # Stale/partial extraction — re-extract below.
242
+ pass
243
+
244
+ url = resolve_asset_url(python_version, preferred_name=preferred_name)
245
+ if not url:
246
+ raise RuntimeError(
247
+ f"Could not resolve a Python-Apple-support iOS asset for Python {python_version}. "
248
+ "Check your network connection or set GITHUB_TOKEN to avoid rate limits."
249
+ )
250
+
251
+ tar_path = cache_dir / os.path.basename(url)
252
+ if not tar_path.exists():
253
+ emit(f"Downloading embedded Python runtime ({python_version} iOS): {os.path.basename(url)}")
254
+ req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
255
+ with urllib.request.urlopen(req) as response, open(tar_path, "wb") as handle:
256
+ handle.write(response.read())
257
+
258
+ if expected_sha:
259
+ actual = _sha256(tar_path)
260
+ if actual != expected_sha:
261
+ tar_path.unlink(missing_ok=True)
262
+ raise RuntimeError(
263
+ f"Checksum mismatch for {tar_path.name}: expected {expected_sha}, got {actual}. "
264
+ "The download may be corrupt; re-run to try again."
265
+ )
266
+ else:
267
+ emit(f"Warning: no pinned checksum for Python {python_version}; skipping verification.")
268
+
269
+ emit("Extracting embedded Python runtime...")
270
+ extract_root.mkdir(parents=True, exist_ok=True)
271
+ _safe_extract(tar_path, extract_root)
272
+ return _locate_runtime(extract_root, python_version)
@@ -30,7 +30,7 @@ Supports:
30
30
 
31
31
  import os
32
32
  import sys
33
- from typing import Any, List, Optional, Tuple
33
+ from typing import Any, Dict, List, Optional, Tuple
34
34
 
35
35
  from .element import Element
36
36
  from .layout import LayoutNode, calculate_layout, extract_layout_style
@@ -106,19 +106,44 @@ class VNode:
106
106
  or an iOS `UIView`). May be `None` for purely virtual
107
107
  wrappers such as providers and error boundaries.
108
108
  children: Ordered list of child `VNode` instances.
109
+ parent: The owning `VNode`, or `None` for the tree root. Used
110
+ by local (component-scoped) re-renders to bubble a changed
111
+ native view up to the nearest native container.
109
112
  hook_state: The component's
110
113
  [`HookState`][pythonnative.hooks.HookState] when the node
111
114
  wraps a function component, otherwise `None`.
115
+ mounted: `False` once the node has been destroyed, so stale
116
+ entries in the reconciler's dirty set are skipped.
112
117
  """
113
118
 
114
- __slots__ = ("element", "native_view", "children", "hook_state", "_rendered")
119
+ __slots__ = (
120
+ "element",
121
+ "native_view",
122
+ "children",
123
+ "parent",
124
+ "hook_state",
125
+ "mounted",
126
+ "_rendered",
127
+ "_measure_cache",
128
+ )
115
129
 
116
130
  def __init__(self, element: Element, native_view: Any, children: List["VNode"]) -> None:
117
131
  self.element = element
118
132
  self.native_view = native_view
119
133
  self.children = children
134
+ self.parent: Optional["VNode"] = None
120
135
  self.hook_state: Any = None
136
+ self.mounted: bool = True
121
137
  self._rendered: Optional[Element] = None
138
+ # Cache for the leaf intrinsic-size measure callback:
139
+ # ``(element, max_w, max_h, width, height)``. Lets the layout
140
+ # pass skip native ``measure_intrinsic`` calls for leaves whose
141
+ # element *object* (compared by identity) and constraints are
142
+ # unchanged since the last measure. Because untouched components
143
+ # keep their exact ``Element`` instances across a local
144
+ # re-render, this turns "re-measure everything every layout pass"
145
+ # into "re-measure only what actually re-rendered".
146
+ self._measure_cache: Optional[Tuple[Any, float, float, float, float]] = None
122
147
 
123
148
 
124
149
  class Reconciler:
@@ -142,6 +167,11 @@ class Reconciler:
142
167
  self._screen_re_render: Optional[Any] = None
143
168
  self._viewport_size: Tuple[float, float] = (0.0, 0.0)
144
169
  self._layout_pass = 0
170
+ # Function-component VNodes whose own state changed since the
171
+ # last flush, keyed by ``id`` to dedupe while keeping a strong
172
+ # reference. Drained by
173
+ # [`flush_dirty`][pythonnative.reconciler.Reconciler.flush_dirty].
174
+ self._dirty_nodes: Dict[int, VNode] = {}
145
175
 
146
176
  # ------------------------------------------------------------------
147
177
  # Public API
@@ -160,6 +190,7 @@ class Reconciler:
160
190
  self._log_viewport(
161
191
  f"mount: start type={self._type_label(element.type)!r} props={self._props_debug(element.props)}"
162
192
  )
193
+ self._dirty_nodes.clear()
163
194
  self._tree = self._create_tree(element)
164
195
  self._log_viewport(f"mount: tree created root={self._node_debug(self._tree)}")
165
196
  self._flush_effects()
@@ -181,6 +212,9 @@ class Reconciler:
181
212
  f"(have_tree={self._tree is not None}) new_type={self._type_label(new_element.type)!r} "
182
213
  f"new_props={self._props_debug(new_element.props)}"
183
214
  )
215
+ # A full reconcile rebuilds the whole tree from the root, so any
216
+ # pending per-component dirty marks are now obsolete.
217
+ self._dirty_nodes.clear()
184
218
  if self._tree is None:
185
219
  self._tree = self._create_tree(new_element)
186
220
  self._log_viewport(f"reconcile: created initial root={self._node_debug(self._tree)}")
@@ -195,6 +229,221 @@ class Reconciler:
195
229
  self._log_viewport("reconcile: done")
196
230
  return self._tree.native_view
197
231
 
232
+ def root_view(self) -> Any:
233
+ """Return the current root native view, or ``None`` before mount."""
234
+ return self._tree.native_view if self._tree is not None else None
235
+
236
+ def mark_dirty(self, vnode: "VNode") -> None:
237
+ """Queue ``vnode`` (a function component) for a local re-render.
238
+
239
+ Called by a component's ``use_state`` / ``use_reducer`` setter
240
+ when its own state changes. The node is re-rendered on the next
241
+ [`flush_dirty`][pythonnative.reconciler.Reconciler.flush_dirty]
242
+ pass, which the screen host schedules. Marking is idempotent and
243
+ cheap; the actual render is deferred so several setters (e.g.
244
+ inside [`batch_updates`][pythonnative.batch_updates]) coalesce
245
+ into a single pass.
246
+ """
247
+ if vnode is None or vnode.hook_state is None or not vnode.mounted:
248
+ return
249
+ self._dirty_nodes[id(vnode)] = vnode
250
+
251
+ def flush_dirty(self) -> Any:
252
+ """Re-render only the component subtrees marked dirty since the last pass.
253
+
254
+ This is the hot path for state-driven updates: instead of
255
+ re-running the whole app from the root, each dirty function
256
+ component re-runs its own body (reusing its
257
+ [`HookState`][pythonnative.hooks.HookState]) and reconciles just
258
+ its subtree. Nodes are processed shallowest-first so that when a
259
+ dirty ancestor's re-render already covers a dirty descendant, the
260
+ descendant is skipped (its ``_dirty`` flag is cleared by the
261
+ ancestor pass).
262
+
263
+ Returns:
264
+ The (possibly replaced) root native view, so the host can
265
+ re-attach it if the root changed.
266
+ """
267
+ if self._tree is None:
268
+ return None
269
+ if not self._dirty_nodes:
270
+ return self._tree.native_view
271
+
272
+ pending = list(self._dirty_nodes.values())
273
+ self._dirty_nodes.clear()
274
+ pending.sort(key=self._node_depth)
275
+ for vnode in pending:
276
+ if not vnode.mounted:
277
+ continue
278
+ hook_state = vnode.hook_state
279
+ if hook_state is None or not hook_state._dirty:
280
+ # Already re-rendered as part of a dirty ancestor's pass.
281
+ continue
282
+ try:
283
+ self._update_component(vnode)
284
+ except Exception as exc:
285
+ # A local re-render starts below any enclosing
286
+ # ``ErrorBoundary``, so route the failure to the nearest
287
+ # boundary ancestor (re-rendering its subtree through the
288
+ # boundary, which mounts the fallback). With no boundary
289
+ # the exception propagates, matching a full render.
290
+ self._handle_local_render_error(vnode, exc)
291
+
292
+ self._flush_effects()
293
+ self._run_layout()
294
+ return self._tree.native_view
295
+
296
+ @staticmethod
297
+ def _node_depth(vnode: "VNode") -> int:
298
+ depth = 0
299
+ node = vnode.parent
300
+ while node is not None:
301
+ depth += 1
302
+ node = node.parent
303
+ return depth
304
+
305
+ def _update_component(self, vnode: "VNode") -> None:
306
+ """Re-run one function component's body and reconcile its subtree in place.
307
+
308
+ Unlike a full reconcile from the root, a local update starts in
309
+ the *middle* of the tree, so the context stack of every
310
+ ``__Provider__`` ancestor must be re-established before the body
311
+ runs (otherwise [`use_context`][pythonnative.use_context] — and
312
+ therefore [`use_navigation`][pythonnative.use_navigation] — would
313
+ read the context default instead of the provided value). Nested
314
+ providers *inside* this subtree are pushed/popped normally by the
315
+ recursive reconcile beneath us.
316
+ """
317
+ from .hooks import _set_hook_state
318
+
319
+ new_el = vnode.element
320
+ if not callable(new_el.type):
321
+ return
322
+ hook_state = vnode.hook_state
323
+ if hook_state is None:
324
+ return
325
+
326
+ providers = self._ancestor_providers(vnode)
327
+ for context, value in providers:
328
+ context._stack.append(value)
329
+ try:
330
+ hook_state.reset_index()
331
+ hook_state._trigger_render = self._screen_re_render
332
+ hook_state._vnode = vnode
333
+ hook_state._reconciler = self
334
+ _set_hook_state(hook_state)
335
+ try:
336
+ rendered = new_el.type(**new_el.props)
337
+ finally:
338
+ _set_hook_state(None)
339
+ hook_state._dirty = False
340
+
341
+ old_native = vnode.native_view
342
+ if vnode.children:
343
+ child = self._reconcile_node(vnode.children[0], rendered)
344
+ else:
345
+ child = self._create_tree(rendered)
346
+ finally:
347
+ for context, _value in reversed(providers):
348
+ context._stack.pop()
349
+
350
+ child.parent = vnode
351
+ vnode.children = [child]
352
+ vnode.native_view = child.native_view
353
+ vnode._rendered = rendered
354
+
355
+ if child.native_view is not old_native:
356
+ self._bubble_native_view_change(vnode, old_native, child.native_view)
357
+
358
+ def _handle_local_render_error(self, vnode: "VNode", exc: Exception) -> None:
359
+ """Route a local re-render failure to the nearest ``ErrorBoundary`` ancestor.
360
+
361
+ Re-reconciles the boundary against its own element so the throw
362
+ is re-triggered *inside*
363
+ [`_reconcile_error_boundary`][pythonnative.reconciler.Reconciler._reconcile_error_boundary],
364
+ which destroys the failed subtree and mounts the boundary's
365
+ fallback. If no boundary encloses ``vnode`` the exception
366
+ propagates, exactly as it would during a full render.
367
+ """
368
+ node = vnode.parent
369
+ while node is not None:
370
+ if isinstance(node.element.type, str) and node.element.type == "__ErrorBoundary__":
371
+ old_native = node.native_view
372
+ # Like a local component update, this re-reconcile starts
373
+ # mid-tree, so restore the boundary's own ancestor
374
+ # provider context first.
375
+ providers = self._ancestor_providers(node)
376
+ for context, value in providers:
377
+ context._stack.append(value)
378
+ try:
379
+ self._reconcile_node(node, node.element)
380
+ finally:
381
+ for context, _value in reversed(providers):
382
+ context._stack.pop()
383
+ if node.native_view is not old_native:
384
+ self._bubble_native_view_change(node, old_native, node.native_view)
385
+ return
386
+ node = node.parent
387
+ raise exc
388
+
389
+ @staticmethod
390
+ def _ancestor_providers(vnode: "VNode") -> List[Tuple[Any, Any]]:
391
+ """Collect ``(context, value)`` for every ``__Provider__`` above ``vnode``.
392
+
393
+ Returned outermost-first so that pushing them in order leaves the
394
+ nearest provider on top of each context's stack (nearest wins,
395
+ matching React).
396
+ """
397
+ chain: List[Tuple[Any, Any]] = []
398
+ node = vnode.parent
399
+ while node is not None:
400
+ el = node.element
401
+ if isinstance(el.type, str) and el.type == "__Provider__":
402
+ chain.append((el.props["__context__"], el.props["__value__"]))
403
+ node = node.parent
404
+ chain.reverse()
405
+ return chain
406
+
407
+ def _bubble_native_view_change(self, vnode: "VNode", old_native: Any, new_native: Any) -> None:
408
+ """Propagate a changed subtree-root native view up to its native parent.
409
+
410
+ A local re-render starts below the real native container, so when
411
+ the dirty component's root native view is swapped (e.g. its output
412
+ changed type), the change must be reflected in (a) every
413
+ transparent ancestor that delegated its ``native_view`` to this
414
+ subtree and (b) the nearest native-container ancestor's child list.
415
+ """
416
+ child = vnode
417
+ node = vnode.parent
418
+ while node is not None:
419
+ if self._is_native_container(node):
420
+ try:
421
+ idx: Optional[int] = node.children.index(child)
422
+ except ValueError:
423
+ idx = None
424
+ if old_native is not None:
425
+ self.backend.remove_child(node.native_view, old_native, node.element.type)
426
+ if new_native is not None:
427
+ if idx is None:
428
+ self.backend.add_child(node.native_view, new_native, node.element.type)
429
+ else:
430
+ self.backend.insert_child(node.native_view, new_native, node.element.type, idx)
431
+ return
432
+ # Transparent ancestor (component / provider / error boundary /
433
+ # fragment) delegates its native view to this subtree.
434
+ if node.native_view is old_native:
435
+ node.native_view = new_native
436
+ child = node
437
+ node = node.parent
438
+ # Reached the root with no native container above: the root's
439
+ # ``native_view`` was already updated in the loop. The host
440
+ # detects the change by comparing ``root_view()`` after the flush.
441
+
442
+ @staticmethod
443
+ def _is_native_container(node: "VNode") -> bool:
444
+ t = node.element.type
445
+ return isinstance(t, str) and t not in ("__Provider__", "__ErrorBoundary__", "__Fragment__")
446
+
198
447
  def set_viewport_size(self, width: float, height: float) -> None:
199
448
  """Update the viewport size and re-run layout if it changed.
200
449
 
@@ -288,12 +537,24 @@ class Reconciler:
288
537
  # ------------------------------------------------------------------
289
538
 
290
539
  def _flush_effects(self) -> None:
291
- """Walk the committed tree and flush pending effects (depth-first)."""
540
+ """Walk the committed tree and flush pending effects (depth-first).
541
+
542
+ This post-commit walk doubles as the single source of truth for
543
+ ``VNode.parent``: every live node's parent pointer is re-linked
544
+ here so that local re-renders
545
+ ([`flush_dirty`][pythonnative.reconciler.Reconciler.flush_dirty])
546
+ can compute node depth and bubble native-view changes upward
547
+ without each reconcile path having to maintain parent links by
548
+ hand. The cost is folded into a walk the reconciler already runs
549
+ after every commit.
550
+ """
292
551
  if self._tree is not None:
552
+ self._tree.parent = None
293
553
  self._flush_tree_effects(self._tree)
294
554
 
295
555
  def _flush_tree_effects(self, node: VNode) -> None:
296
556
  for child in node.children:
557
+ child.parent = node
297
558
  self._flush_tree_effects(child)
298
559
  if node.hook_state is not None:
299
560
  node.hook_state.flush_pending_effects()
@@ -347,6 +608,8 @@ class Reconciler:
347
608
  vnode = VNode(element, child_node.native_view, [child_node])
348
609
  vnode.hook_state = hook_state
349
610
  vnode._rendered = rendered
611
+ hook_state._vnode = vnode
612
+ hook_state._reconciler = self
350
613
  return vnode
351
614
 
352
615
  # Native element
@@ -478,6 +741,8 @@ class Reconciler:
478
741
  old.element = new_el
479
742
  old.hook_state = hook_state
480
743
  old._rendered = rendered
744
+ hook_state._vnode = old
745
+ hook_state._reconciler = self
481
746
  return old
482
747
 
483
748
  # Native element
@@ -667,13 +932,25 @@ class Reconciler:
667
932
  )
668
933
 
669
934
  def _destroy_tree(self, node: VNode) -> None:
935
+ node.mounted = False
936
+ # Drop the node from the pending-render set so a setter that
937
+ # fired moments before unmount can't resurrect a dead subtree.
938
+ self._dirty_nodes.pop(id(node), None)
670
939
  if node.hook_state is not None:
671
940
  node.hook_state.cleanup_all_effects()
941
+ # Break the back-references so the unmounted component's hook
942
+ # state (and the closures it captured) can be freed by plain
943
+ # refcounting — important on iOS, where the cyclic GC is
944
+ # disabled.
945
+ node.hook_state._vnode = None
946
+ node.hook_state._reconciler = None
947
+ node.hook_state._trigger_render = None
672
948
  if node.element is not None:
673
949
  self._detach_ref(node.element)
674
950
  for child in node.children:
675
951
  self._destroy_tree(child)
676
952
  node.children = []
953
+ node.parent = None
677
954
 
678
955
  @staticmethod
679
956
  def _strip_reconciler_props(props: dict) -> dict:
@@ -935,6 +1212,10 @@ class Reconciler:
935
1212
  node_label = self._node_debug(vnode)
936
1213
 
937
1214
  def measure(max_w: float, max_h: float) -> Tuple[float, float]:
1215
+ cache = vnode._measure_cache
1216
+ if cache is not None and cache[0] is vnode.element and cache[1] == max_w and cache[2] == max_h:
1217
+ self._log_viewport(f"measure: cache hit type={type_name!r} result=({cache[3]!r},{cache[4]!r})")
1218
+ return (cache[3], cache[4])
938
1219
  try:
939
1220
  self._log_viewport(
940
1221
  "measure: before backend.measure_intrinsic " f"{node_label} max=({max_w!r},{max_h!r})"
@@ -942,6 +1223,7 @@ class Reconciler:
942
1223
  w, h = backend.measure_intrinsic(view, type_name, max_w, max_h)
943
1224
  result = (float(w), float(h))
944
1225
  self._log_viewport(f"measure: after backend.measure_intrinsic type={type_name!r} result={result!r}")
1226
+ vnode._measure_cache = (vnode.element, max_w, max_h, result[0], result[1])
945
1227
  return result
946
1228
  except Exception as e:
947
1229
  self._log_viewport(