mapframe 0.3.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.
mapframe/widget.py ADDED
@@ -0,0 +1,1483 @@
1
+ """The MapLibre map widget, and the rules between it and its views.
2
+
3
+ ``state.py`` declares and validates the state. This module publishes it and
4
+ keeps the rest of the contract, summed up here for whoever drives a widget or
5
+ writes a front end for it.
6
+
7
+ Traits. ``state``, ``view``, ``view_request``, ``insets``, ``marker``, ``drawing``,
8
+ ``draw_request``, ``drawn``, ``draw_tool`` and ``projection`` are read-only: assigning one raises
9
+ ``traitlets.TraitError``, and only the widget writes them. The comm opens with
10
+ the first request, sequence 1, in ``view_request``.
11
+
12
+ Publishing. ``MapWidget.publish`` sets a whole ``MapState`` in the ``state``
13
+ trait, with a ``revision`` one above the last. Each layer gets an
14
+ ``instance``, an integer that grows over the widget's life, given in input
15
+ order from 1. A layer gets a new one when it first appears, when it comes back
16
+ after a publish without it, and when its source, source attribution or token
17
+ changes; visibility, opacity, paint, zooms, zone and order keep it. Rejected
18
+ input leaves the previous snapshot and counters intact. Once the local state
19
+ is installed, observer failures are logged. A transport failure propagates
20
+ with the local snapshot committed.
21
+
22
+ Style ids. A view owns every source and layer whose id starts with ``mapframe:``. A
23
+ layer's source is ``mapframe:<id>:<instance>``, with the id escaped as
24
+ ``encodeURIComponent`` does, and its layers add a part: ``:fill``, ``:line``
25
+ and ``:circle`` (or ``:pin``, for ``VectorPaint(marker="pin")``, and ``:cluster`` and ``:count``
26
+ on a clustered source), or ``:raster``. The basemap's source and layer are
27
+ ``mapframe:basemap``. A GeoJSON source generates feature ids, unique within it.
28
+ A new instance is a new source, so nothing reported about the
29
+ old one counts for it. Owned layers stay below every other layer, and the view
30
+ never changes those.
31
+
32
+ Messages. Each mounted view has a unique ``view_id`` and a side
33
+ (``main``, or ``right`` for the second map of a compare view; any other
34
+ side is ignored). It sends JSON messages
35
+ with a ``type``: ``view_open`` on mount and every 20 s, ``view_close``,
36
+ ``pull`` with the GeoJSON digests it lacks, ``status`` on one layer instance,
37
+ ``click``, ``view_report`` with its camera and ``draw_report`` with its drawn
38
+ features. A ``status`` on a rejected style operation also carries its
39
+ ``style_revision``, which counts only for the current publish. A layer whose
40
+ tiles fail is in ``error`` only when every tile of a load failed, until a tile
41
+ loads again; failed tiles beside loaded ones do not count.
42
+ Python answers each pulled digest with a ``data`` message that carries the
43
+ UTF-8 GeoJSON as one buffer, gzipped and marked ``encoding: "gzip"`` when it is
44
+ over ``GZIP_MIN_BYTES``, or ``missing: true`` once a publish dropped it, and
45
+ sends ``status_request`` to ask one view and side to send its statuses again.
46
+ Python's messages reach every view, so each ignores what it did not ask for.
47
+ Any message renews its view; one silent for ``VIEW_EXPIRY_S`` and then
48
+ ``VIEW_GRACE_S`` is dropped with its reports.
49
+
50
+ Camera. The browser owns it. ``set_center`` and ``fit_bounds`` write
51
+ ``view_request`` with a ``seq`` that only grows. A new view first restores the
52
+ camera saved in ``view``, then applies each request newer than the last one it
53
+ applied, and every report names that request and its ``cause``: ``user``,
54
+ ``request``, ``resize``, or ``link`` for a linked map's move that no user made
55
+ (see Linked maps). ``view`` mirrors the last accepted report, with its
56
+ ``cause``, and so does the dict each ``on_view`` callback gets. Reports from
57
+ views not mounted, on an older request, or with a latitude outside [-90, 90]
58
+ or a zoom outside [0, 24] are dropped, and on the same request a ``user`` or
59
+ ``link`` camera is kept over an acknowledgement or another view's resize.
60
+ A view reports its center's longitude in [-180, 180], and its bounds moved by
61
+ as many turns, so across the antimeridian one of their sides passes 180.
62
+
63
+ A center request carries ``center`` and ``zoom``, null to keep the zoom. A fit
64
+ carries ``bounds``, ``padding``, ``max_zoom`` (null for the map's maximum) and
65
+ the view fits the bounds inside ``padding`` px, no further in than
66
+ ``max_zoom``, and jumps there. A padding the usable area cannot hold is
67
+ reduced so that 1 px is left each way. A request with ``animate: true``
68
+ flies there instead (MapLibre's ``flyTo``), and the view reports it when the
69
+ flight ends; a user who moves the map meanwhile ends it, and a newer request
70
+ replaces it. A view jumps to the request it finds on mount, to a fit that
71
+ waited for a usable area, and, as MapLibre does, for a user whose system asks
72
+ for reduced motion. A fit waits while the view's usable
73
+ area has no size, and runs once it has one.
74
+
75
+ Projection. ``projection`` is ``"mercator"`` or ``"globe"``, and every view
76
+ draws its map in it once its style loaded, a view shown later included.
77
+ ``set_projection`` writes it, and so does a ``projection`` message from a
78
+ mounted view, which a view sends when its map changed projection while the
79
+ model holds another, as the globe button does. Linked maps keep their own.
80
+
81
+ Linked maps. Maps whose ``link_group`` names the same group keep one camera.
82
+ A map in a group has ``_link`` set to ``{"group", "seq", "member"}``, else
83
+ ``{}``: the group is the token ``<scope>:<name>``, where the scope is the id
84
+ of the kernel that built the map (each virtual kernel's under ``solara
85
+ run``), else the process's, ``seq`` is the request the link was written on,
86
+ and ``member`` is an id the map keeps for life, by which its views tell each
87
+ other from other maps' views. Linking is per page and per kernel: the views
88
+ of one page that share a token follow each other, and a kernel's maps never
89
+ move another kernel's. In the browser
90
+ every move that changes one view's camera jumps the others to its center and
91
+ zoom in the same call, and each paints it on its next frame. Each view still
92
+ reports its own camera, a follower once per movement of the view that moved,
93
+ as that view does: as ``user`` when a user moved it, else as ``link``, which
94
+ counts like a user's. A move that keeps a view's camera, such as a resize,
95
+ or keeps its map in place as its insets change, moves no other view. Views of one widget never move each other. The first map
96
+ shown sets the camera: a view that joins takes the camera of the group's maps
97
+ already shown, unless a request newer than its link ``seq`` moved it on mount,
98
+ which then moves them. A request not newer than the link, such as a fit that
99
+ waited for a size, moves no other view: while another member is shown, the
100
+ view takes that member's camera instead.
101
+ Python keeps the group's camera, the last one a member reported that was not
102
+ a ``resize``, and moves only the members with no ``main`` view mounted: each
103
+ new camera becomes a request on them, sent with their ``_link`` in one
104
+ message, its ``seq`` the request's. A ``request`` report moves no such member
105
+ that holds a ``set_center`` or ``fit_bounds`` newer than its link ``seq`` and
106
+ made after the request reported, so that request moves the group once the
107
+ member is shown. A map's first request, and those that follow its group,
108
+ count as made before every ``set_center`` and ``fit_bounds``, and so does
109
+ one that a later ``set_center`` or ``fit_bounds`` of the same map replaced
110
+ before a view reported it. A map that joins a group with a camera, built
111
+ with ``link_group`` or set to it, requests that camera instead of its own
112
+ ``center``, mounted or not; one that joins with an accepted ``view`` while
113
+ the group has none gives the group that view's camera. A group forgets its
114
+ camera with its last member, so a re-run notebook cell or a Solara hot
115
+ reload, which keeps the kernel, builds its new maps into the old group,
116
+ still open, and they ignore their ``center`` until the old maps are closed.
117
+ Under Solara, the component that builds a map closes it in an effect
118
+ cleanup, which also runs on a hot reload.
119
+
120
+ Compare. ``MapState.compare`` turns on a swipe compare: each ``Layer.side``
121
+ (``left``, ``right`` or ``both``) says which half draws it. The ``main`` view
122
+ draws the ``left`` and ``both`` layers and the ``right`` view the ``right`` and
123
+ ``both`` ones. Outside compare every layer is drawn by ``main`` alone, whatever
124
+ its side, and the ``right`` view's reports count for nothing. A layer's status
125
+ reduces over the views that draw it, and a publish drops the reports of a view
126
+ whose side stops drawing a layer, since the browser sends nothing then. A
127
+ change of side keeps the layer's instance. A compare view keeps its own map
128
+ as ``main`` and adds the ``right`` map, under the same ``view_id``, while the
129
+ state compares: it opens with ``view_open`` and closes with ``view_close``
130
+ like a view, follows the main map's camera and sends no camera, click or
131
+ draw report. Each map takes a payload the other holds instead of pulling it.
132
+ The right map shows right of a divider the user moves inside the insets; the
133
+ browser keeps the divider's position and never sends it. The pointer reads the map shown under
134
+ it: right of the divider, a click's ``features`` (sent by ``main``), the
135
+ content of the popup and the tooltip, the ``pointer`` cursor and a cluster's
136
+ zoom come from the ``right`` map, while the popup and tooltip themselves, the
137
+ marker and the camera stay on the main map. A click's ``hidden_features`` come
138
+ from the other map, the one the shown half covers there.
139
+ Drawing takes input in both halves, and the ``right`` map draws a copy of
140
+ what Terra Draw renders, handles included, in source ``mapframe-draw-mirror``
141
+ and layers ``mapframe-draw-mirror-fill``, ``-line`` and ``-point``, above its
142
+ owned layers.
143
+
144
+ Clicks. A ``click`` carries the view's ``lnglat`` (longitude wrapped into
145
+ [-180, 180]), its ``zoom``, ``settled``, ``features`` and ``hidden_features``.
146
+ ``settled`` is true when the view has marked the latest state's revision on its root (see the end
147
+ of this docstring), or when everything but the layers in error (a rejected style
148
+ operation, a payload that failed to decode) is on the map: such a layer does not
149
+ hold ``settled`` back, though the mark itself waits for it. Each feature is ``{"id", "instance", "properties"}``: the
150
+ layer id and instance come from the feature's own source id, so a hit on a
151
+ replaced instance names the old one. The view sends at most 5 features per
152
+ layer and 20 in all, but always the first of each layer, top first, and none
153
+ while drawing is interactive. ``hidden_features`` holds, in the same form and
154
+ under the same caps, the hits of the map the shown one covers at the click in
155
+ compare, and is empty outside it. Python accepts a click only from a mounted
156
+ view, with finite ``lnglat`` (latitude in [-90, 90]), ``zoom``, a boolean
157
+ ``settled`` and lists of hits (a missing ``hidden_features`` is empty). It
158
+ drops hits, in both lists, that are not objects or whose ``(id, instance)`` is
159
+ not the current published one, names the layers of the latter in
160
+ ``ClickEvent.stale``, and queues the ``ClickEvent`` to every ``on_click``
161
+ callback under the lock, like ``on_view``.
162
+
163
+ Cursor and marker. ``cursor`` (``""``, ``"crosshair"``, ``"pointer"`` or
164
+ ``"wait"``) is a writable trait: ``""`` leaves MapLibre's own cursor. A view
165
+ shows ``pointer`` instead over a feature of a layer with a popup, a tooltip
166
+ or clusters, and leaves the cursor to the drawing tools while they are
167
+ interactive. ``marker`` is read-only: ``{}`` or ``{"lnglat": [lng, lat],
168
+ "color": str}``, set with ``set_marker`` and ``clear_marker``; each view shows
169
+ one marker for it. ``Controls.coordinates`` shows the pointer's ``lat, lng``
170
+ at the bottom left.
171
+
172
+ Pins and clusters. ``VectorPaint.marker`` is ``"circle"`` (default) or ``"pin"``: a
173
+ pin replaces a point's circle by a symbol anchored at its tip, tinted with the
174
+ fill (else the stroke) colour and sized by ``point_radius``. A ``GeoJSONSource`` may
175
+ carry a ``Cluster(radius, max_zoom)``, part of the source, so changing it gives a
176
+ new instance. A clustered source must hold only points: MapLibre's cluster index
177
+ drops lines and polygons, and a property ``cluster`` that is true is reserved
178
+ on it; ``publish`` checks both with ``check_clusterable``. The view draws count bubbles in the stroke colour, with the count as
179
+ white text (local glyphs, nothing is fetched); a click on one zooms into it and
180
+ sends no click or popup, and clusters are never hits or tooltips. The click
181
+ is a bubble's when the top feature of the popup, tooltip and cluster layers
182
+ there is one (the layers that show the ``pointer`` cursor), whatever other
183
+ layer draws above it. A bubble also hides the popups and tooltips of the features it covers. The
184
+ view draws pins on a canvas and registers them as images with ids
185
+ ``mapframe-pin:<color>`` (the colour escaped as ``encodeURIComponent`` does). The marker option does nothing on raster layers.
186
+
187
+ Colours by class. ``VectorPaint(color_by=name, class_colors=...)`` colours one
188
+ layer's features by the value of their property ``name``: ``class_colors`` is a
189
+ mapping or a sequence of ``(value, colour)`` pairs, given together with
190
+ ``color_by``. Values are unique and all strings or all integers (no bools, at
191
+ most 2**53 - 1 in absolute value). The view turns the fill, line and circle colours and
192
+ the pin image into MapLibre ``match`` expressions on ``["get", name]``. A
193
+ feature whose value is in no class, is of the other type (``"1"`` is not
194
+ ``1``), is null or is missing keeps the colour the paint gives without classes:
195
+ the fill (else the stroke) for polygons, circles and pins, the stroke for
196
+ lines. Circle outlines and cluster bubbles keep the stroke. Like any paint
197
+ change, changing the classes keeps the instance.
198
+
199
+ Popups and tooltips. A vector layer may carry an ``Interaction``, which is part
200
+ of the state but not of its instance identity, so changing it keeps the
201
+ instance. ``popup`` and ``tooltip`` are each ``None`` (off), ``()`` (every
202
+ property, in the feature's order), a tuple naming the properties to show, in
203
+ that order, or a mapping from each name to the non-empty label shown for it
204
+ (a plain name is its own label); names are non-empty strings, and a raster
205
+ layer takes no interaction. A click opens one popup per view, at the click, for the top
206
+ feature among layers with a popup: a two-column table with a row per named
207
+ property the feature has, headed by its label, and nothing when there is no row. A new popup
208
+ replaces the old one. The pointer shows one tooltip, updated once per
209
+ animation frame, for the top feature among layers with a tooltip: a single
210
+ named property shows only its value, otherwise one ``label: value`` line each. It
211
+ hides when nothing is hit and when the pointer leaves the map. Values are
212
+ strings as they are, numbers with ``str``, ``null`` as empty and objects or
213
+ arrays as JSON, each cut at 200 characters, and are inserted as text, never
214
+ HTML. Both are off while drawing is interactive, and close when it becomes
215
+ so. Each remembers the source id of its feature and closes when that source is
216
+ no longer declared, its layer is hidden, or the layer no longer declares it.
217
+ The click message is sent whether or not a popup opens.
218
+
219
+ Drawing. ``drawing`` declares the tools: ``session``, ``modes`` (empty while
220
+ no session is active, else drawing modes with ``select`` last when editing is
221
+ on), ``color`` and ``labels``, the toolbar's label of each drawing mode, of
222
+ ``select`` and of ``clear``, which ``draw.set_labels`` sets. Python holds the
223
+ tools through sessions, one at a time: ``draw.begin`` ends the active session
224
+ and begins the next, numbered in ``session`` from 1 (0 before the first), and
225
+ ``DrawSession.end`` clears the drawing and hides the tools. The browser owns
226
+ the drawn features, like the camera. ``begin``, ``end`` and a session's
227
+ ``set`` and ``clear`` write ``draw_request``, ``{"seq", "features"}``, whose
228
+ ``seq`` only grows from 0; ``begin`` and ``end`` write it with ``drawing`` in
229
+ one message, ``end`` with no features, so the reports of an ended session are
230
+ dropped. ``drawn``, ``{"request_seq", "features"}``, mirrors the last accepted
231
+ report. Python checks the shapes it requests: one closed ring of 4 positions
232
+ or more per polygon, lines of 2 or more, finite positions on the globe and
233
+ JSON properties. It splits Multi* geometries and keeps ids, properties and
234
+ coordinates as given.
235
+
236
+ The browser holds the active tool too. While ``modes`` is not empty, each view
237
+ shows the draw toolbar in its top-left corner, after the controls already
238
+ there: one ``maplibregl-ctrl-group`` with a ``button.mapframe-draw-tool`` per mode,
239
+ ``data-mode`` naming it and ``aria-pressed`` true on the active one, then a
240
+ ``button.mapframe-draw-clear``. A click on a tool makes it the view's active tool, a
241
+ click on the active one leaves it for ``static``, and the clear button removes
242
+ every drawn feature and sends a ``user`` report, even of a drawing that was
243
+ already empty. Drawing is interactive while a view's active tool is not
244
+ ``static``. ``DrawSession.start`` and ``stop`` write ``draw_tool``,
245
+ ``{"seq", "session", "mode"}``, whose ``seq`` only grows from 0. A view
246
+ holds its tool apart from Terra Draw's mode, and a new session starts with
247
+ none. A restart in one session, after a style replacement, enters the view's
248
+ tool again and reads no ``draw_tool``. Only a view's first start in a session
249
+ reads it: it applies the request when it names that session and no view of
250
+ the page applied it yet, so a ``start`` made before any view shows reaches the
251
+ first one, and a view shown later, or shown again, starts with no tool. A view
252
+ running the session applies each request for it newer than the last it
253
+ applied, so every running view follows one ``start``.
254
+
255
+ Each view runs its own Terra Draw 1.39 while ``modes`` is not empty, with every
256
+ drawing mode registered, and prepares each feature before it adds it: it
257
+ rounds the coordinates to 9 decimals, drops Terra Draw's reserved property
258
+ names but ``mode``, replaces a ``mode`` that does not draw the geometry with
259
+ the geometry's own, and replaces an id that is not a UUID4 string, or repeats
260
+ one of the batch, with ``SSSSSSSS-0000-4000-8000-IIIIIIIIIIII``: the batch's
261
+ seq in 8 hex digits and the feature's index in 12. When that ID is already
262
+ reserved by a saved feature, numbering continues past the batch. The seq is the request's,
263
+ or ``drawn.request_seq`` on a restore, so every view gives the same ids. On its
264
+ first start a view restores ``drawn`` when ``drawn.request_seq >=
265
+ draw_request.seq``, else applies the request. A new ``session`` stops its
266
+ Terra Draw, drops its features and starts it empty, then applies the request
267
+ if it is newer than the last one the view applied, which ``begin`` always
268
+ makes it. ``modes`` going empty stops it and drops its features. A restart in
269
+ one session, after a style replacement, restores the view's own features
270
+ unless a newer request came. A view applies a request only while it runs the
271
+ session ``drawing`` names, with tools. Applying a request replaces its
272
+ features and sends a ``draw_report`` with cause ``request``; a user's finished
273
+ drawing or edit, or deletion, sends one with cause ``user``, on the request it
274
+ last applied. A report carries ``request_seq``, ``cause`` and ``features``:
275
+ committed Polygon, LineString and Point features only (no helper or
276
+ in-progress geometry, no reserved names but ``mode``), each moved by whole
277
+ turns so its first vertex lies in [-180, 180] and rounded to 9 decimals; one
278
+ that still crosses the antimeridian is left out. Python accepts a report only
279
+ from a mounted view on the current request; once a user report was accepted
280
+ on it, an acknowledgement from any view is dropped. A feature whose shape
281
+ Python would not request is dropped from a report, and a user report runs the
282
+ active session's ``on_change``. Terra Draw's sources and layers have ids
283
+ starting with ``mapframe-draw-`` and stay above every owned layer.
284
+
285
+ Insets. ``insets`` holds the CSS pixels other UI covers on each side of the
286
+ map element, as ``left``, ``right``, ``top`` and ``bottom``, all 0 at first. A
287
+ view applies them as the map's padding before it restores the camera, and
288
+ moves its control corners in by as much. The reported center is the middle of
289
+ the usable area, and a fit stays inside it. The reported ``bounds`` cover this
290
+ area, including the full range of longitudes when a pole is visible on a
291
+ globe. When the insets change, the map keeps its place on screen and
292
+ the view reports the new middle as a ``resize``. While its map is fullscreen,
293
+ a view uses no insets, and the center keeps its place in the area as it enters
294
+ or leaves fullscreen.
295
+
296
+ A view marks its root element with ``data-mapframe-revision`` once its owned style
297
+ matches that revision and every GeoJSON source has loaded its data, on both
298
+ maps when the state at that revision compares. Its
299
+ fullscreen control fills the closest ancestor marked
300
+ ``data-mapframe-fullscreen-root``, else the root element, and marks that element
301
+ with ``data-mapframe-fullscreen`` while it is fullscreen.
302
+
303
+ The same element, the fullscreen root, holds the height in CSS pixels of each
304
+ control corner, which the view measures each time a corner changes size. They
305
+ are set inline as ``--mapframe-controls-top-left``, ``--mapframe-controls-top-right``,
306
+ ``--mapframe-controls-bottom-left`` and ``--mapframe-controls-bottom-right``, with
307
+ ``data-mapframe-controls`` set to the view's id, so a host's overlays can clear
308
+ the controls. A view removes them when it goes, unless a newer view has
309
+ measured there since. While compare is on, the same element also holds
310
+ ``--mapframe-divider-x``, the divider's x in CSS pixels from its left edge, which
311
+ follows every move of the divider and is removed under the same rule. A host
312
+ must not bind the fullscreen root's ``style``: rewriting it drops them.
313
+ """
314
+
315
+ from __future__ import annotations
316
+
317
+ import asyncio
318
+ import copy
319
+ import gzip
320
+ import hashlib
321
+ import itertools
322
+ import json
323
+ import logging
324
+ import math
325
+ import os
326
+ import threading
327
+ import time
328
+ import uuid
329
+ import weakref
330
+ from collections.abc import Callable, Mapping, Sequence
331
+ from pathlib import Path
332
+ from types import MappingProxyType
333
+ from typing import Any, TypeGuard
334
+
335
+ import anywidget
336
+ import traitlets
337
+
338
+ from ._callbacks import CallbackQueue, running_loop
339
+ from ._camera import INSET_SIDES, MAX_ZOOM, _bounds_request, _center_request, _insets
340
+ from ._draw import DEFAULT_COLOR, DRAW_LABELS, STATIC, Draw, report_features
341
+ from ._events import ClickEvent, FeatureHit
342
+ from .state import GeoJSONSource, LayerStatus, MapState, _finite, check_clusterable
343
+
344
+ _STATIC = Path(__file__).parent / "static"
345
+
346
+ logger = logging.getLogger("mapframe")
347
+
348
+
349
+ def _close_part(part: str, close: Callable[[], None]) -> None:
350
+ """Run one step of a close, and log its failure instead of raising it.
351
+
352
+ Solara closes a kernel's widgets in one loop with no guard
353
+ (``Widget.close_all``): a raise would stop it and leak the kernel.
354
+ """
355
+ try:
356
+ close()
357
+ except Exception:
358
+ logger.exception("mapframe: closing the map's %s failed", part)
359
+
360
+
361
+ def _asset(name: str) -> str | Path:
362
+ """A bundled asset for anywidget: its text, or its path while hot reload is on.
363
+
364
+ anywidget turns a path into a class-level ``FileContents`` and connects every
365
+ instance to its change signal with a strong reference, so no widget would ever
366
+ be collected. ``ANYWIDGET_HMR=1`` is anywidget's own switch for watching files.
367
+ """
368
+ path = _STATIC / name
369
+ if os.getenv("ANYWIDGET_HMR") == "1":
370
+ return path
371
+ return path.read_text(encoding="utf-8")
372
+
373
+
374
+ #: The maps a view mounts: ``main``, and the ``right`` one beside it in compare.
375
+ SIDES = ("main", "right")
376
+ STATUSES = ("loading", "ready", "error")
377
+ #: What moved a view's camera: a user, a request, anything else, or a linked map's
378
+ #: move that no user made.
379
+ CAUSES = ("user", "request", "resize", "link")
380
+ #: The causes that take the camera: an acknowledgement or a resize does not replace them.
381
+ _TAKING = ("user", "link")
382
+ #: What changed a view's drawing: a user, or applying a request.
383
+ DRAW_CAUSES = ("user", "request")
384
+ #: A mounted view repeats ``view_open`` every 20 s, and any message from it
385
+ #: renews it; one silent this long is late. Chrome runs the timers of a
386
+ #: hidden tab as rarely as once a minute.
387
+ VIEW_EXPIRY_S = 150.0
388
+ #: How long a late view has left. A cell that holds the loop past every
389
+ #: deadline makes them all late at once; the messages queued behind it then
390
+ #: renew them within this grace.
391
+ VIEW_GRACE_S = 10.0
392
+ #: A pulled payload over this many bytes goes gzipped.
393
+ GZIP_MIN_BYTES = 64 * 1024
394
+ #: On 100k points (15.5 MB) level 1 gives 2.4 MB in about 60 ms; level 6
395
+ #: saves another 17% for two to three times as long.
396
+ GZIP_LEVEL = 1
397
+
398
+ StatusCallback = Callable[[Mapping[str, LayerStatus]], object]
399
+ ViewCallback = Callable[[dict], Any]
400
+ ClickCallback = Callable[[ClickEvent], object]
401
+ CURSORS = ("", "crosshair", "pointer", "wait")
402
+ PROJECTIONS = ("mercator", "globe")
403
+ View = tuple[str, str]
404
+
405
+
406
+ def _is_int(value) -> TypeGuard[int]:
407
+ return isinstance(value, int) and not isinstance(value, bool)
408
+
409
+
410
+ def _numbers(value, count: int) -> list[float] | None:
411
+ """``value`` as a list of ``count`` finite numbers, or None."""
412
+ if not isinstance(value, (list, tuple)) or len(value) != count:
413
+ return None
414
+ if not all(
415
+ isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) for x in value
416
+ ):
417
+ return None
418
+ return [float(x) for x in value]
419
+
420
+
421
+ def _sides_drawing(side: str, compare: bool) -> tuple[str, ...]:
422
+ """The views that draw a layer of ``side``; outside compare, all on ``main``."""
423
+ if not compare:
424
+ return ("main",)
425
+ return {"left": ("main",), "right": ("right",), "both": ("main", "right")}[side]
426
+
427
+
428
+ def _reduce_status(
429
+ current: Mapping[str, tuple[int, int]],
430
+ expected: Mapping[str, Sequence[View]],
431
+ reports: Mapping[View, Mapping[str, LayerStatus]],
432
+ ) -> dict[str, LayerStatus]:
433
+ """Reduce the views' reports to one status per layer.
434
+
435
+ ``current`` maps each layer id to its ``(token, instance)`` and
436
+ ``expected`` to the mounted ``(view, side)`` pairs that draw it. A layer
437
+ no mounted view draws has no status. A view that has not yet reported
438
+ on the current instance counts as loading. Across views an error wins
439
+ over loading and loading over ready, so a layer is ready only once every
440
+ view drawing it is; the first failing view, in enrolment order, names
441
+ the error.
442
+ """
443
+ out: dict[str, LayerStatus] = {}
444
+ for layer_id, (token, instance) in current.items():
445
+ views = expected.get(layer_id, ())
446
+ if not views:
447
+ continue
448
+ failed: LayerStatus | None = None
449
+ loading = False
450
+ for view in views:
451
+ report = reports.get(view, {}).get(layer_id)
452
+ if report is None or report.instance != instance:
453
+ loading = True
454
+ elif report.status == "error":
455
+ failed = report
456
+ break
457
+ elif report.status == "loading":
458
+ loading = True
459
+ if failed is not None:
460
+ out[layer_id] = LayerStatus("error", failed.error, token, instance)
461
+ else:
462
+ out[layer_id] = LayerStatus("loading" if loading else "ready", None, token, instance)
463
+ return out
464
+
465
+
466
+ #: The link scope of maps built with no kernel running.
467
+ _PROCESS = uuid.uuid4().hex
468
+ # The link scope of each kernel, held weakly.
469
+ _KERNEL_SCOPES: weakref.WeakKeyDictionary[object, str] = weakref.WeakKeyDictionary()
470
+ # Guards the registries below; never held together with a widget's lock.
471
+ _LINK_LOCK = threading.Lock()
472
+ # token -> the maps of that group
473
+ _LINK_MEMBERS: dict[str, weakref.WeakSet[MapWidget]] = {}
474
+ # token -> the group's camera as (lng, lat, zoom)
475
+ _LINK_CAMERAS: dict[str, tuple[float, float, float]] = {}
476
+ # Orders the requests set_center and fit_bounds make, across every map.
477
+ _STAMPS = itertools.count(1)
478
+ # Only guards _STAMPS, and nothing is taken under it.
479
+ _STAMP_LOCK = threading.Lock()
480
+
481
+
482
+ def _stamp() -> int:
483
+ """The stamp of a request ``set_center`` or ``fit_bounds`` makes now."""
484
+ with _STAMP_LOCK:
485
+ return next(_STAMPS)
486
+
487
+
488
+ def _current_kernel() -> object | None:
489
+ """The kernel running now, found as Solara's ``Comm`` finds it, or None.
490
+
491
+ Under Solara this relies on its patch of ``Kernel.instance()`` and
492
+ ``Kernel.initialized()`` (``solara/server/patch.py``), which is not public API.
493
+ pysepal's tests fail if two kernel contexts stop giving different kernels.
494
+ """
495
+ try:
496
+ import ipykernel.kernelbase
497
+ except ImportError:
498
+ return None
499
+ kernel = ipykernel.kernelbase.Kernel
500
+ return kernel.instance() if kernel.initialized() else None
501
+
502
+
503
+ def _kernel_scope() -> str:
504
+ """The link scope of the kernel running now, else of the process."""
505
+ kernel = _current_kernel()
506
+ if kernel is None:
507
+ return _PROCESS
508
+ with _LINK_LOCK:
509
+ return _KERNEL_SCOPES.setdefault(kernel, uuid.uuid4().hex)
510
+
511
+
512
+ def _group_name(value) -> str | None:
513
+ if value is None or (isinstance(value, str) and value):
514
+ return value
515
+ raise ValueError(f"link_group must be a non-empty string or None, got {value!r}")
516
+
517
+
518
+ def _members(token: str) -> weakref.WeakSet[MapWidget] | None:
519
+ """A group's live maps; a group with none is dropped. Call with ``_LINK_LOCK`` held."""
520
+ members = _LINK_MEMBERS.get(token)
521
+ if members:
522
+ return members
523
+ _LINK_MEMBERS.pop(token, None)
524
+ _LINK_CAMERAS.pop(token, None)
525
+ return None
526
+
527
+
528
+ def _join(token: str, widget: MapWidget) -> tuple[float, float, float] | None:
529
+ """Add ``widget`` to a group, returning the group's camera; call with ``_LINK_LOCK`` held."""
530
+ camera = _LINK_CAMERAS.get(token) if _members(token) else None
531
+ _LINK_MEMBERS.setdefault(token, weakref.WeakSet()).add(widget)
532
+ return camera
533
+
534
+
535
+ def _leave(token: str, widget: MapWidget) -> None:
536
+ """Remove ``widget`` from a group; call with ``_LINK_LOCK`` held."""
537
+ members = _LINK_MEMBERS.get(token)
538
+ if members is not None:
539
+ members.discard(widget)
540
+ _members(token)
541
+
542
+
543
+ class MapWidget(anywidget.AnyWidget):
544
+ """A MapLibre map whose persistent configuration lives in ``state``."""
545
+
546
+ _esm = _asset("widget.js")
547
+ _css = _asset("widget.css")
548
+
549
+ state = traitlets.Dict(read_only=True).tag(sync=True)
550
+ view = traitlets.Dict(read_only=True).tag(sync=True)
551
+ view_request = traitlets.Dict(read_only=True).tag(sync=True)
552
+ insets = traitlets.Dict(dict.fromkeys(INSET_SIDES, 0), read_only=True).tag(sync=True)
553
+ marker = traitlets.Dict(read_only=True).tag(sync=True)
554
+ drawing = traitlets.Dict(read_only=True).tag(sync=True)
555
+ draw_request = traitlets.Dict(read_only=True).tag(sync=True)
556
+ drawn = traitlets.Dict(read_only=True).tag(sync=True)
557
+ draw_tool = traitlets.Dict(read_only=True).tag(sync=True)
558
+ projection = traitlets.Enum(PROJECTIONS, "mercator", read_only=True).tag(sync=True)
559
+ cursor = traitlets.Enum(CURSORS, "").tag(sync=True)
560
+ height = traitlets.Unicode("400px").tag(sync=True)
561
+ _link = traitlets.Dict(read_only=True).tag(sync=True)
562
+
563
+ def __init__(
564
+ self,
565
+ *,
566
+ center: tuple[float, float] = (0.0, 0.0),
567
+ zoom: float = 2.0,
568
+ height: str = "400px",
569
+ loop: asyncio.AbstractEventLoop | None = None,
570
+ link_group: str | None = None,
571
+ **kwargs,
572
+ ):
573
+ """Create an empty map of the given CSS height, at ``center`` and ``zoom``.
574
+
575
+ ``center`` is ``(lng, lat)``. ``loop`` is the loop callbacks run on,
576
+ and the timer that expires silent views. It defaults to the loop
577
+ running now, else the one running when the first message from a
578
+ view arrives, and a message that finds it closed, as after a
579
+ reconnect, adopts the loop running then. Leave it unset under
580
+ Solara; pass one only for a host other than Solara. ``link_group``
581
+ is the first :attr:`link_group`; a group that has a camera replaces
582
+ ``center`` and ``zoom`` with it.
583
+ """
584
+ # Set before anything can raise, since close() reads them.
585
+ self._lock = threading.RLock()
586
+ self._closed = False
587
+ self._link_name: str | None = None
588
+ self._loop = loop if loop is not None else running_loop()
589
+ self._callbacks = CallbackQueue()
590
+ # The Layout ipywidgets builds is the widget's own; a given one is the caller's.
591
+ self._owns_layout = "layout" not in kwargs
592
+ self._expiry: asyncio.TimerHandle | None = None
593
+ # (view_id, side) -> monotonic deadline of each mounted view
594
+ self._views: dict[View, float] = {}
595
+ # The views past their deadline, now in their grace period.
596
+ self._late: set[View] = set()
597
+ # (view_id, side) -> layer id -> that view's report on the layer
598
+ self._reports: dict[View, dict[str, LayerStatus]] = {}
599
+ self._link_scope = _kernel_scope()
600
+ self._status: dict[str, LayerStatus] = {}
601
+ self._status_callbacks: list[StatusCallback] = []
602
+ self._view_callbacks: list[ViewCallback] = []
603
+ self._click_callbacks: list[ClickCallback] = []
604
+ # The request a user report was accepted on: acknowledgements of it lose.
605
+ self._draw_user_seq: int | None = None
606
+ self._draw = Draw(self)
607
+ # The last request issued, and the one the last accepted report applied.
608
+ self._issued = 1
609
+ self._acknowledged = 0
610
+ # The seq and stamp of the last request set_center or fit_bounds made.
611
+ self._stamped = (0, 0)
612
+ # The view whose user or link move on that request gave the camera in ``view``.
613
+ self._user_view: str | None = None
614
+ lng, lat = center
615
+ # Set before super().__init__(), which opens the comm with this request.
616
+ self._first_request = {"seq": 1, **_center_request(lng, lat, _finite("zoom", zoom))}
617
+ self._link_member = uuid.uuid4().hex
618
+ name = _group_name(link_group)
619
+ camera = None
620
+ if name is not None:
621
+ self._link_name = name
622
+ # One hold reads the camera and joins, so no forward falls between them.
623
+ with _LINK_LOCK:
624
+ camera = _join(self._token(name), self)
625
+ if camera is not None:
626
+ self._first_request = {"seq": 1, **_center_request(*camera)}
627
+ # The last zoom asked for, until a report says what the views show.
628
+ self._zoom: float | None = self._first_request["zoom"]
629
+ try:
630
+ super().__init__(height=height, **kwargs)
631
+ except BaseException:
632
+ # Left here, since the close() of a failed widget runs in __del__.
633
+ self._leave_group()
634
+ raise
635
+ self._payloads: dict[str, bytes] = {}
636
+ # digest -> the gzipped bytes of a held payload once pulled
637
+ self._gzipped: dict[str, bytes] = {}
638
+ # digests of held payloads that passed check_clusterable
639
+ self._clusterable: set[str] = set()
640
+ self._revision = 0
641
+ self._next_instance = 1
642
+ # id -> (identity, instance) of the last published snapshot
643
+ self._instances: dict[str, tuple[tuple, int]] = {}
644
+ # id -> (token, instance) of the last published snapshot
645
+ self._current: dict[str, tuple[int, int]] = {}
646
+ # id -> the sides drawing it, from the same publish
647
+ self._drawn_on: dict[str, tuple[str, ...]] = {}
648
+ self.on_msg(self._on_message)
649
+ if name is not None:
650
+ # A forward before the comm opened skipped this map.
651
+ self._catch_up(self._token(name), camera)
652
+
653
+ @traitlets.default("view_request")
654
+ def _default_view_request(self) -> dict:
655
+ return self._first_request
656
+
657
+ @traitlets.default("_link")
658
+ def _default_link(self) -> dict:
659
+ if self._link_name is None:
660
+ return {}
661
+ return self._link_on(self._token(self._link_name), self._first_request["seq"])
662
+
663
+ @traitlets.default("drawing")
664
+ def _default_drawing(self) -> dict:
665
+ return {"session": 0, "modes": [], "color": DEFAULT_COLOR, "labels": dict(DRAW_LABELS)}
666
+
667
+ @traitlets.default("draw_request")
668
+ def _default_draw_request(self) -> dict:
669
+ return {"seq": 0, "features": []}
670
+
671
+ @traitlets.default("drawn")
672
+ def _default_drawn(self) -> dict:
673
+ return {"request_seq": 0, "features": []}
674
+
675
+ @traitlets.default("draw_tool")
676
+ def _default_draw_tool(self) -> dict:
677
+ return {"seq": 0, "session": 0, "mode": STATIC}
678
+
679
+ @property
680
+ def draw(self) -> Draw:
681
+ """The drawing tools of this map, and the features they drew."""
682
+ return self._draw
683
+
684
+ @property
685
+ def link_group(self) -> str | None:
686
+ """The name of the group of maps this one keeps one camera with, or None.
687
+
688
+ Setting it joins that group and ``None`` leaves it; the name the map
689
+ has already changes nothing. A name is a non-empty string, and
690
+ anything else raises ``ValueError`` and changes nothing. A map that
691
+ joins a group with a camera requests that camera; one that joins
692
+ with a ``view`` while the group has no camera gives it that view's.
693
+ ``close`` leaves the group, so a closed map reads None, and setting
694
+ it there does nothing.
695
+ """
696
+ return self._link_name
697
+
698
+ @link_group.setter
699
+ def link_group(self, value: str | None) -> None:
700
+ """Join the group ``value`` names, or leave the group for None."""
701
+ name = _group_name(value)
702
+ token = None if name is None else self._token(name)
703
+ camera = seeded = None
704
+ with _LINK_LOCK:
705
+ old = self._link_name
706
+ # close() sets _closed before it leaves, so a close never misses this join.
707
+ if self._closed or name == old:
708
+ return
709
+ self._link_name = name
710
+ if old is not None:
711
+ _leave(self._token(old), self)
712
+ if token is not None:
713
+ camera = _join(token, self)
714
+ view = self.view
715
+ if camera is None and view:
716
+ seeded = _LINK_CAMERAS[token] = (*view["center"], view["zoom"])
717
+ with self._lock:
718
+ if self._link_name != name:
719
+ # A later assignment on another thread won.
720
+ return
721
+ if token is None:
722
+ self.set_trait("_link", {})
723
+ elif camera is not None:
724
+ self._take_camera(token, *camera)
725
+ else:
726
+ self.set_trait("_link", self._link_on(token, self.view_request["seq"]))
727
+ if token is not None:
728
+ # A forward before _link was written skipped this map.
729
+ self._catch_up(token, camera or seeded)
730
+
731
+ @property
732
+ def loop(self) -> asyncio.AbstractEventLoop | None:
733
+ """The loop the widget runs its callbacks and expiry timer on now.
734
+
735
+ It is the constructor's ``loop``, else the loop running at
736
+ construction, else the one running when the first message from a
737
+ view arrives. A message that finds that loop closed adopts the loop
738
+ running then. None until there is one.
739
+ """
740
+ return self._loop
741
+
742
+ @property
743
+ def layer_status(self) -> Mapping[str, LayerStatus]:
744
+ """Each drawn layer's status in the mounted views, read-only.
745
+
746
+ Empty while no view is mounted.
747
+ """
748
+ return MappingProxyType(self._status)
749
+
750
+ def on_status(self, callback: StatusCallback, remove: bool = False) -> None:
751
+ """Call ``callback(layer_status)`` each time ``layer_status`` changes.
752
+
753
+ ``remove=True`` unregisters it.
754
+ """
755
+ with self._lock:
756
+ if remove:
757
+ if callback in self._status_callbacks:
758
+ self._status_callbacks.remove(callback)
759
+ elif callback not in self._status_callbacks:
760
+ self._status_callbacks.append(callback)
761
+
762
+ def on_view(self, callback: ViewCallback, remove: bool = False) -> None:
763
+ """Call ``callback(view)`` with the new ``view`` on each accepted report.
764
+
765
+ ``remove=True`` unregisters it.
766
+ """
767
+ with self._lock:
768
+ if remove:
769
+ if callback in self._view_callbacks:
770
+ self._view_callbacks.remove(callback)
771
+ elif callback not in self._view_callbacks:
772
+ self._view_callbacks.append(callback)
773
+
774
+ def on_click(self, callback: ClickCallback, remove: bool = False) -> None:
775
+ """Call ``callback(event)`` with a ``ClickEvent`` on each accepted click.
776
+
777
+ ``remove=True`` unregisters it.
778
+ """
779
+ with self._lock:
780
+ if remove:
781
+ if callback in self._click_callbacks:
782
+ self._click_callbacks.remove(callback)
783
+ elif callback not in self._click_callbacks:
784
+ self._click_callbacks.append(callback)
785
+
786
+ def set_marker(self, lng: float, lat: float, color: str = "#3388ff") -> None:
787
+ """Show the one highlight marker at ``(lng, lat)`` in ``color``, in every view."""
788
+ lnglat = _numbers([lng, lat], 2)
789
+ if lnglat is None or not -90 <= lnglat[1] <= 90:
790
+ raise ValueError("the marker needs a finite lng and a lat in [-90, 90]")
791
+ if not isinstance(color, str):
792
+ raise ValueError("the marker color must be a string")
793
+ self.set_trait("marker", {"lnglat": lnglat, "color": color})
794
+
795
+ def clear_marker(self) -> None:
796
+ """Remove the highlight marker."""
797
+ self.set_trait("marker", {})
798
+
799
+ def set_projection(self, projection: str) -> None:
800
+ """Draw the map in ``projection``, ``"mercator"`` or ``"globe"``, in every view."""
801
+ if projection not in PROJECTIONS:
802
+ raise ValueError(f"the projection is 'mercator' or 'globe', not {projection!r}")
803
+ self.set_trait("projection", projection)
804
+
805
+ def set_center(
806
+ self, lng: float, lat: float, zoom: float | None = None, *, animate: bool = False
807
+ ) -> None:
808
+ """Ask every view to center on ``(lng, lat)``; no zoom keeps theirs.
809
+
810
+ Until a view reports, a new view has no zoom to keep, so no zoom
811
+ means the last one asked for. With ``animate``, the views fly there.
812
+ """
813
+ self._center(lng, lat, zoom, stamped=True, animate=animate)
814
+
815
+ def _center(
816
+ self, lng: float, lat: float, zoom: float | None, stamped: bool, animate: bool = False
817
+ ) -> None:
818
+ request = _center_request(lng, lat, zoom, animate)
819
+ with self._lock:
820
+ if zoom is None:
821
+ request["zoom"] = self._zoom
822
+ elif self._zoom is not None:
823
+ self._zoom = request["zoom"]
824
+ self._request(request, stamped)
825
+
826
+ def fit_bounds(
827
+ self,
828
+ bounds: tuple[float, float, float, float],
829
+ padding: int = 20,
830
+ max_zoom: float | None = None,
831
+ *,
832
+ animate: bool = False,
833
+ ) -> None:
834
+ """Ask every view to fit ``(west, south, east, north)``, ``padding`` px in.
835
+
836
+ The fit stays inside the insets, zooms in no further than
837
+ ``max_zoom`` (in [0, 24]; None is the map's maximum). A west east of
838
+ east crosses the antimeridian. A view without a usable area fits
839
+ once it has one. With ``animate``, the views fly there.
840
+ """
841
+ self._request(_bounds_request(bounds, padding, max_zoom, animate))
842
+
843
+ def set_insets(self, *, left: int = 0, right: int = 0, top: int = 0, bottom: int = 0) -> None:
844
+ """Declare how many CSS pixels of each side of the map other UI covers.
845
+
846
+ The views center, fit and report bounds inside the rest, and move
847
+ their controls in by as much; the map itself keeps its place on
848
+ screen, as under a panel that opens over it. A side left out is 0; a value that is
849
+ not a non-negative int raises ``ValueError`` and changes nothing.
850
+ """
851
+ self.set_trait("insets", _insets(left, right, top, bottom))
852
+
853
+ def close(self) -> None:
854
+ """Close the widget and the layout it built, and leave its link group.
855
+
856
+ Later messages from its views do nothing. A part that fails to close
857
+ is logged, and the rest still closes.
858
+ """
859
+ with self._lock:
860
+ self._closed = True
861
+ _close_part("view expiry", self._cancel_expiry)
862
+ self._views.clear()
863
+ self._late.clear()
864
+ self._reports.clear()
865
+ self._status = {}
866
+ _close_part("link group", self._leave_group)
867
+ _close_part("callbacks", self._callbacks.close)
868
+ # _trait_values, not self.layout: reading an unset trait would build one
869
+ layout = self._trait_values.get("layout") if self._owns_layout else None
870
+ _close_part("widget", super().close)
871
+ if layout is not None:
872
+ _close_part("layout", layout.close)
873
+
874
+ def _request(self, request: dict, stamped: bool = True) -> None:
875
+ # Under the lock, so requests from several threads go out in seq order.
876
+ with self._lock:
877
+ self._issued += 1
878
+ if stamped:
879
+ self._stamped = (self._issued, _stamp())
880
+ self.set_trait("view_request", {"seq": self._issued, **request})
881
+
882
+ def _token(self, name: str) -> str:
883
+ return f"{self._link_scope}:{name}"
884
+
885
+ def _link_on(self, token: str, seq: int) -> dict:
886
+ """The ``_link`` of this map in group ``token``, written on request ``seq``."""
887
+ return {"group": token, "seq": seq, "member": self._link_member}
888
+
889
+ def _leave_group(self) -> None:
890
+ """Leave the link group once; call without the widget lock.
891
+
892
+ A later call takes no lock: ipywidgets' ``__del__`` closes the widget
893
+ again on whatever thread collects it, which may hold ``_LINK_LOCK``.
894
+ """
895
+ if self._link_name is None:
896
+ return
897
+ with _LINK_LOCK:
898
+ name, self._link_name = self._link_name, None
899
+ if name is not None:
900
+ _leave(self._token(name), self)
901
+
902
+ def _take_camera(self, token: str, lng: float, lat: float, zoom: float) -> None:
903
+ """Request a group's camera and link on that request, in one message."""
904
+ with self._lock, self.hold_sync():
905
+ self._center(lng, lat, zoom, stamped=False)
906
+ self.set_trait("_link", self._link_on(token, self.view_request["seq"]))
907
+
908
+ def _catch_up(self, token: str, seen: tuple[float, float, float] | None) -> None:
909
+ """Take the group's camera if it is no longer ``seen``; call without the lock."""
910
+ with _LINK_LOCK:
911
+ camera = _LINK_CAMERAS.get(token)
912
+ if camera is None or camera == seen:
913
+ return
914
+ with self._lock:
915
+ if not self._closed and self._link.get("group") == token:
916
+ self._take_camera(token, *camera)
917
+
918
+ def _follow(
919
+ self, token: str, lng: float, lat: float, zoom: float, stamp: int | None = None
920
+ ) -> None:
921
+ """Take a peer's camera, unless this map left ``token``, shows a view or holds a newer request.
922
+
923
+ ``stamp`` is the stamp of the request the peer's camera acknowledges,
924
+ None when a move gave it.
925
+ """
926
+ with self._lock:
927
+ if (
928
+ self._closed
929
+ # Not open yet: the constructor catches up once it is.
930
+ or self.comm is None
931
+ or self._link.get("group") != token
932
+ or any(side == "main" for _, side in self._views)
933
+ or (stamp is not None and self._holds_newer(stamp))
934
+ ):
935
+ return
936
+ self._take_camera(token, lng, lat, zoom)
937
+
938
+ def _holds_newer(self, stamp: int) -> bool:
939
+ """Whether this map's request is its own, newer than its link and ``stamp``; call with the lock.
940
+
941
+ Such a request moves the group once a view shows it.
942
+ """
943
+ seq, own = self._stamped
944
+ return seq == self._issued and seq > self._link.get("seq", 0) and own > stamp
945
+
946
+ def _follow_peers(
947
+ self, token: str, center: list[float], zoom: float, stamp: int | None
948
+ ) -> None:
949
+ """Move the group's other maps that show no view to this camera; call without the lock.
950
+
951
+ A camera the group holds already moves nobody, so a hidden map gets
952
+ one request per move, however many members report it. ``stamp`` is
953
+ as for ``_follow``.
954
+ """
955
+ camera = (center[0], center[1], zoom)
956
+ with _LINK_LOCK:
957
+ members = _members(token)
958
+ if members is None or _LINK_CAMERAS.get(token) == camera:
959
+ return
960
+ _LINK_CAMERAS[token] = camera
961
+ peers = [m for m in members if m is not self]
962
+ for peer in peers:
963
+ try:
964
+ peer._follow(token, *camera, stamp)
965
+ except Exception:
966
+ logger.exception("mapframe: a linked map could not follow")
967
+
968
+ def _sides_of(self, layer_id: str) -> Sequence[str]:
969
+ """The sides that draw a layer in the last publish; call with the lock held."""
970
+ return self._drawn_on.get(layer_id, ())
971
+
972
+ def _on_message(self, _widget, content, _buffers) -> None:
973
+ if self.comm is None or not isinstance(content, dict):
974
+ return
975
+ with self._lock:
976
+ if self._loop is None or self._loop.is_closed():
977
+ # A dead loop took its timer along; the next arm makes one.
978
+ if self._loop is not None:
979
+ self._callbacks.forget_loop(self._loop)
980
+ self._loop = running_loop()
981
+ self._expiry = None
982
+ self._renew(content)
983
+ kind = content.get("type")
984
+ if kind == "pull":
985
+ self._answer_pull(content.get("digests"))
986
+ elif kind == "view_open":
987
+ self._view_open(content)
988
+ elif kind == "view_close":
989
+ self._view_close(content)
990
+ elif kind == "status":
991
+ self._report(content)
992
+ elif kind == "view_report":
993
+ self._view_report(content)
994
+ elif kind == "click":
995
+ self._click(content)
996
+ elif kind == "draw_report":
997
+ self._draw_report(content)
998
+ elif kind == "projection":
999
+ self._projection_report(content)
1000
+
1001
+ def _answer_pull(self, digests) -> None:
1002
+ """Send each digest's bytes, or ``missing`` once a publish dropped them."""
1003
+ if not isinstance(digests, list):
1004
+ return
1005
+ for digest in dict.fromkeys(d for d in digests if isinstance(d, str)):
1006
+ data = self._payloads.get(digest)
1007
+ if data is None:
1008
+ self.send({"type": "data", "digest": digest, "missing": True}, [])
1009
+ elif len(data) <= GZIP_MIN_BYTES:
1010
+ self.send({"type": "data", "digest": digest}, [data])
1011
+ else:
1012
+ reply = {"type": "data", "digest": digest, "encoding": "gzip"}
1013
+ self.send(reply, [self._gzip(digest, data)])
1014
+
1015
+ def _gzip(self, digest: str, data: bytes) -> bytes:
1016
+ """The held payload ``data`` of ``digest``, gzipped once; call without the lock."""
1017
+ with self._lock:
1018
+ packed = self._gzipped.get(digest)
1019
+ if packed is None:
1020
+ packed = gzip.compress(data, compresslevel=GZIP_LEVEL, mtime=0)
1021
+ with self._lock:
1022
+ if digest in self._payloads:
1023
+ self._gzipped[digest] = packed
1024
+ return packed
1025
+
1026
+ def _renew(self, content: dict) -> None:
1027
+ """Renew the known views a message came from; call with the lock held.
1028
+
1029
+ A message without a side, such as ``view_report``, renews every side
1030
+ of its view.
1031
+ """
1032
+ view_id, side = content.get("view_id"), content.get("side")
1033
+ if not isinstance(view_id, str):
1034
+ return
1035
+ due = self._now() + VIEW_EXPIRY_S
1036
+ for view in self._views:
1037
+ if view[0] == view_id and side in (None, view[1]):
1038
+ self._views[view] = due
1039
+ self._late.discard(view)
1040
+
1041
+ @staticmethod
1042
+ def _view_of(content: dict) -> View | None:
1043
+ view_id, side = content.get("view_id"), content.get("side")
1044
+ if not isinstance(view_id, str) or not view_id or side not in SIDES:
1045
+ return None
1046
+ return view_id, side
1047
+
1048
+ def _view_open(self, content: dict) -> None:
1049
+ view = self._view_of(content)
1050
+ if view is None:
1051
+ return
1052
+ with self._lock:
1053
+ if self._closed:
1054
+ return
1055
+ self._expire_due()
1056
+ enrolled = view not in self._views
1057
+ self._views[view] = self._now() + VIEW_EXPIRY_S
1058
+ if enrolled:
1059
+ self._reports[view] = {}
1060
+ self._arm_expiry()
1061
+ # A heartbeat only renews; a new or returning view replays its reports.
1062
+ if enrolled:
1063
+ self.send({"type": "status_request", "view_id": view[0], "side": view[1]})
1064
+ self._refresh()
1065
+
1066
+ def _view_close(self, content: dict) -> None:
1067
+ view = self._view_of(content)
1068
+ with self._lock:
1069
+ if view not in self._views:
1070
+ return
1071
+ del self._views[view]
1072
+ self._late.discard(view)
1073
+ self._reports.pop(view, None)
1074
+ if not self._views:
1075
+ self._cancel_expiry()
1076
+ self._refresh()
1077
+
1078
+ def _report(self, content: dict) -> None:
1079
+ """Keep one view's report on the current instance of a layer.
1080
+
1081
+ Reports from views that are not mounted, about layers or instances
1082
+ no longer drawn, or about a style operation of an earlier publish are
1083
+ stale and ignored.
1084
+ """
1085
+ view = self._view_of(content)
1086
+ layer_id = content.get("id")
1087
+ token, instance = content.get("token"), content.get("instance")
1088
+ status, error = content.get("status"), content.get("error")
1089
+ style_revision = content.get("style_revision")
1090
+ if (
1091
+ view is None
1092
+ or not isinstance(layer_id, str)
1093
+ or status not in STATUSES
1094
+ or not (error is None or isinstance(error, str))
1095
+ or not (_is_int(token) and _is_int(instance))
1096
+ or not (style_revision is None or _is_int(style_revision))
1097
+ ):
1098
+ return
1099
+ with self._lock:
1100
+ self._expire_due()
1101
+ if (
1102
+ view in self._views
1103
+ and self._current.get(layer_id) == (token, instance)
1104
+ and (style_revision is None or style_revision == self._revision)
1105
+ and view[1] in self._sides_of(layer_id)
1106
+ ):
1107
+ error = error if status == "error" else None
1108
+ report = LayerStatus(status, error, token, instance)
1109
+ self._reports[view][layer_id] = report
1110
+ self._refresh()
1111
+
1112
+ def _view_report(self, content: dict) -> None:
1113
+ """Mirror one view's camera in ``view`` and tell the callbacks.
1114
+
1115
+ A report of a view that is not mounted, or on a request older than
1116
+ the one the last accepted report applied, is stale and ignored, and
1117
+ so is one with a latitude outside [-90, 90] or a zoom outside [0, 24].
1118
+ On the same request, a camera a user move or a link move gave is kept
1119
+ for redisplay: a later user or link move replaces it, and so does a
1120
+ resize of the view that moved, which keeps that camera. An
1121
+ acknowledgement, or another view's resize, does not. An accepted
1122
+ report that is not a resize then moves the linked maps that show no
1123
+ view, but an acknowledgement moves none that holds a newer request of
1124
+ its own (see ``_holds_newer``).
1125
+ """
1126
+ view_id, seq = content.get("view_id"), content.get("request_seq")
1127
+ center = _numbers(content.get("center"), 2)
1128
+ zoom = _numbers([content.get("zoom")], 1)
1129
+ bounds = _numbers(content.get("bounds"), 4)
1130
+ cause = content.get("cause")
1131
+ if (
1132
+ not isinstance(view_id, str)
1133
+ or not (_is_int(seq) and seq >= 0)
1134
+ or center is None
1135
+ or not -90 <= center[1] <= 90
1136
+ or zoom is None
1137
+ or not 0 <= zoom[0] <= MAX_ZOOM
1138
+ or bounds is None
1139
+ or cause not in CAUSES
1140
+ ):
1141
+ return
1142
+ forward = stamp = None
1143
+ with self._lock:
1144
+ self._expire_due()
1145
+ same = seq == self._acknowledged and self._user_view is not None
1146
+ own_resize = same and cause == "resize" and view_id == self._user_view
1147
+ kept = same and cause not in _TAKING and not own_resize
1148
+ if (
1149
+ not self._closed
1150
+ and any(v[0] == view_id for v in self._views)
1151
+ and self._acknowledged <= seq <= self._issued
1152
+ and not kept
1153
+ ):
1154
+ self._acknowledged = seq
1155
+ if cause in _TAKING:
1156
+ self._user_view = view_id
1157
+ elif not own_resize:
1158
+ self._user_view = None
1159
+ # A new view now restores this camera, zoom included.
1160
+ self._zoom = None
1161
+ view = {"center": center, "zoom": zoom[0], "bounds": bounds}
1162
+ view["request_seq"] = seq
1163
+ view["cause"] = cause
1164
+ # Under the lock, so reports on other threads cannot reorder it.
1165
+ self.set_trait("view", view)
1166
+ for callback in self._view_callbacks:
1167
+ self._callbacks.put(callback, copy.deepcopy(view))
1168
+ # A resize keeps the camera, and could undo a newer fit on a hidden map.
1169
+ if cause != "resize":
1170
+ forward = self._link.get("group")
1171
+ if cause == "request":
1172
+ # Only the last set_center or fit_bounds keeps its stamp: one
1173
+ # it replaced is reported just before it.
1174
+ stamped_seq, own = self._stamped
1175
+ stamp = own if seq == stamped_seq else 0
1176
+ if forward:
1177
+ self._follow_peers(forward, center, zoom[0], stamp)
1178
+ # Expiring a view can change the status too.
1179
+ self._refresh()
1180
+
1181
+ def _click(self, content: dict) -> None:
1182
+ """Queue a click from a mounted view to the click callbacks.
1183
+
1184
+ Hits that are not objects, or not on the current instance of their
1185
+ layer, are dropped; a layer whose hit was on a retired instance is
1186
+ named in ``stale``.
1187
+ """
1188
+ view = self._view_of(content)
1189
+ lnglat = _numbers(content.get("lnglat"), 2)
1190
+ zoom = _numbers([content.get("zoom")], 1)
1191
+ settled, hits = content.get("settled"), content.get("features")
1192
+ hidden = content.get("hidden_features", [])
1193
+ if (
1194
+ view is None
1195
+ or lnglat is None
1196
+ or not -90 <= lnglat[1] <= 90
1197
+ or zoom is None
1198
+ or not isinstance(settled, bool)
1199
+ or not isinstance(hits, list)
1200
+ or not isinstance(hidden, list)
1201
+ ):
1202
+ return
1203
+ with self._lock:
1204
+ self._expire_due()
1205
+ if self._closed or view not in self._views:
1206
+ return
1207
+ stale: set[str] = set()
1208
+ features, under = self._hits(hits, stale), self._hits(hidden, stale)
1209
+ event = ClickEvent(
1210
+ lnglat[0], lnglat[1], zoom[0], settled, features, frozenset(stale), view[0], under
1211
+ )
1212
+ for callback in self._click_callbacks:
1213
+ self._callbacks.put(callback, event)
1214
+ self._callbacks.flush(self._loop)
1215
+
1216
+ def _hits(self, hits: list, stale: set[str]) -> tuple[FeatureHit, ...]:
1217
+ """The well-formed hits on current instances; the layers of retired ones go in ``stale``."""
1218
+ features: list[FeatureHit] = []
1219
+ for hit in hits:
1220
+ if not isinstance(hit, dict):
1221
+ continue
1222
+ layer_id, instance = hit.get("id"), hit.get("instance")
1223
+ properties = hit.get("properties")
1224
+ if (
1225
+ not isinstance(layer_id, str)
1226
+ or not _is_int(instance)
1227
+ or not isinstance(properties, dict)
1228
+ ):
1229
+ continue
1230
+ if self._current.get(layer_id, (None, None))[1] != instance:
1231
+ stale.add(layer_id)
1232
+ continue
1233
+ features.append(
1234
+ FeatureHit(layer_id, instance, MappingProxyType(copy.deepcopy(properties)))
1235
+ )
1236
+ return tuple(features)
1237
+
1238
+ def _projection_report(self, content: dict) -> None:
1239
+ """Take the projection a user picked in a mounted view."""
1240
+ projection = content.get("projection")
1241
+ if not isinstance(projection, str) or projection not in PROJECTIONS:
1242
+ return
1243
+ with self._lock:
1244
+ mounted = any(v[0] == content.get("view_id") for v in self._views)
1245
+ if mounted and not self._closed:
1246
+ self.set_trait("projection", projection)
1247
+
1248
+ def _draw_report(self, content: dict) -> None:
1249
+ """Mirror one view's drawn features in ``drawn``, and tell the session a user's.
1250
+
1251
+ Only a report of a mounted view on the current request counts, and on
1252
+ that request, once a user report was accepted, an acknowledgement from
1253
+ any view is dropped. Features ``check_features`` refuses are dropped.
1254
+ """
1255
+ view = self._view_of(content)
1256
+ seq, cause, features = (content.get(k) for k in ("request_seq", "cause", "features"))
1257
+ if (
1258
+ view is None
1259
+ or not (_is_int(seq) and seq >= 0)
1260
+ or cause not in DRAW_CAUSES
1261
+ or not isinstance(features, list)
1262
+ ):
1263
+ return
1264
+ with self._lock:
1265
+ self._expire_due()
1266
+ if (
1267
+ not self._closed
1268
+ and view in self._views
1269
+ and seq == self.draw_request["seq"]
1270
+ and not (cause == "request" and self._draw_user_seq == seq)
1271
+ ):
1272
+ accepted = report_features(features)
1273
+ if cause == "user":
1274
+ self._draw_user_seq = seq
1275
+ # The current request is the active session's, since begin
1276
+ # and end each write a new one.
1277
+ callback = self._draw._change_callback()
1278
+ # Before ``drawn`` is written: a report that an observer of
1279
+ # it gets accepted then runs its callback after this one.
1280
+ if callback is not None:
1281
+ collection = {"type": "FeatureCollection", "features": accepted}
1282
+ self._callbacks.put(callback, copy.deepcopy(collection))
1283
+ self.set_trait("drawn", {"request_seq": seq, "features": accepted})
1284
+ self._refresh()
1285
+
1286
+ def _refresh(self) -> None:
1287
+ """Reduce the reports again, tell the callbacks if that changed.
1288
+
1289
+ Also runs whatever callbacks are queued.
1290
+ """
1291
+ with self._lock:
1292
+ if not self._closed:
1293
+ expected = {
1294
+ layer_id: [v for v in self._views if v[1] in self._sides_of(layer_id)]
1295
+ for layer_id in self._current
1296
+ }
1297
+ status = _reduce_status(self._current, expected, self._reports)
1298
+ if status != self._status:
1299
+ self._status = status
1300
+ snapshot = MappingProxyType(status)
1301
+ # Queued as the snapshot is taken: they run in its order.
1302
+ for callback in self._status_callbacks:
1303
+ self._callbacks.put(callback, snapshot)
1304
+ self._callbacks.flush(self._loop)
1305
+
1306
+ def _now(self) -> float:
1307
+ loop = self._loop
1308
+ return time.monotonic() if loop is None else loop.time()
1309
+
1310
+ def _expire_due(self) -> None:
1311
+ """Drop views silent through their grace; call with the lock held.
1312
+
1313
+ A view found past its deadline is late, not gone: it has
1314
+ ``VIEW_GRACE_S`` more, and any message from it meanwhile renews it.
1315
+ """
1316
+ now = self._now()
1317
+ for view, due in list(self._views.items()):
1318
+ if due > now:
1319
+ continue
1320
+ if view in self._late:
1321
+ del self._views[view]
1322
+ self._late.discard(view)
1323
+ self._reports.pop(view, None)
1324
+ else:
1325
+ self._late.add(view)
1326
+ self._views[view] = now + VIEW_GRACE_S
1327
+ if not self._views:
1328
+ self._cancel_expiry()
1329
+
1330
+ def _arm_expiry(self) -> None:
1331
+ """Point the one expiry timer at the earliest deadline, under the lock.
1332
+
1333
+ A renewed deadline, or a grace, is only ever later, so neither re-arms
1334
+ it: the timer re-arms itself for the next deadline when it fires.
1335
+ """
1336
+ loop = self._loop
1337
+ if self._expiry is not None or not self._views:
1338
+ return
1339
+ if loop is None or loop.is_closed():
1340
+ return
1341
+ if loop.is_running() and running_loop() is not loop:
1342
+ # A message handled off the owner loop's thread.
1343
+ loop.call_soon_threadsafe(self._arm_expiry_locked)
1344
+ return
1345
+ delay = max(0.0, min(self._views.values()) - loop.time())
1346
+ self._expiry = loop.call_later(delay, self._on_expiry)
1347
+
1348
+ def _arm_expiry_locked(self) -> None:
1349
+ with self._lock:
1350
+ if not self._closed:
1351
+ self._arm_expiry()
1352
+
1353
+ def _on_expiry(self) -> None:
1354
+ with self._lock:
1355
+ self._expiry = None
1356
+ if self._closed:
1357
+ return
1358
+ self._expire_due()
1359
+ self._arm_expiry()
1360
+ self._refresh()
1361
+
1362
+ def _cancel_expiry(self) -> None:
1363
+ handle, self._expiry = self._expiry, None
1364
+ if handle is None:
1365
+ return
1366
+ loop = self._loop
1367
+ if loop is not None and loop.is_running() and running_loop() is not loop:
1368
+ loop.call_soon_threadsafe(handle.cancel)
1369
+ else:
1370
+ handle.cancel()
1371
+
1372
+ def add_payload(self, data: bytes) -> str:
1373
+ """Keep GeoJSON bytes for the next publish and return their sha256 digest.
1374
+
1375
+ The next ``publish`` drops every payload its state does not reference,
1376
+ including ones added since the publish before it, so add payloads right
1377
+ before the publish that uses them.
1378
+ """
1379
+ digest = hashlib.sha256(data).hexdigest()
1380
+ with self._lock:
1381
+ self._payloads[digest] = bytes(data)
1382
+ return digest
1383
+
1384
+ def has_payload(self, digest: str) -> bool:
1385
+ """Whether the widget still holds the bytes of ``digest``."""
1386
+ with self._lock:
1387
+ return digest in self._payloads
1388
+
1389
+ def _check_clusterable(self, digest: str) -> None:
1390
+ """Run ``check_clusterable`` on a held payload once; call with the lock held."""
1391
+ if digest in self._clusterable:
1392
+ return
1393
+ try:
1394
+ data = json.loads(self._payloads[digest])
1395
+ except ValueError:
1396
+ data = None # not JSON: the views report it as a layer error
1397
+ if isinstance(data, dict):
1398
+ check_clusterable(data)
1399
+ self._clusterable.add(digest)
1400
+
1401
+ def _notify_observers(self, event) -> None:
1402
+ if event["name"] != "state" or event["type"] != "change":
1403
+ return super()._notify_observers(event)
1404
+ # ipywidgets sends the trait before Traitlets calls this hook.
1405
+ try:
1406
+ super()._notify_observers(event)
1407
+ except Exception:
1408
+ logger.exception("mapframe: a state observer failed")
1409
+
1410
+ def publish(self, state: MapState) -> None:
1411
+ """Publish ``state`` as the next snapshot. Rejected input changes nothing.
1412
+
1413
+ Every GeoJSON digest in ``state`` must come from ``add_payload``. The
1414
+ publish then drops the payloads ``state`` does not reference, even ones
1415
+ added since the last publish: add each payload right before the publish
1416
+ that uses it. The payload of a clustered source must pass
1417
+ ``check_clusterable``, else ``ValueError``. Publishes from several
1418
+ threads publish one at a time. Observers of ``state`` run under the
1419
+ widget lock, so a publish they make publishes after this one. An observer
1420
+ exception is logged. A transport exception propagates after the local
1421
+ state and status have been updated. The views may need a new publish.
1422
+ """
1423
+ if not isinstance(state, MapState):
1424
+ raise TypeError("publish expects a MapState")
1425
+ try:
1426
+ self._publish(state)
1427
+ finally:
1428
+ self._refresh()
1429
+
1430
+ def _publish(self, state: MapState) -> None:
1431
+ # One publish at a time from validation to prune, so concurrent publishes
1432
+ # publish in revision order and never share an instance.
1433
+ with self._lock:
1434
+ referenced = {
1435
+ layer.source.digest
1436
+ for layer in state.layers
1437
+ if isinstance(layer.source, GeoJSONSource)
1438
+ }
1439
+ missing = sorted(referenced - self._payloads.keys())
1440
+ if missing:
1441
+ raise KeyError(f"payloads never added: {', '.join(missing)}")
1442
+ for layer in state.layers:
1443
+ if isinstance(layer.source, GeoJSONSource) and layer.source.cluster is not None:
1444
+ self._check_clusterable(layer.source.digest)
1445
+
1446
+ data = state.to_json()
1447
+ instances: dict[str, tuple[tuple, int]] = {}
1448
+ next_instance = self._next_instance
1449
+ for layer, entry in zip(state.layers, data["layers"]):
1450
+ identity = (layer.source, layer.attribution, layer.token)
1451
+ previous = self._instances.get(layer.id)
1452
+ if previous is not None and previous[0] == identity:
1453
+ instance = previous[1]
1454
+ else:
1455
+ instance = next_instance
1456
+ next_instance += 1
1457
+ instances[layer.id] = (identity, instance)
1458
+ entry["instance"] = instance
1459
+ data["revision"] = self._revision + 1
1460
+ current = {layer.id: (layer.token, instances[layer.id][1]) for layer in state.layers}
1461
+
1462
+ self._instances = instances
1463
+ self._next_instance = next_instance
1464
+ self._revision += 1
1465
+ self._current = current
1466
+ self._drawn_on = {
1467
+ layer.id: _sides_drawing(layer.side, state.compare) for layer in state.layers
1468
+ }
1469
+ # Retire reports on replaced and removed instances, and those of a
1470
+ # side that no longer draws the layer (the browser sends nothing
1471
+ # when it stops), before any view sees the new snapshot.
1472
+ for (_, side), reports in self._reports.items():
1473
+ for layer_id, report in list(reports.items()):
1474
+ if current.get(layer_id) != (
1475
+ report.token,
1476
+ report.instance,
1477
+ ) or side not in self._drawn_on.get(layer_id, ()):
1478
+ del reports[layer_id]
1479
+ # Pruned first: a publish that a state observer makes prunes last.
1480
+ self._payloads = {d: b for d, b in self._payloads.items() if d in referenced}
1481
+ self._clusterable &= referenced
1482
+ self._gzipped = {d: b for d, b in self._gzipped.items() if d in referenced}
1483
+ self.set_trait("state", data)