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/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """A generic MapLibre GL JS anywidget."""
2
+
3
+ from ._draw import DRAW_MODES, Draw, DrawSession
4
+ from ._events import ClickEvent, FeatureHit
5
+ from .state import (
6
+ Basemap,
7
+ Cluster,
8
+ Controls,
9
+ GeoJSONSource,
10
+ Interaction,
11
+ Layer,
12
+ LayerStatus,
13
+ MapState,
14
+ PMTilesSource,
15
+ RasterSource,
16
+ Side,
17
+ VectorPaint,
18
+ check_clusterable,
19
+ tile_urls,
20
+ )
21
+ from .widget import MapWidget
22
+
23
+ __version__ = "0.3.0"
24
+ __all__ = [
25
+ "DRAW_MODES",
26
+ "Basemap",
27
+ "ClickEvent",
28
+ "Cluster",
29
+ "Controls",
30
+ "Draw",
31
+ "DrawSession",
32
+ "FeatureHit",
33
+ "GeoJSONSource",
34
+ "Interaction",
35
+ "Layer",
36
+ "LayerStatus",
37
+ "MapState",
38
+ "MapWidget",
39
+ "PMTilesSource",
40
+ "RasterSource",
41
+ "Side",
42
+ "VectorPaint",
43
+ "check_clusterable",
44
+ "tile_urls",
45
+ ]
mapframe/_callbacks.py ADDED
@@ -0,0 +1,186 @@
1
+ """Run user callbacks on the session loop."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ import logging
8
+ import threading
9
+ from collections import deque
10
+ from collections.abc import Callable
11
+ from typing import TypeGuard
12
+
13
+ logger = logging.getLogger("mapframe")
14
+
15
+ #: Tasks dispatched without a queue, kept alive until they finish.
16
+ _running: set[asyncio.Future] = set()
17
+
18
+
19
+ def running_loop() -> asyncio.AbstractEventLoop | None:
20
+ """The loop running in this thread, if any."""
21
+ try:
22
+ return asyncio.get_running_loop()
23
+ except RuntimeError:
24
+ return None
25
+
26
+
27
+ def _usable(loop: asyncio.AbstractEventLoop | None) -> TypeGuard[asyncio.AbstractEventLoop]:
28
+ return loop is not None and not loop.is_closed()
29
+
30
+
31
+ def dispatch(cb: Callable, *args, loop: asyncio.AbstractEventLoop | None) -> None:
32
+ """Call ``cb(*args)`` on ``loop``, and run an awaitable it returns there too.
33
+
34
+ From another thread the call is queued with ``loop.call_soon_threadsafe``,
35
+ even if that thread runs a loop of its own. Without a session loop it
36
+ happens now, and an awaitable runs on this thread's running loop, else to
37
+ completion. A failure is logged to ``mapframe``.
38
+ """
39
+ if _usable(loop) and running_loop() is not loop:
40
+ try:
41
+ loop.call_soon_threadsafe(_call, cb, args, loop, None)
42
+ return
43
+ except RuntimeError:
44
+ loop = None # it closed meanwhile
45
+ _call(cb, args, loop, None)
46
+
47
+
48
+ def _call(
49
+ cb: Callable,
50
+ args: tuple,
51
+ loop: asyncio.AbstractEventLoop | None,
52
+ track: Callable[[asyncio.Future], None] | None,
53
+ ) -> None:
54
+ try:
55
+ result = cb(*args)
56
+ except Exception:
57
+ logger.exception("mapframe: a callback failed")
58
+ return
59
+ if inspect.isawaitable(result):
60
+ _await(result, loop, track)
61
+
62
+
63
+ def _await(awaitable, loop, track) -> None:
64
+ target = loop if _usable(loop) else running_loop()
65
+ if target is None:
66
+ try:
67
+ asyncio.run(_wait(awaitable))
68
+ except Exception:
69
+ logger.exception("mapframe: a callback failed")
70
+ return
71
+ try:
72
+ task = asyncio.ensure_future(awaitable, loop=target)
73
+ except Exception:
74
+ if inspect.iscoroutine(awaitable):
75
+ awaitable.close()
76
+ logger.exception("mapframe: a callback failed")
77
+ return
78
+ task.add_done_callback(_finished)
79
+ if track is None:
80
+ _running.add(task)
81
+ else:
82
+ track(task)
83
+
84
+
85
+ async def _wait(awaitable):
86
+ return await awaitable
87
+
88
+
89
+ def _finished(task: asyncio.Future) -> None:
90
+ _running.discard(task)
91
+ error = None if task.cancelled() else task.exception()
92
+ if error is not None:
93
+ logger.error("mapframe: a callback failed", exc_info=error)
94
+
95
+
96
+ def _cancel(task: asyncio.Future) -> None:
97
+ loop = task.get_loop()
98
+ if loop.is_closed():
99
+ return
100
+ if running_loop() is loop:
101
+ task.cancel()
102
+ else:
103
+ loop.call_soon_threadsafe(task.cancel)
104
+
105
+
106
+ class CallbackQueue:
107
+ """One owner's callbacks, run on its session loop in the order queued.
108
+
109
+ The owner queues with ``put`` under its own lock, right where it takes
110
+ the snapshot a callback gets, so the queue order is the snapshot order.
111
+ ``flush`` then runs the queue without that lock. One drain at a time
112
+ empties it front to back on the loop, so a call queued later, from any
113
+ thread or from a callback such as one that draws, never runs before an
114
+ earlier one. ``close`` drops the calls still queued and cancels the
115
+ tasks of the awaitables the callbacks returned.
116
+ """
117
+
118
+ def __init__(self) -> None:
119
+ self._lock = threading.Lock()
120
+ self._queue: deque[tuple[Callable, tuple]] = deque()
121
+ self._draining = False
122
+ self._closed = False
123
+ self._tasks: set[asyncio.Future] = set()
124
+
125
+ def put(self, cb: Callable, *args) -> None:
126
+ """Queue ``cb(*args)``; the next ``flush`` runs it."""
127
+ with self._lock:
128
+ if not self._closed:
129
+ self._queue.append((cb, args))
130
+
131
+ def flush(self, loop: asyncio.AbstractEventLoop | None) -> None:
132
+ """Run the queued calls on ``loop``, as ``dispatch`` would run one."""
133
+ with self._lock:
134
+ # Whoever queues a call flushes after it, so nothing is left behind.
135
+ if not self._queue:
136
+ return
137
+ # A drain that runs after close() finds nothing to do.
138
+ dispatch(self._drain, loop, loop=loop)
139
+
140
+ def close(self) -> None:
141
+ """Drop the queued calls and cancel what the callbacks left running."""
142
+ with self._lock:
143
+ self._closed = True
144
+ self._queue.clear()
145
+ tasks, self._tasks = self._tasks, set()
146
+ for task in tasks:
147
+ _cancel(task)
148
+
149
+ def forget_loop(self, loop: asyncio.AbstractEventLoop) -> None:
150
+ """Release tasks whose closed loop can no longer run a done callback."""
151
+ with self._lock:
152
+ self._tasks = {task for task in self._tasks if task.get_loop() is not loop}
153
+
154
+ def _drain(self, loop: asyncio.AbstractEventLoop | None) -> None:
155
+ with self._lock:
156
+ if self._draining:
157
+ # The running drain, further up this stack or on another
158
+ # thread, takes what was just queued.
159
+ return
160
+ self._draining = True
161
+ try:
162
+ while True:
163
+ with self._lock:
164
+ if self._closed or not self._queue:
165
+ self._draining = False
166
+ return
167
+ cb, args = self._queue.popleft()
168
+ _call(cb, args, loop, self._track)
169
+ except BaseException:
170
+ with self._lock:
171
+ self._draining = False
172
+ raise
173
+
174
+ def _track(self, task: asyncio.Future) -> None:
175
+ with self._lock:
176
+ closed = self._closed
177
+ if not closed:
178
+ self._tasks.add(task)
179
+ if closed:
180
+ _cancel(task)
181
+ else:
182
+ task.add_done_callback(self._untrack)
183
+
184
+ def _untrack(self, task: asyncio.Future) -> None:
185
+ with self._lock:
186
+ self._tasks.discard(task)
mapframe/_camera.py ADDED
@@ -0,0 +1,69 @@
1
+ """Validate the camera requests and the insets before they reach the views."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numbers
6
+
7
+ from .state import _finite
8
+
9
+ #: The map's maximum zoom.
10
+ MAX_ZOOM = 24
11
+ #: The sides of the map element that other UI can cover, in ``insets`` order.
12
+ INSET_SIDES = ("left", "right", "top", "bottom")
13
+
14
+
15
+ def _pixels(name: str, value) -> int:
16
+ """``value`` as a whole, non-negative number of CSS pixels; never a bool."""
17
+ if isinstance(value, bool) or not isinstance(value, numbers.Integral) or value < 0:
18
+ raise ValueError(f"{name} must be a whole number of pixels, got {value!r}")
19
+ return int(value)
20
+
21
+
22
+ def _latitude(name: str, value) -> float:
23
+ if not -90 <= _finite(name, value) <= 90:
24
+ raise ValueError(f"{name} must be in [-90, 90], got {value!r}")
25
+ return float(value)
26
+
27
+
28
+ def _zoom(name: str, value) -> float:
29
+ if not 0 <= _finite(name, value) <= MAX_ZOOM:
30
+ raise ValueError(f"{name} must be in [0, {MAX_ZOOM}], got {value!r}")
31
+ return float(value)
32
+
33
+
34
+ def _animated(request: dict, animate: bool) -> dict:
35
+ """``request``, with ``animate: True`` when it flies; a jump carries no key."""
36
+ return {**request, "animate": True} if animate else request
37
+
38
+
39
+ def _center_request(lng, lat, zoom, animate: bool = False) -> dict:
40
+ center = [float(_finite("lng", lng)), _latitude("lat", lat)]
41
+ request = {"center": center, "zoom": None if zoom is None else _zoom("zoom", zoom)}
42
+ return _animated(request, animate)
43
+
44
+
45
+ def _bounds_request(bounds, padding, max_zoom, animate: bool = False) -> dict:
46
+ corners = tuple(bounds)
47
+ if len(corners) != 4:
48
+ raise ValueError(f"bounds must be (west, south, east, north), got {bounds!r}")
49
+ west, south, east, north = corners
50
+ box = [
51
+ float(_finite("west", west)),
52
+ _latitude("south", south),
53
+ float(_finite("east", east)),
54
+ _latitude("north", north),
55
+ ]
56
+ if box[1] > box[3]:
57
+ raise ValueError(f"south must not be above north, got {bounds!r}")
58
+ request = {
59
+ "bounds": box,
60
+ "padding": _pixels("padding", padding),
61
+ "max_zoom": None if max_zoom is None else _zoom("max_zoom", max_zoom),
62
+ }
63
+ return _animated(request, animate)
64
+
65
+
66
+ def _insets(left, right, top, bottom) -> dict[str, int]:
67
+ """The four insets as plain ints, in ``INSET_SIDES`` order."""
68
+ sides = dict(zip(INSET_SIDES, (left, right, top, bottom)))
69
+ return {side: _pixels(side, value) for side, value in sides.items()}
mapframe/_draw.py ADDED
@@ -0,0 +1,378 @@
1
+ """The drawing tools of a map, the sessions that hold them, and the shapes drawn features take.
2
+
3
+ The views draw with Terra Draw 1.39, which validates every feature added to it.
4
+ Python checks the shapes it validates (``validations/*.validation.ts``), so a
5
+ feature Python accepts is one a view can add. Each view prepares the features
6
+ before it adds them: it rounds them to Terra Draw's precision, drops the
7
+ property names Terra Draw reserves and gives them ids, the same in every view.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import copy
13
+ import json
14
+ import math
15
+ import numbers
16
+ from collections.abc import Callable, Mapping, Sequence
17
+ from types import MappingProxyType
18
+ from typing import TYPE_CHECKING, Any
19
+
20
+ if TYPE_CHECKING:
21
+ from .widget import MapWidget
22
+
23
+ #: The drawing tools a map can offer, in toolbar order.
24
+ DRAW_MODES = ("polygon", "rectangle", "circle", "linestring", "point")
25
+ #: The mode that edits what the tools drew, offered after them.
26
+ SELECT = "select"
27
+ #: No tool: the map pans and clicks as usual.
28
+ STATIC = "static"
29
+ DEFAULT_COLOR = "#3388ff"
30
+ #: The toolbar's English labels: one per drawing tool, ``select`` and ``clear``.
31
+ DRAW_LABELS = MappingProxyType(
32
+ {
33
+ "polygon": "Draw a polygon",
34
+ "rectangle": "Draw a rectangle",
35
+ "circle": "Draw a circle",
36
+ "linestring": "Draw a line",
37
+ "point": "Draw a point",
38
+ "select": "Select and edit shapes",
39
+ "clear": "Remove all shapes",
40
+ }
41
+ )
42
+ #: The geometries Terra Draw draws, and the part each Multi* geometry splits into.
43
+ _KINDS = ("Polygon", "LineString", "Point")
44
+ _MULTI = {"MultiPolygon": "Polygon", "MultiLineString": "LineString", "MultiPoint": "Point"}
45
+
46
+ DrawCallback = Callable[[dict], object]
47
+
48
+
49
+ def _empty() -> dict:
50
+ return {"type": "FeatureCollection", "features": []}
51
+
52
+
53
+ def _position(value) -> list[float]:
54
+ """A finite ``[lng, lat]`` on the globe."""
55
+ if not isinstance(value, (list, tuple)) or len(value) != 2:
56
+ raise ValueError(f"a position is [lng, lat], got {value!r}")
57
+ if not all(isinstance(x, numbers.Real) and not isinstance(x, bool) for x in value):
58
+ raise ValueError(f"a position holds two finite numbers, got {value!r}")
59
+ try:
60
+ lng, lat = (float(x) for x in value)
61
+ except OverflowError:
62
+ raise ValueError(f"a position holds two finite numbers, got {value!r}") from None
63
+ if not (math.isfinite(lng) and math.isfinite(lat)):
64
+ raise ValueError(f"a position holds two finite numbers, got {value!r}")
65
+ if not (-180 <= lng <= 180 and -90 <= lat <= 90):
66
+ raise ValueError(f"a position needs a lng in [-180, 180] and a lat in [-90, 90]: {value!r}")
67
+ return [lng, lat]
68
+
69
+
70
+ def _positions(value, minimum: int) -> list[list[float]]:
71
+ if not isinstance(value, (list, tuple)) or len(value) < minimum:
72
+ raise ValueError(f"expected at least {minimum} positions, got {value!r}")
73
+ return [_position(p) for p in value]
74
+
75
+
76
+ def _coordinates(kind: str, coordinates):
77
+ """The checked coordinates of a Polygon, LineString or Point."""
78
+ if kind == "Point":
79
+ return _position(coordinates)
80
+ if kind == "LineString":
81
+ return _positions(coordinates, 2)
82
+ if not isinstance(coordinates, (list, tuple)) or len(coordinates) != 1:
83
+ raise ValueError("a polygon has exactly one ring: Terra Draw cannot draw holes")
84
+ ring = _positions(coordinates[0], 4)
85
+ if ring[0] != ring[-1]:
86
+ raise ValueError("a polygon's ring must be closed")
87
+ return [ring]
88
+
89
+
90
+ def _geometries(geometry, split: bool) -> list[dict]:
91
+ """The Polygon, LineString or Point geometries of ``geometry``.
92
+
93
+ With ``split``, a Multi* geometry gives one per part.
94
+ """
95
+ if not isinstance(geometry, Mapping):
96
+ raise ValueError(f"a feature needs a geometry, got {geometry!r}")
97
+ kind, coordinates = geometry.get("type"), geometry.get("coordinates")
98
+ if split and kind in _MULTI:
99
+ if not isinstance(coordinates, (list, tuple)):
100
+ raise ValueError(f"{kind} coordinates must be a list")
101
+ part = _MULTI[kind]
102
+ return [{"type": part, "coordinates": _coordinates(part, c)} for c in coordinates]
103
+ if kind not in _KINDS:
104
+ raise ValueError(f"Terra Draw draws Polygon, LineString and Point geometries, not {kind!r}")
105
+ return [{"type": kind, "coordinates": _coordinates(kind, coordinates)}]
106
+
107
+
108
+ def _json(value, what: str):
109
+ """A copy of ``value`` the comm can send: a NaN or an object would fail once synced."""
110
+ try:
111
+ return json.loads(json.dumps(value, allow_nan=False))
112
+ except (TypeError, ValueError) as error:
113
+ raise ValueError(f"{what} must be JSON: {error}") from error
114
+
115
+
116
+ def _feature_list(features) -> list:
117
+ """The features of a FeatureCollection, a Feature, or a sequence of Features."""
118
+ if isinstance(features, Mapping):
119
+ if features.get("type") == "FeatureCollection":
120
+ features = features.get("features")
121
+ if not isinstance(features, (list, tuple)):
122
+ raise ValueError("a FeatureCollection needs a list of features")
123
+ return list(features)
124
+ return [features]
125
+ if isinstance(features, Sequence) and not isinstance(features, (str, bytes)):
126
+ return list(features)
127
+ raise ValueError(f"expected a FeatureCollection, a Feature or Features, got {features!r}")
128
+
129
+
130
+ def _check(feature, split: bool) -> list[dict]:
131
+ """``feature`` as drawn features, one per part, with its id and properties."""
132
+ if not isinstance(feature, Mapping) or feature.get("type") != "Feature":
133
+ raise ValueError(f"expected a GeoJSON Feature, got {feature!r}")
134
+ geometries = _geometries(feature.get("geometry"), split)
135
+ properties = feature.get("properties")
136
+ if properties is not None and not isinstance(properties, Mapping):
137
+ raise ValueError(f"feature properties must be a mapping, got {properties!r}")
138
+ properties = _json(dict(properties or {}), "feature properties")
139
+ head: dict[str, Any] = {"type": "Feature"}
140
+ if "id" in feature:
141
+ head["id"] = _json(feature["id"], "a feature id")
142
+ return [
143
+ {**head, "geometry": geometry, "properties": copy.deepcopy(properties)}
144
+ for geometry in geometries
145
+ ]
146
+
147
+
148
+ def check_features(features) -> list[dict]:
149
+ """The drawn features of ``features``, each Multi* geometry split into one per part.
150
+
151
+ ``features`` is a FeatureCollection, a Feature or a sequence of Features
152
+ of Polygon, LineString or Point geometries, or Multi* ones. Ids,
153
+ properties and coordinates are kept as given. A position is a finite
154
+ ``[lng, lat]`` with a lng in [-180, 180] and a lat in [-90, 90]; a line has
155
+ 2 positions or more, and a polygon one closed ring of 4 or more, since
156
+ Terra Draw draws no holes. Properties must be JSON. Any failure raises
157
+ ``ValueError``.
158
+ """
159
+ return [part for f in _feature_list(features) for part in _check(f, split=True)]
160
+
161
+
162
+ def report_features(features: list) -> list[dict]:
163
+ """The features of a view's report that ``check_features`` accepts; the rest are dropped.
164
+
165
+ A view reports no Multi* geometry, so one is dropped too.
166
+ """
167
+ out: list[dict] = []
168
+ for feature in features:
169
+ try:
170
+ out.extend(_check(feature, split=False))
171
+ except ValueError:
172
+ continue
173
+ return out
174
+
175
+
176
+ def _check_modes(modes, edit: bool) -> list[str]:
177
+ if isinstance(modes, str) or not isinstance(modes, Sequence):
178
+ raise ValueError(f"modes must be a sequence of names, got {modes!r}")
179
+ names = list(modes)
180
+ if not names or len(set(names)) != len(names) or any(m not in DRAW_MODES for m in names):
181
+ raise ValueError(f"modes must name tools of {DRAW_MODES} once each, got {modes!r}")
182
+ return names + ([SELECT] if edit else [])
183
+
184
+
185
+ class DrawSession:
186
+ """One owner's hold on a map's drawing tools, from ``Draw.begin`` until it ends.
187
+
188
+ A session ends when its ``end`` runs or another ``Draw.begin`` does. An
189
+ ended session stays ended: ``features`` is empty, ``set``, ``clear``,
190
+ ``start`` and ``stop`` raise ``RuntimeError`` and ``end`` does nothing.
191
+ """
192
+
193
+ def __init__(self, draw: Draw, on_change: DrawCallback | None) -> None:
194
+ self._draw = draw
195
+ self._on_change = on_change
196
+ self._active = True
197
+
198
+ @property
199
+ def active(self) -> bool:
200
+ """Whether the session still holds the tools."""
201
+ with self._draw._widget._lock:
202
+ return self._active
203
+
204
+ @property
205
+ def features(self) -> dict:
206
+ """The drawn features, as a FeatureCollection the caller may change.
207
+
208
+ The features of the newest request until a view acknowledged it, then
209
+ those of the last report the widget accepted; empty once the session
210
+ ended.
211
+ """
212
+ widget = self._draw._widget
213
+ with widget._lock:
214
+ if not self._active:
215
+ return _empty()
216
+ request, drawn = widget.draw_request, widget.drawn
217
+ current = drawn if drawn["request_seq"] >= request["seq"] else request
218
+ return {"type": "FeatureCollection", "features": copy.deepcopy(current["features"])}
219
+
220
+ def set(self, features) -> None:
221
+ """Ask every view to show exactly ``features``, as ``check_features`` takes them.
222
+
223
+ A polygon with holes, or any other failure, raises ``ValueError`` and
224
+ changes nothing. Each view prepares the features before it shows them:
225
+ it rounds the coordinates to 9 decimals, drops the property names Terra
226
+ Draw reserves but ``mode``, replaces a ``mode`` that does not draw the
227
+ geometry with the geometry's own, and replaces an id that is not a
228
+ UUID4 string, or repeats one, with an id every view derives alike.
229
+ ``features`` holds what the views report once one acknowledged them.
230
+ """
231
+ self._require()
232
+ checked = check_features(features)
233
+ widget = self._draw._widget
234
+ with widget._lock:
235
+ self._require()
236
+ widget.set_trait(
237
+ "draw_request", {"seq": widget.draw_request["seq"] + 1, "features": checked}
238
+ )
239
+
240
+ def clear(self) -> None:
241
+ """Ask every view to remove every drawn feature."""
242
+ self.set([])
243
+
244
+ def start(self, mode: str) -> None:
245
+ """Ask for ``mode``, one of ``Draw.modes``, as the active tool.
246
+
247
+ The browser holds the active tool, which the toolbar sets. Every view
248
+ that runs the session applies the request; of the views shown later,
249
+ only the first to start does. A mode the session does not offer,
250
+ ``"static"`` included, raises ``ValueError``.
251
+ """
252
+ with self._draw._widget._lock:
253
+ self._require()
254
+ if mode not in self._draw.modes:
255
+ raise ValueError(f"{mode!r} is not among the tools offered: {self._draw.modes}")
256
+ self._request_tool(mode)
257
+
258
+ def stop(self) -> None:
259
+ """Ask for no active tool, as ``start`` asks for one: the map pans and clicks as usual."""
260
+ with self._draw._widget._lock:
261
+ self._require()
262
+ self._request_tool(STATIC)
263
+
264
+ def end(self) -> None:
265
+ """Clear the drawing and hide the tools in every view; nothing once ended."""
266
+ with self._draw._widget._lock:
267
+ if self._active:
268
+ self._draw._hand_over(None, modes=[], features=[])
269
+
270
+ def _require(self) -> None:
271
+ if not self.active:
272
+ raise RuntimeError("this drawing session has ended")
273
+
274
+ def _request_tool(self, mode: str) -> None:
275
+ widget = self._draw._widget
276
+ seq, session = widget.draw_tool["seq"] + 1, widget.drawing["session"]
277
+ widget.set_trait("draw_tool", {"seq": seq, "session": session, "mode": mode})
278
+
279
+
280
+ class Draw:
281
+ """The drawing tools of one ``MapWidget``, and the session that holds them.
282
+
283
+ The browser owns the drawn features, like the camera. ``begin`` offers the
284
+ tools to one session at a time, which asks every view for features and
285
+ mirrors what they report.
286
+ """
287
+
288
+ def __init__(self, widget: MapWidget) -> None:
289
+ self._widget = widget
290
+ self._session: DrawSession | None = None
291
+
292
+ @property
293
+ def modes(self) -> tuple[str, ...]:
294
+ """The tools offered, ``"select"`` last when editing is on; ``()`` with no session."""
295
+ return tuple(self._widget.drawing["modes"])
296
+
297
+ @property
298
+ def color(self) -> str:
299
+ """The colour the tools draw in: outlines in it, fills in it at 0.2 opacity."""
300
+ return self._widget.drawing["color"]
301
+
302
+ @property
303
+ def features(self) -> dict:
304
+ """The active session's ``features``; an empty FeatureCollection with no session."""
305
+ with self._widget._lock:
306
+ session = self._session
307
+ return _empty() if session is None else session.features
308
+
309
+ def begin(
310
+ self,
311
+ modes: Sequence[str] = ("polygon", "rectangle", "circle"),
312
+ *,
313
+ edit: bool = True,
314
+ features=None,
315
+ on_change: DrawCallback | None = None,
316
+ ) -> DrawSession:
317
+ """End the active session and begin one that offers the tools ``modes``.
318
+
319
+ ``modes`` names tools of ``DRAW_MODES`` once each, in toolbar order, and
320
+ ``edit`` offers ``"select"`` after them. No tool is active. Every view
321
+ shows ``features``, as ``DrawSession.set`` takes them, else nothing.
322
+ ``on_change(collection)`` runs on the session loop with a
323
+ FeatureCollection on each drawing or edit a user makes in this
324
+ session, never for a view acknowledging a request. Bad modes or
325
+ features raise ``ValueError`` and change nothing, so the active
326
+ session goes on.
327
+ """
328
+ names = _check_modes(modes, edit)
329
+ seeds = [] if features is None else check_features(features)
330
+ session = DrawSession(self, on_change)
331
+ self._hand_over(session, modes=names, features=seeds)
332
+ return session
333
+
334
+ def set_color(self, color: str) -> None:
335
+ """Draw in ``color``, a MapLibre colour string, from now on."""
336
+ if not isinstance(color, str) or not color:
337
+ raise ValueError(f"color must be a non-empty string, got {color!r}")
338
+ self._write(color=color)
339
+
340
+ def set_labels(self, labels: Mapping[str, str]) -> None:
341
+ """Label the toolbar's buttons that ``labels`` names; the others keep theirs.
342
+
343
+ Keys are the keys of ``DRAW_LABELS``: the tools of ``DRAW_MODES``,
344
+ ``select`` and ``clear``. A label is a non-empty string. Any other key
345
+ or label raises ``ValueError`` and changes nothing.
346
+ """
347
+ if not isinstance(labels, Mapping):
348
+ raise ValueError(f"labels must be a mapping, got {labels!r}")
349
+ for key, label in labels.items():
350
+ if key not in DRAW_LABELS:
351
+ raise ValueError(f"{key!r} labels no button; the keys are {tuple(DRAW_LABELS)}")
352
+ if not isinstance(label, str) or not label:
353
+ raise ValueError(f"the {key!r} label must be a non-empty string, got {label!r}")
354
+ with self._widget._lock:
355
+ self._write(labels={**self._widget.drawing["labels"], **labels})
356
+
357
+ def _hand_over(self, session: DrawSession | None, *, modes: list, features: list) -> None:
358
+ """Give the tools to ``session``, or to nobody, in one message."""
359
+ widget = self._widget
360
+ with widget._lock, widget.hold_sync():
361
+ # Before the traits: their observers must see who holds the tools.
362
+ if self._session is not None:
363
+ self._session._active = False
364
+ self._session = session
365
+ drawing = widget.drawing
366
+ number = drawing["session"] + (0 if session is None else 1)
367
+ seq = widget.draw_request["seq"] + 1
368
+ widget.set_trait("draw_request", {"seq": seq, "features": features})
369
+ widget.set_trait("drawing", {**drawing, "session": number, "modes": modes})
370
+
371
+ def _change_callback(self) -> DrawCallback | None:
372
+ """The active session's ``on_change``; call with the widget lock held."""
373
+ return None if self._session is None else self._session._on_change
374
+
375
+ def _write(self, **changes: Any) -> None:
376
+ widget = self._widget
377
+ with widget._lock:
378
+ widget.set_trait("drawing", {**widget.drawing, **changes})