loop-link 0.1.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.
- loop_link/__init__.py +61 -0
- loop_link/_websocket.py +436 -0
- loop_link/adapters/__init__.py +51 -0
- loop_link/adapters/loopstructural.py +83 -0
- loop_link/adapters/pandas.py +227 -0
- loop_link/adapters/pyvista.py +267 -0
- loop_link/commands.py +418 -0
- loop_link/discovery.py +170 -0
- loop_link/encode.py +688 -0
- loop_link/errors.py +279 -0
- loop_link/fetch.py +610 -0
- loop_link/objects.py +581 -0
- loop_link/orientation.py +164 -0
- loop_link/protocol.py +235 -0
- loop_link/push.py +166 -0
- loop_link/selection.py +215 -0
- loop_link/testing/__init__.py +7 -0
- loop_link/testing/fake_viewer.py +1587 -0
- loop_link/tool.py +343 -0
- loop_link/version.py +12 -0
- loop_link/viewer.py +1518 -0
- loop_link-0.1.0.dist-info/METADATA +115 -0
- loop_link-0.1.0.dist-info/RECORD +26 -0
- loop_link-0.1.0.dist-info/WHEEL +5 -0
- loop_link-0.1.0.dist-info/licenses/LICENSE +21 -0
- loop_link-0.1.0.dist-info/top_level.txt +1 -0
loop_link/viewer.py
ADDED
|
@@ -0,0 +1,1518 @@
|
|
|
1
|
+
"""The ``Viewer`` class: one connection from Python to the viewer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
import weakref
|
|
8
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from types import TracebackType
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from loop_link import discovery, encode, protocol
|
|
17
|
+
from loop_link._websocket import WebSocketClient, WebSocketClosed, WebSocketError
|
|
18
|
+
from loop_link.adapters import convert
|
|
19
|
+
from loop_link.commands import (
|
|
20
|
+
ColourSettings,
|
|
21
|
+
FilterResult,
|
|
22
|
+
check_codes,
|
|
23
|
+
check_number,
|
|
24
|
+
check_rgb,
|
|
25
|
+
check_text,
|
|
26
|
+
format_number,
|
|
27
|
+
list_colour_map_names,
|
|
28
|
+
run_command,
|
|
29
|
+
)
|
|
30
|
+
from loop_link.errors import (
|
|
31
|
+
BusyError,
|
|
32
|
+
InvalidInputError,
|
|
33
|
+
MissingFeatureError,
|
|
34
|
+
NoViewerError,
|
|
35
|
+
Refusal,
|
|
36
|
+
ViewerClosedError,
|
|
37
|
+
ViewerRefusedError,
|
|
38
|
+
)
|
|
39
|
+
from loop_link.fetch import FetchResult, fetch_object
|
|
40
|
+
from loop_link.protocol import ProtocolError
|
|
41
|
+
from loop_link.selection import Selection, SelectionWatcher, parse_selection_result
|
|
42
|
+
from loop_link.tool import ToolConnection
|
|
43
|
+
|
|
44
|
+
_LINK_ERRORS = (OSError, WebSocketClosed, WebSocketError)
|
|
45
|
+
_SELECTION_FEATURE = "selection and fetch (geoviewer protocol 1.18)"
|
|
46
|
+
_KIND_NAMES = {"cells": "cell", "nodes": "vertex"}
|
|
47
|
+
_INDEX_MAX = 2**32 - 1
|
|
48
|
+
_COLOUR_SCALES = ("linear", "log")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class InventoryEntry:
|
|
53
|
+
"""One object in the scene of the viewer.
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
id : str
|
|
58
|
+
The identifier of the object.
|
|
59
|
+
object_type : str
|
|
60
|
+
The type of the object, as the viewer names it.
|
|
61
|
+
revision : int
|
|
62
|
+
The revision of the object in the viewer.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
id: str
|
|
66
|
+
object_type: str
|
|
67
|
+
revision: int
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Viewer:
|
|
71
|
+
"""A connection to the viewer.
|
|
72
|
+
|
|
73
|
+
Parameters
|
|
74
|
+
----------
|
|
75
|
+
port : int, optional
|
|
76
|
+
The port of the viewer. The default is to search for it.
|
|
77
|
+
token : str, optional
|
|
78
|
+
The access token. The default is to read it from the environment or the settings.
|
|
79
|
+
host : str
|
|
80
|
+
The host of the viewer.
|
|
81
|
+
crs : str
|
|
82
|
+
The coordinate reference system that this client proposes.
|
|
83
|
+
origin : sequence of float
|
|
84
|
+
The scene origin that this client proposes, three values.
|
|
85
|
+
settings_dir : pathlib.Path, optional
|
|
86
|
+
The settings folder of the viewer.
|
|
87
|
+
timeout : float
|
|
88
|
+
The time in seconds to wait for the connection and the first replies.
|
|
89
|
+
heartbeat_interval : float
|
|
90
|
+
The time in seconds between keepalive checks.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
*,
|
|
96
|
+
port: int | None = None,
|
|
97
|
+
token: str | None = None,
|
|
98
|
+
host: str = "127.0.0.1",
|
|
99
|
+
crs: str = "",
|
|
100
|
+
origin: Sequence[float] = (0.0, 0.0, 0.0),
|
|
101
|
+
settings_dir: Path | None = None,
|
|
102
|
+
timeout: float = 5.0,
|
|
103
|
+
heartbeat_interval: float = 5.0,
|
|
104
|
+
) -> None:
|
|
105
|
+
self._port = port
|
|
106
|
+
self._token = token
|
|
107
|
+
self._host = host
|
|
108
|
+
self._crs = crs
|
|
109
|
+
self._proposed_origin = _triple(origin)
|
|
110
|
+
self._settings_dir = settings_dir
|
|
111
|
+
self._timeout = timeout
|
|
112
|
+
self._heartbeat_interval = heartbeat_interval
|
|
113
|
+
|
|
114
|
+
self._lock = threading.Lock()
|
|
115
|
+
self._client: WebSocketClient | None = None
|
|
116
|
+
self._stop = threading.Event()
|
|
117
|
+
self._shared: dict[str, Any] = {"client": None, "stop": self._stop}
|
|
118
|
+
weakref.finalize(self, _release_shared, self._shared)
|
|
119
|
+
self._thread: threading.Thread | None = None
|
|
120
|
+
# _dead: the data connection failed. A later send opens a new connection.
|
|
121
|
+
# _closed: close() was called. Only connect() opens the viewer again.
|
|
122
|
+
self._dead = False
|
|
123
|
+
self._closed = False
|
|
124
|
+
self._address_lock = threading.Lock()
|
|
125
|
+
self._address: discovery.ViewerAddress | None = None
|
|
126
|
+
self._last_send = 0.0
|
|
127
|
+
self._seq = 0
|
|
128
|
+
self._tool_lock = threading.Lock()
|
|
129
|
+
self._tool_connection: ToolConnection | None = None
|
|
130
|
+
self._watchers: list[SelectionWatcher] = []
|
|
131
|
+
self._colour_map_names: tuple[str, ...] | None = None
|
|
132
|
+
|
|
133
|
+
self._revisions: dict[str, int] = {}
|
|
134
|
+
self._inventory: dict[str, InventoryEntry] = {}
|
|
135
|
+
self._inventory_revisions: dict[str, int] = {}
|
|
136
|
+
self._refusals: list[Refusal] = []
|
|
137
|
+
self._scene_origin = self._proposed_origin
|
|
138
|
+
self._scene_crs = crs
|
|
139
|
+
|
|
140
|
+
# -- properties -----------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def revisions(self) -> Mapping[str, int]:
|
|
144
|
+
"""The last revision that this client used for each id."""
|
|
145
|
+
return dict(self._revisions)
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def scene_origin(self) -> tuple[float, float, float]:
|
|
149
|
+
"""The scene origin that all frames use."""
|
|
150
|
+
return self._scene_origin
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def scene_crs(self) -> str:
|
|
154
|
+
"""The coordinate reference system of the scene, as the viewer reported it."""
|
|
155
|
+
return self._scene_crs
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def connected(self) -> bool:
|
|
159
|
+
"""True while the connection is open."""
|
|
160
|
+
return self._client is not None and not self._dead
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def tool_connected(self) -> bool:
|
|
164
|
+
"""True while the tool connection is open."""
|
|
165
|
+
tool = self._tool_connection
|
|
166
|
+
return tool is not None and tool.connected and not self._closed
|
|
167
|
+
|
|
168
|
+
# -- context manager ------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def __enter__(self) -> Viewer:
|
|
171
|
+
"""Connect and return the viewer."""
|
|
172
|
+
self.connect()
|
|
173
|
+
return self
|
|
174
|
+
|
|
175
|
+
def __exit__(
|
|
176
|
+
self,
|
|
177
|
+
exc_type: type[BaseException] | None,
|
|
178
|
+
exc: BaseException | None,
|
|
179
|
+
tb: TracebackType | None,
|
|
180
|
+
) -> None:
|
|
181
|
+
"""Close the connection."""
|
|
182
|
+
self.close()
|
|
183
|
+
|
|
184
|
+
# -- connection -----------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
def connect(self) -> Viewer:
|
|
187
|
+
"""Connect to the viewer and read its ``hello`` and inventory.
|
|
188
|
+
|
|
189
|
+
Raises
|
|
190
|
+
------
|
|
191
|
+
loop_link.errors.NoViewerError
|
|
192
|
+
No viewer was found.
|
|
193
|
+
loop_link.errors.TokenError
|
|
194
|
+
The viewer refused the token.
|
|
195
|
+
loop_link.errors.BusyError
|
|
196
|
+
Another client owns the scene.
|
|
197
|
+
loop_link.errors.MissingFeatureError
|
|
198
|
+
The viewer does not support this protocol version.
|
|
199
|
+
loop_link.errors.ViewerRefusedError
|
|
200
|
+
The viewer sent another error.
|
|
201
|
+
loop_link.errors.ViewerClosedError
|
|
202
|
+
The viewer closed the connection before it finished the hello.
|
|
203
|
+
|
|
204
|
+
Returns
|
|
205
|
+
-------
|
|
206
|
+
Viewer
|
|
207
|
+
The viewer itself.
|
|
208
|
+
"""
|
|
209
|
+
from loop_link import __version__
|
|
210
|
+
|
|
211
|
+
if self.connected:
|
|
212
|
+
return self
|
|
213
|
+
self._closed = False
|
|
214
|
+
self._stop_thread()
|
|
215
|
+
self._drop_client()
|
|
216
|
+
address = self._resolve_address()
|
|
217
|
+
try:
|
|
218
|
+
client = WebSocketClient.connect(
|
|
219
|
+
address.host, address.port, token=address.token, timeout=self._timeout, path="/"
|
|
220
|
+
)
|
|
221
|
+
except NoViewerError:
|
|
222
|
+
# The viewer at the known address is gone. Search again.
|
|
223
|
+
self._forget_address()
|
|
224
|
+
address = self._resolve_address()
|
|
225
|
+
client = WebSocketClient.connect(
|
|
226
|
+
address.host, address.port, token=address.token, timeout=self._timeout, path="/"
|
|
227
|
+
)
|
|
228
|
+
try:
|
|
229
|
+
_read_early(client)
|
|
230
|
+
client.send_binary(encode.hello_frame(self._crs, self._proposed_origin, __version__))
|
|
231
|
+
hello, entries = self._read_hello(client)
|
|
232
|
+
origin, crs = _parse_hello(hello)
|
|
233
|
+
except _LINK_ERRORS as error:
|
|
234
|
+
try:
|
|
235
|
+
_read_early(client, 0.3)
|
|
236
|
+
except _LINK_ERRORS:
|
|
237
|
+
pass
|
|
238
|
+
except BaseException:
|
|
239
|
+
_close_client(client)
|
|
240
|
+
raise
|
|
241
|
+
_close_client(client)
|
|
242
|
+
raise ViewerClosedError from error
|
|
243
|
+
except BaseException:
|
|
244
|
+
_close_client(client)
|
|
245
|
+
raise
|
|
246
|
+
self._scene_origin = origin if origin is not None else self._proposed_origin
|
|
247
|
+
self._scene_crs = crs
|
|
248
|
+
self._inventory = {entry.id: entry for entry in entries}
|
|
249
|
+
self._inventory_revisions = {entry.id: entry.revision for entry in entries}
|
|
250
|
+
self._refusals = []
|
|
251
|
+
self._client = client
|
|
252
|
+
self._shared["client"] = client
|
|
253
|
+
self._dead = False
|
|
254
|
+
self._last_send = time.monotonic()
|
|
255
|
+
self._stop = threading.Event()
|
|
256
|
+
self._shared["stop"] = self._stop
|
|
257
|
+
self._thread = threading.Thread(
|
|
258
|
+
target=_heartbeat_loop,
|
|
259
|
+
args=(weakref.ref(self), self._stop, self._heartbeat_interval),
|
|
260
|
+
name="loop-link-heartbeat",
|
|
261
|
+
daemon=True,
|
|
262
|
+
)
|
|
263
|
+
self._thread.start()
|
|
264
|
+
return self
|
|
265
|
+
|
|
266
|
+
def _read_hello(self, client: WebSocketClient) -> tuple[dict[str, Any], list[InventoryEntry]]:
|
|
267
|
+
"""Read frames until the ``hello`` and the inventory arrive."""
|
|
268
|
+
hello: dict[str, Any] | None = None
|
|
269
|
+
entries: list[InventoryEntry] | None = None
|
|
270
|
+
deadline = time.monotonic() + self._timeout
|
|
271
|
+
while hello is None or entries is None:
|
|
272
|
+
remaining = deadline - time.monotonic()
|
|
273
|
+
if remaining <= 0:
|
|
274
|
+
raise ViewerClosedError(
|
|
275
|
+
"The viewer did not answer the hello in time. Check the viewer and retry."
|
|
276
|
+
)
|
|
277
|
+
data = client.receive(min(remaining, 0.5))
|
|
278
|
+
if data is None:
|
|
279
|
+
continue
|
|
280
|
+
header = protocol.decode_frame(data).header
|
|
281
|
+
kind = header.get("type")
|
|
282
|
+
if kind == "error":
|
|
283
|
+
_raise_hello_error(header)
|
|
284
|
+
elif kind == "hello":
|
|
285
|
+
hello = header
|
|
286
|
+
elif kind == "scene.inventory":
|
|
287
|
+
entries = _parse_inventory(header)
|
|
288
|
+
return hello, entries
|
|
289
|
+
|
|
290
|
+
# -- sending --------------------------------------------------------------
|
|
291
|
+
|
|
292
|
+
def send(
|
|
293
|
+
self,
|
|
294
|
+
obj: Any, # noqa: ANN401
|
|
295
|
+
*,
|
|
296
|
+
id: str,
|
|
297
|
+
name: str | None = None,
|
|
298
|
+
parent: str | None = None,
|
|
299
|
+
colour: ColourSettings | None = None,
|
|
300
|
+
**hints: Any, # noqa: ANN401
|
|
301
|
+
) -> int:
|
|
302
|
+
"""Send one object to the viewer.
|
|
303
|
+
|
|
304
|
+
If ``colour`` is given, the method waits for a late refusal of the object
|
|
305
|
+
and then applies the colour settings with ``apply_colour``.
|
|
306
|
+
|
|
307
|
+
Parameters
|
|
308
|
+
----------
|
|
309
|
+
obj : Any
|
|
310
|
+
The object to send: a loop_link object, or an input that an adapter converts.
|
|
311
|
+
id : str
|
|
312
|
+
The identifier of the object. The same id replaces the object.
|
|
313
|
+
name : str, optional
|
|
314
|
+
The display name. The default is the id.
|
|
315
|
+
parent : str, optional
|
|
316
|
+
The identifier of a group that holds the object.
|
|
317
|
+
colour : loop_link.commands.ColourSettings, optional
|
|
318
|
+
The colour settings to apply after the object is sent.
|
|
319
|
+
**hints : Any
|
|
320
|
+
Options for the adapter that converts ``obj``.
|
|
321
|
+
|
|
322
|
+
Returns
|
|
323
|
+
-------
|
|
324
|
+
int
|
|
325
|
+
The revision that the frame used.
|
|
326
|
+
|
|
327
|
+
Raises
|
|
328
|
+
------
|
|
329
|
+
loop_link.errors.InvalidInputError
|
|
330
|
+
The input type is not accepted, ``colour`` is not a ``ColourSettings``
|
|
331
|
+
object, or the viewer refused a colour command. The object stays in
|
|
332
|
+
the viewer.
|
|
333
|
+
loop_link.errors.ViewerRefusedError
|
|
334
|
+
The viewer refused this object and ``colour`` is given. Refusals of
|
|
335
|
+
other objects stay for the next ``flush``.
|
|
336
|
+
loop_link.errors.MissingFeatureError
|
|
337
|
+
``colour`` is given and the viewer does not support the colour commands.
|
|
338
|
+
loop_link.errors.ViewerClosedError
|
|
339
|
+
The connection is closed.
|
|
340
|
+
"""
|
|
341
|
+
if colour is not None and not isinstance(colour, ColourSettings):
|
|
342
|
+
raise InvalidInputError("colour must be a ColourSettings object.")
|
|
343
|
+
obj = convert(obj, **hints)
|
|
344
|
+
self._ensure_connected()
|
|
345
|
+
revision = self._next_revision(id)
|
|
346
|
+
data = encode.encode_object(
|
|
347
|
+
obj,
|
|
348
|
+
id=id,
|
|
349
|
+
name=id if name is None else name,
|
|
350
|
+
parent=parent,
|
|
351
|
+
revision=revision,
|
|
352
|
+
origin=self._scene_origin,
|
|
353
|
+
)
|
|
354
|
+
self._send_frame(data)
|
|
355
|
+
self._revisions[id] = revision
|
|
356
|
+
object_type = str(protocol.decode_header(data).get("object_type", ""))
|
|
357
|
+
self._inventory[id] = InventoryEntry(id, object_type, revision)
|
|
358
|
+
if colour is not None:
|
|
359
|
+
refusals = self.flush(raise_on_refusal=False)
|
|
360
|
+
own = [r for r in refusals if r.object_id == id]
|
|
361
|
+
others = [r for r in refusals if r.object_id != id]
|
|
362
|
+
# Keep the refusals of other objects for the next flush.
|
|
363
|
+
self._refusals = others + self._refusals
|
|
364
|
+
if own:
|
|
365
|
+
raise ViewerRefusedError(own)
|
|
366
|
+
self.apply_colour(id, colour)
|
|
367
|
+
return revision
|
|
368
|
+
|
|
369
|
+
def send_group(self, id: str, name: str | None = None, parent: str | None = None) -> int:
|
|
370
|
+
"""Send a group.
|
|
371
|
+
|
|
372
|
+
Parameters
|
|
373
|
+
----------
|
|
374
|
+
id : str
|
|
375
|
+
The identifier of the group.
|
|
376
|
+
name : str, optional
|
|
377
|
+
The display name. The default is the id.
|
|
378
|
+
parent : str, optional
|
|
379
|
+
The identifier of a parent group.
|
|
380
|
+
|
|
381
|
+
Returns
|
|
382
|
+
-------
|
|
383
|
+
int
|
|
384
|
+
The revision that the frame used.
|
|
385
|
+
"""
|
|
386
|
+
self._ensure_connected()
|
|
387
|
+
revision = self._next_revision(id)
|
|
388
|
+
self._send_frame(encode.group_frame(id, id if name is None else name, parent, revision))
|
|
389
|
+
self._revisions[id] = revision
|
|
390
|
+
self._inventory[id] = InventoryEntry(id, "Group", revision)
|
|
391
|
+
return revision
|
|
392
|
+
|
|
393
|
+
def remove(self, id: str) -> None:
|
|
394
|
+
"""Remove one object from the scene. The revision count of the id is dropped.
|
|
395
|
+
|
|
396
|
+
Parameters
|
|
397
|
+
----------
|
|
398
|
+
id : str
|
|
399
|
+
The identifier of the object.
|
|
400
|
+
"""
|
|
401
|
+
self._ensure_connected()
|
|
402
|
+
self._send_frame(encode.remove_frame(id))
|
|
403
|
+
self._inventory.pop(id, None)
|
|
404
|
+
self._revisions.pop(id, None)
|
|
405
|
+
self._inventory_revisions.pop(id, None)
|
|
406
|
+
|
|
407
|
+
def clear(self) -> None:
|
|
408
|
+
"""Remove all objects from the scene."""
|
|
409
|
+
self._ensure_connected()
|
|
410
|
+
self._send_frame(encode.clear_frame())
|
|
411
|
+
self._inventory.clear()
|
|
412
|
+
self._revisions.clear()
|
|
413
|
+
self._inventory_revisions.clear()
|
|
414
|
+
|
|
415
|
+
def inventory(self) -> list[InventoryEntry]:
|
|
416
|
+
"""Return the known scene.
|
|
417
|
+
|
|
418
|
+
The list starts with the inventory from the hello frame. ``send`` and
|
|
419
|
+
``send_group`` add or update an entry, ``remove`` drops one, and ``clear``
|
|
420
|
+
drops all. A new connection replaces the list with the hello list.
|
|
421
|
+
|
|
422
|
+
Returns
|
|
423
|
+
-------
|
|
424
|
+
list of InventoryEntry
|
|
425
|
+
The entries.
|
|
426
|
+
"""
|
|
427
|
+
return list(self._inventory.values())
|
|
428
|
+
|
|
429
|
+
def flush(self, settle: float = 0.5, *, raise_on_refusal: bool = True) -> list[Refusal]:
|
|
430
|
+
"""Wait for late replies and return the refusals.
|
|
431
|
+
|
|
432
|
+
Parameters
|
|
433
|
+
----------
|
|
434
|
+
settle : float
|
|
435
|
+
The time in seconds to wait for late frames.
|
|
436
|
+
raise_on_refusal : bool
|
|
437
|
+
If true, raise when the viewer refused an object.
|
|
438
|
+
|
|
439
|
+
Returns
|
|
440
|
+
-------
|
|
441
|
+
list of Refusal
|
|
442
|
+
The refusals since the last flush.
|
|
443
|
+
|
|
444
|
+
Raises
|
|
445
|
+
------
|
|
446
|
+
loop_link.errors.ViewerRefusedError
|
|
447
|
+
The viewer refused one or more objects and ``raise_on_refusal`` is true.
|
|
448
|
+
"""
|
|
449
|
+
self._ensure_connected()
|
|
450
|
+
deadline = time.monotonic() + settle
|
|
451
|
+
while True:
|
|
452
|
+
self._drain(max(0.001, min(0.05, deadline - time.monotonic())))
|
|
453
|
+
if time.monotonic() >= deadline:
|
|
454
|
+
break
|
|
455
|
+
refusals, self._refusals = self._refusals, []
|
|
456
|
+
if refusals and raise_on_refusal:
|
|
457
|
+
raise ViewerRefusedError(refusals)
|
|
458
|
+
return refusals
|
|
459
|
+
|
|
460
|
+
# -- selection ------------------------------------------------------------
|
|
461
|
+
|
|
462
|
+
def select(
|
|
463
|
+
self,
|
|
464
|
+
object_id: str,
|
|
465
|
+
*,
|
|
466
|
+
cells: Sequence[int] | np.ndarray | None = None,
|
|
467
|
+
vertices: Sequence[int] | np.ndarray | None = None,
|
|
468
|
+
revision: int | None = None,
|
|
469
|
+
) -> dict[str, int]:
|
|
470
|
+
"""Select cells and vertices of one object in the viewer.
|
|
471
|
+
|
|
472
|
+
Parameters
|
|
473
|
+
----------
|
|
474
|
+
object_id : str
|
|
475
|
+
The identifier of the object.
|
|
476
|
+
cells : sequence of int, optional
|
|
477
|
+
The cell indices. Each index is from 0 to 2**32-1.
|
|
478
|
+
vertices : sequence of int, optional
|
|
479
|
+
The vertex indices. Each index is from 0 to 2**32-1.
|
|
480
|
+
revision : int, optional
|
|
481
|
+
The revision that the selection is for. The viewer refuses an old revision.
|
|
482
|
+
|
|
483
|
+
Returns
|
|
484
|
+
-------
|
|
485
|
+
dict of str to int
|
|
486
|
+
The number of selected cells (key ``cell``) and vertices (key ``vertex``).
|
|
487
|
+
|
|
488
|
+
Raises
|
|
489
|
+
------
|
|
490
|
+
loop_link.errors.InvalidInputError
|
|
491
|
+
The id is not valid, no index list is given, an index list is not valid,
|
|
492
|
+
or the viewer refused the indices.
|
|
493
|
+
loop_link.errors.StaleRevisionError
|
|
494
|
+
The revision is old.
|
|
495
|
+
loop_link.errors.MissingFeatureError
|
|
496
|
+
The viewer does not support the selection.
|
|
497
|
+
loop_link.errors.ViewerClosedError
|
|
498
|
+
The connection is closed.
|
|
499
|
+
"""
|
|
500
|
+
if not isinstance(object_id, str) or not object_id:
|
|
501
|
+
raise InvalidInputError("The object_id must be a string that is not empty.")
|
|
502
|
+
if cells is None and vertices is None:
|
|
503
|
+
raise InvalidInputError(
|
|
504
|
+
"Give cells or vertices. Use an empty list to clear the selection."
|
|
505
|
+
)
|
|
506
|
+
cell_array = None if cells is None else _indices(cells, "cells")
|
|
507
|
+
vertex_array = None if vertices is None else _indices(vertices, "vertices")
|
|
508
|
+
tool = self._tool()
|
|
509
|
+
frame = tool.request(
|
|
510
|
+
lambda request: encode.selection_set_frame(
|
|
511
|
+
request, object_id, cell_array, vertex_array, revision
|
|
512
|
+
),
|
|
513
|
+
until=("selection.result",),
|
|
514
|
+
feature=_SELECTION_FEATURE,
|
|
515
|
+
object_id=object_id,
|
|
516
|
+
)
|
|
517
|
+
counts = {"cell": 0, "vertex": 0}
|
|
518
|
+
for entry in frame.header.get("entries") or []:
|
|
519
|
+
name = _KIND_NAMES.get(entry.get("kind"))
|
|
520
|
+
if name is not None:
|
|
521
|
+
counts[name] = int(entry.get("count", 0))
|
|
522
|
+
return counts
|
|
523
|
+
|
|
524
|
+
def selection(self) -> Selection:
|
|
525
|
+
"""Read the selection in the viewer.
|
|
526
|
+
|
|
527
|
+
Returns
|
|
528
|
+
-------
|
|
529
|
+
Selection
|
|
530
|
+
The selection. It is empty when nothing is selected.
|
|
531
|
+
|
|
532
|
+
Raises
|
|
533
|
+
------
|
|
534
|
+
loop_link.errors.MissingFeatureError
|
|
535
|
+
The viewer does not support the selection.
|
|
536
|
+
loop_link.errors.ViewerClosedError
|
|
537
|
+
The connection is closed.
|
|
538
|
+
"""
|
|
539
|
+
tool = self._tool()
|
|
540
|
+
frame = tool.request(
|
|
541
|
+
encode.selection_get_frame,
|
|
542
|
+
until=("selection.result",),
|
|
543
|
+
feature=_SELECTION_FEATURE,
|
|
544
|
+
)
|
|
545
|
+
return parse_selection_result(frame)
|
|
546
|
+
|
|
547
|
+
def watch_selection(
|
|
548
|
+
self,
|
|
549
|
+
callback: Callable[[Selection], None],
|
|
550
|
+
*,
|
|
551
|
+
interval: float = 0.5,
|
|
552
|
+
initial: bool = False,
|
|
553
|
+
) -> SelectionWatcher:
|
|
554
|
+
"""Call a function each time the selection in the viewer changes.
|
|
555
|
+
|
|
556
|
+
Parameters
|
|
557
|
+
----------
|
|
558
|
+
callback : callable
|
|
559
|
+
The function to call with the new ``Selection``.
|
|
560
|
+
interval : float
|
|
561
|
+
The time in seconds between two polls. It must be more than zero.
|
|
562
|
+
initial : bool
|
|
563
|
+
If true, call the function once with the current selection when it is
|
|
564
|
+
not empty.
|
|
565
|
+
|
|
566
|
+
Returns
|
|
567
|
+
-------
|
|
568
|
+
SelectionWatcher
|
|
569
|
+
The running watcher. Call its ``stop`` method to end it.
|
|
570
|
+
|
|
571
|
+
Raises
|
|
572
|
+
------
|
|
573
|
+
loop_link.errors.InvalidInputError
|
|
574
|
+
The interval is not more than zero.
|
|
575
|
+
loop_link.errors.MissingFeatureError
|
|
576
|
+
The viewer does not support the selection.
|
|
577
|
+
loop_link.errors.ViewerClosedError
|
|
578
|
+
The connection is closed.
|
|
579
|
+
"""
|
|
580
|
+
if not interval > 0:
|
|
581
|
+
raise InvalidInputError("The interval must be more than zero.")
|
|
582
|
+
last = self.selection()
|
|
583
|
+
if initial and not last.empty:
|
|
584
|
+
callback(last)
|
|
585
|
+
watcher = SelectionWatcher(weakref.ref(self), callback, interval, last)
|
|
586
|
+
self._watchers.append(watcher)
|
|
587
|
+
watcher.start()
|
|
588
|
+
return watcher
|
|
589
|
+
|
|
590
|
+
# -- filters --------------------------------------------------------------
|
|
591
|
+
|
|
592
|
+
def filter_range(
|
|
593
|
+
self,
|
|
594
|
+
object_id: str,
|
|
595
|
+
array: str,
|
|
596
|
+
minimum: float,
|
|
597
|
+
maximum: float,
|
|
598
|
+
*,
|
|
599
|
+
keep_nan: bool = False,
|
|
600
|
+
wait: bool = True,
|
|
601
|
+
cancel: threading.Event | None = None,
|
|
602
|
+
timeout: float = 60.0,
|
|
603
|
+
progress: Callable[[float], None] | None = None,
|
|
604
|
+
) -> FilterResult:
|
|
605
|
+
"""Keep the cells or vertices with an array value in a range.
|
|
606
|
+
|
|
607
|
+
Parameters
|
|
608
|
+
----------
|
|
609
|
+
object_id : str
|
|
610
|
+
The identifier of the object.
|
|
611
|
+
array : str
|
|
612
|
+
The name of a number array of the object.
|
|
613
|
+
minimum : float
|
|
614
|
+
The low limit of the range.
|
|
615
|
+
maximum : float
|
|
616
|
+
The high limit of the range. It is not less than ``minimum``.
|
|
617
|
+
keep_nan : bool
|
|
618
|
+
If true, keep the items that have no value (NaN).
|
|
619
|
+
wait : bool
|
|
620
|
+
If true, wait for the end of the filter build. If false, send the last edit and
|
|
621
|
+
return an empty result at once. A refusal of that edit is not seen.
|
|
622
|
+
cancel : threading.Event, optional
|
|
623
|
+
When it is set, the viewer cancels the build and the call raises ``CancelledError``.
|
|
624
|
+
timeout : float
|
|
625
|
+
The time in seconds to wait for the next frame of the viewer. It must be more
|
|
626
|
+
than zero.
|
|
627
|
+
progress : callable, optional
|
|
628
|
+
Called with the fraction of each progress frame of the build.
|
|
629
|
+
|
|
630
|
+
Returns
|
|
631
|
+
-------
|
|
632
|
+
FilterResult
|
|
633
|
+
The counts of the build. A field is ``None`` when the viewer gives no value.
|
|
634
|
+
|
|
635
|
+
Raises
|
|
636
|
+
------
|
|
637
|
+
loop_link.errors.CancelledError
|
|
638
|
+
The ``cancel`` event was set.
|
|
639
|
+
loop_link.errors.InvalidInputError
|
|
640
|
+
An argument is not valid, or the viewer refused the filter.
|
|
641
|
+
loop_link.errors.MissingFeatureError
|
|
642
|
+
The viewer does not support the filter commands.
|
|
643
|
+
loop_link.errors.ViewerClosedError
|
|
644
|
+
The connection is closed.
|
|
645
|
+
"""
|
|
646
|
+
object_id = check_text(object_id, "object_id")
|
|
647
|
+
array = check_text(array, "array")
|
|
648
|
+
low = check_number(minimum, "minimum")
|
|
649
|
+
high = check_number(maximum, "maximum")
|
|
650
|
+
if low > high:
|
|
651
|
+
raise InvalidInputError("'minimum' must not be more than 'maximum'.")
|
|
652
|
+
keep_nan = _check_bool(keep_nan, "keep_nan")
|
|
653
|
+
_check_wait(wait, timeout)
|
|
654
|
+
tool = self._tool()
|
|
655
|
+
self._filter_add(tool, object_id, array, cancel, timeout)
|
|
656
|
+
return _filter_edits(
|
|
657
|
+
tool,
|
|
658
|
+
object_id,
|
|
659
|
+
(
|
|
660
|
+
{
|
|
661
|
+
"kind": "set_range",
|
|
662
|
+
"array": array,
|
|
663
|
+
"min": format_number(low),
|
|
664
|
+
"max": format_number(high),
|
|
665
|
+
"keep_nan": keep_nan,
|
|
666
|
+
},
|
|
667
|
+
{"kind": "set_on", "array": array, "on": True},
|
|
668
|
+
),
|
|
669
|
+
wait=wait,
|
|
670
|
+
cancel=cancel,
|
|
671
|
+
timeout=timeout,
|
|
672
|
+
progress=progress,
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
def filter_values(
|
|
676
|
+
self,
|
|
677
|
+
object_id: str,
|
|
678
|
+
array: str,
|
|
679
|
+
values: Sequence[int] | np.ndarray,
|
|
680
|
+
*,
|
|
681
|
+
exclude: bool = False,
|
|
682
|
+
wait: bool = True,
|
|
683
|
+
cancel: threading.Event | None = None,
|
|
684
|
+
timeout: float = 60.0,
|
|
685
|
+
progress: Callable[[float], None] | None = None,
|
|
686
|
+
) -> FilterResult:
|
|
687
|
+
"""Keep the cells or vertices with an array value in a list of codes.
|
|
688
|
+
|
|
689
|
+
Parameters
|
|
690
|
+
----------
|
|
691
|
+
object_id : str
|
|
692
|
+
The identifier of the object.
|
|
693
|
+
array : str
|
|
694
|
+
The name of a category array of the object.
|
|
695
|
+
values : sequence of int
|
|
696
|
+
The category codes. Each code is from 0 to 2**32-1.
|
|
697
|
+
exclude : bool
|
|
698
|
+
If true, remove the items with these codes and keep the others.
|
|
699
|
+
wait : bool
|
|
700
|
+
If true, wait for the end of the filter build. If false, send the last edit and
|
|
701
|
+
return an empty result at once. A refusal of that edit is not seen.
|
|
702
|
+
cancel : threading.Event, optional
|
|
703
|
+
When it is set, the viewer cancels the build and the call raises ``CancelledError``.
|
|
704
|
+
timeout : float
|
|
705
|
+
The time in seconds to wait for the next frame of the viewer. It must be more
|
|
706
|
+
than zero.
|
|
707
|
+
progress : callable, optional
|
|
708
|
+
Called with the fraction of each progress frame of the build.
|
|
709
|
+
|
|
710
|
+
Returns
|
|
711
|
+
-------
|
|
712
|
+
FilterResult
|
|
713
|
+
The counts of the build. A field is ``None`` when the viewer gives no value.
|
|
714
|
+
|
|
715
|
+
Raises
|
|
716
|
+
------
|
|
717
|
+
loop_link.errors.CancelledError
|
|
718
|
+
The ``cancel`` event was set.
|
|
719
|
+
loop_link.errors.InvalidInputError
|
|
720
|
+
An argument is not valid, or the viewer refused the filter.
|
|
721
|
+
loop_link.errors.MissingFeatureError
|
|
722
|
+
The viewer does not support the filter commands.
|
|
723
|
+
loop_link.errors.ViewerClosedError
|
|
724
|
+
The connection is closed.
|
|
725
|
+
"""
|
|
726
|
+
object_id = check_text(object_id, "object_id")
|
|
727
|
+
array = check_text(array, "array")
|
|
728
|
+
codes = check_codes(values, "values")
|
|
729
|
+
exclude = _check_bool(exclude, "exclude")
|
|
730
|
+
_check_wait(wait, timeout)
|
|
731
|
+
tool = self._tool()
|
|
732
|
+
self._filter_add(tool, object_id, array, cancel, timeout)
|
|
733
|
+
return _filter_edits(
|
|
734
|
+
tool,
|
|
735
|
+
object_id,
|
|
736
|
+
(
|
|
737
|
+
{"kind": "set_values", "array": array, "values": codes},
|
|
738
|
+
{"kind": "set_exclude", "array": array, "exclude": exclude},
|
|
739
|
+
{"kind": "set_on", "array": array, "on": True},
|
|
740
|
+
),
|
|
741
|
+
wait=wait,
|
|
742
|
+
cancel=cancel,
|
|
743
|
+
timeout=timeout,
|
|
744
|
+
progress=progress,
|
|
745
|
+
)
|
|
746
|
+
|
|
747
|
+
def filter_enable(
|
|
748
|
+
self,
|
|
749
|
+
object_id: str,
|
|
750
|
+
array: str,
|
|
751
|
+
on: bool = True,
|
|
752
|
+
*,
|
|
753
|
+
wait: bool = True,
|
|
754
|
+
cancel: threading.Event | None = None,
|
|
755
|
+
timeout: float = 60.0,
|
|
756
|
+
progress: Callable[[float], None] | None = None,
|
|
757
|
+
) -> FilterResult:
|
|
758
|
+
"""Turn the filter of one array on or off.
|
|
759
|
+
|
|
760
|
+
Parameters
|
|
761
|
+
----------
|
|
762
|
+
object_id : str
|
|
763
|
+
The identifier of the object.
|
|
764
|
+
array : str
|
|
765
|
+
The name of the array of the filter.
|
|
766
|
+
on : bool
|
|
767
|
+
True to turn the filter on, false to turn it off.
|
|
768
|
+
wait : bool
|
|
769
|
+
If true, wait for the end of the filter build. If false, send the edit and
|
|
770
|
+
return an empty result at once.
|
|
771
|
+
cancel : threading.Event, optional
|
|
772
|
+
When it is set, the viewer cancels the build and the call raises ``CancelledError``.
|
|
773
|
+
timeout : float
|
|
774
|
+
The time in seconds to wait for the next frame of the viewer. It must be more
|
|
775
|
+
than zero.
|
|
776
|
+
progress : callable, optional
|
|
777
|
+
Called with the fraction of each progress frame of the build.
|
|
778
|
+
|
|
779
|
+
Returns
|
|
780
|
+
-------
|
|
781
|
+
FilterResult
|
|
782
|
+
The counts of the build. A field is ``None`` when the viewer gives no value.
|
|
783
|
+
|
|
784
|
+
Raises
|
|
785
|
+
------
|
|
786
|
+
loop_link.errors.CancelledError
|
|
787
|
+
The ``cancel`` event was set.
|
|
788
|
+
loop_link.errors.InvalidInputError
|
|
789
|
+
An argument is not valid, or the viewer refused the command.
|
|
790
|
+
loop_link.errors.MissingFeatureError
|
|
791
|
+
The viewer does not support the filter commands.
|
|
792
|
+
loop_link.errors.ViewerClosedError
|
|
793
|
+
The connection is closed.
|
|
794
|
+
"""
|
|
795
|
+
object_id = check_text(object_id, "object_id")
|
|
796
|
+
array = check_text(array, "array")
|
|
797
|
+
on = _check_bool(on, "on")
|
|
798
|
+
_check_wait(wait, timeout)
|
|
799
|
+
return _filter_edits(
|
|
800
|
+
self._tool(),
|
|
801
|
+
object_id,
|
|
802
|
+
({"kind": "set_on", "array": array, "on": on},),
|
|
803
|
+
wait=wait,
|
|
804
|
+
cancel=cancel,
|
|
805
|
+
timeout=timeout,
|
|
806
|
+
progress=progress,
|
|
807
|
+
)
|
|
808
|
+
|
|
809
|
+
def filter_remove(
|
|
810
|
+
self,
|
|
811
|
+
object_id: str,
|
|
812
|
+
array: str,
|
|
813
|
+
*,
|
|
814
|
+
wait: bool = True,
|
|
815
|
+
cancel: threading.Event | None = None,
|
|
816
|
+
timeout: float = 60.0,
|
|
817
|
+
progress: Callable[[float], None] | None = None,
|
|
818
|
+
) -> FilterResult:
|
|
819
|
+
"""Remove the filter of one array.
|
|
820
|
+
|
|
821
|
+
Parameters
|
|
822
|
+
----------
|
|
823
|
+
object_id : str
|
|
824
|
+
The identifier of the object.
|
|
825
|
+
array : str
|
|
826
|
+
The name of the array of the filter.
|
|
827
|
+
wait : bool
|
|
828
|
+
If true, wait for the end of the filter build. If false, send the edit and
|
|
829
|
+
return an empty result at once.
|
|
830
|
+
cancel : threading.Event, optional
|
|
831
|
+
When it is set, the viewer cancels the build and the call raises ``CancelledError``.
|
|
832
|
+
timeout : float
|
|
833
|
+
The time in seconds to wait for the next frame of the viewer. It must be more
|
|
834
|
+
than zero.
|
|
835
|
+
progress : callable, optional
|
|
836
|
+
Called with the fraction of each progress frame of the build.
|
|
837
|
+
|
|
838
|
+
Returns
|
|
839
|
+
-------
|
|
840
|
+
FilterResult
|
|
841
|
+
The counts of the build. A field is ``None`` when the viewer gives no value.
|
|
842
|
+
|
|
843
|
+
Raises
|
|
844
|
+
------
|
|
845
|
+
loop_link.errors.CancelledError
|
|
846
|
+
The ``cancel`` event was set.
|
|
847
|
+
loop_link.errors.InvalidInputError
|
|
848
|
+
An argument is not valid, or the viewer refused the command.
|
|
849
|
+
loop_link.errors.MissingFeatureError
|
|
850
|
+
The viewer does not support the filter commands.
|
|
851
|
+
loop_link.errors.ViewerClosedError
|
|
852
|
+
The connection is closed.
|
|
853
|
+
"""
|
|
854
|
+
object_id = check_text(object_id, "object_id")
|
|
855
|
+
array = check_text(array, "array")
|
|
856
|
+
_check_wait(wait, timeout)
|
|
857
|
+
return _filter_edits(
|
|
858
|
+
self._tool(),
|
|
859
|
+
object_id,
|
|
860
|
+
({"kind": "remove", "array": array},),
|
|
861
|
+
wait=wait,
|
|
862
|
+
cancel=cancel,
|
|
863
|
+
timeout=timeout,
|
|
864
|
+
progress=progress,
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
def cancel_filter(self, object_id: str) -> None:
|
|
868
|
+
"""Cancel the filter build that runs for one object.
|
|
869
|
+
|
|
870
|
+
Parameters
|
|
871
|
+
----------
|
|
872
|
+
object_id : str
|
|
873
|
+
The identifier of the object.
|
|
874
|
+
|
|
875
|
+
Raises
|
|
876
|
+
------
|
|
877
|
+
loop_link.errors.InvalidInputError
|
|
878
|
+
The id is not valid, or the viewer refused the command.
|
|
879
|
+
loop_link.errors.MissingFeatureError
|
|
880
|
+
The viewer does not support the filter commands.
|
|
881
|
+
loop_link.errors.ViewerClosedError
|
|
882
|
+
The connection is closed.
|
|
883
|
+
"""
|
|
884
|
+
object_id = check_text(object_id, "object_id")
|
|
885
|
+
_filter_edit(self._tool(), object_id, {"kind": "cancel"})
|
|
886
|
+
|
|
887
|
+
@staticmethod
|
|
888
|
+
def _filter_add(
|
|
889
|
+
tool: ToolConnection,
|
|
890
|
+
object_id: str,
|
|
891
|
+
array: str,
|
|
892
|
+
cancel: threading.Event | None,
|
|
893
|
+
timeout: float,
|
|
894
|
+
) -> None:
|
|
895
|
+
"""Add a filter. A refusal is not an error: the filter can exist already."""
|
|
896
|
+
try:
|
|
897
|
+
_filter_edit(tool, object_id, {"kind": "add", "array": array}, cancel, timeout)
|
|
898
|
+
except InvalidInputError:
|
|
899
|
+
pass
|
|
900
|
+
|
|
901
|
+
# -- colour ---------------------------------------------------------------
|
|
902
|
+
|
|
903
|
+
def colour_map_names(self) -> tuple[str, ...]:
|
|
904
|
+
"""Return the names of the colour maps of the viewer.
|
|
905
|
+
|
|
906
|
+
The names are kept until the viewer is closed.
|
|
907
|
+
|
|
908
|
+
Returns
|
|
909
|
+
-------
|
|
910
|
+
tuple of str
|
|
911
|
+
The names.
|
|
912
|
+
|
|
913
|
+
Raises
|
|
914
|
+
------
|
|
915
|
+
loop_link.errors.MissingFeatureError
|
|
916
|
+
The viewer does not give the names.
|
|
917
|
+
loop_link.errors.ViewerClosedError
|
|
918
|
+
The connection is closed.
|
|
919
|
+
"""
|
|
920
|
+
names = self._read_colour_map_names(self._tool())
|
|
921
|
+
if names is None:
|
|
922
|
+
raise MissingFeatureError("colour map names (geoviewer protocol 1.18)")
|
|
923
|
+
return names
|
|
924
|
+
|
|
925
|
+
def set_colour_property(self, object_id: str, array: str | None) -> None:
|
|
926
|
+
"""Set the array that colours an object.
|
|
927
|
+
|
|
928
|
+
Parameters
|
|
929
|
+
----------
|
|
930
|
+
object_id : str
|
|
931
|
+
The identifier of the object.
|
|
932
|
+
array : str or None
|
|
933
|
+
The name of the array. ``None`` shows no array.
|
|
934
|
+
|
|
935
|
+
Raises
|
|
936
|
+
------
|
|
937
|
+
loop_link.errors.InvalidInputError
|
|
938
|
+
An argument is not valid, or the viewer refused the command.
|
|
939
|
+
loop_link.errors.MissingFeatureError
|
|
940
|
+
The viewer does not support the colour commands.
|
|
941
|
+
loop_link.errors.ViewerClosedError
|
|
942
|
+
The connection is closed.
|
|
943
|
+
"""
|
|
944
|
+
object_id = check_text(object_id, "object_id")
|
|
945
|
+
body: dict[str, Any] = {"id": object_id}
|
|
946
|
+
if array is not None:
|
|
947
|
+
body["array"] = check_text(array, "array")
|
|
948
|
+
run_command(self._tool(), "colour.set_active", body, object_id=object_id)
|
|
949
|
+
|
|
950
|
+
def set_colour_map(self, object_id: str, name: str) -> None:
|
|
951
|
+
"""Set the colour map of an object.
|
|
952
|
+
|
|
953
|
+
Parameters
|
|
954
|
+
----------
|
|
955
|
+
object_id : str
|
|
956
|
+
The identifier of the object.
|
|
957
|
+
name : str
|
|
958
|
+
The name of the colour map.
|
|
959
|
+
|
|
960
|
+
Raises
|
|
961
|
+
------
|
|
962
|
+
loop_link.errors.InvalidInputError
|
|
963
|
+
An argument is not valid, the name is not known, or the viewer refused
|
|
964
|
+
the command.
|
|
965
|
+
loop_link.errors.MissingFeatureError
|
|
966
|
+
The viewer does not support the colour commands.
|
|
967
|
+
loop_link.errors.ViewerClosedError
|
|
968
|
+
The connection is closed.
|
|
969
|
+
"""
|
|
970
|
+
object_id = check_text(object_id, "object_id")
|
|
971
|
+
name = check_text(name, "name")
|
|
972
|
+
tool = self._tool()
|
|
973
|
+
self._check_colour_map(tool, name)
|
|
974
|
+
run_command(tool, "colour.set_map", {"id": object_id, "name": name}, object_id=object_id)
|
|
975
|
+
|
|
976
|
+
def set_colour_range(self, object_id: str, minimum: float, maximum: float) -> None:
|
|
977
|
+
"""Set the colour range of an object.
|
|
978
|
+
|
|
979
|
+
Parameters
|
|
980
|
+
----------
|
|
981
|
+
object_id : str
|
|
982
|
+
The identifier of the object.
|
|
983
|
+
minimum : float
|
|
984
|
+
The low limit of the range.
|
|
985
|
+
maximum : float
|
|
986
|
+
The high limit of the range. It is more than ``minimum``.
|
|
987
|
+
|
|
988
|
+
Raises
|
|
989
|
+
------
|
|
990
|
+
loop_link.errors.InvalidInputError
|
|
991
|
+
An argument is not valid, or the viewer refused the command.
|
|
992
|
+
loop_link.errors.MissingFeatureError
|
|
993
|
+
The viewer does not support the colour commands.
|
|
994
|
+
loop_link.errors.ViewerClosedError
|
|
995
|
+
The connection is closed.
|
|
996
|
+
"""
|
|
997
|
+
object_id = check_text(object_id, "object_id")
|
|
998
|
+
low = check_number(minimum, "minimum")
|
|
999
|
+
high = check_number(maximum, "maximum")
|
|
1000
|
+
if not low < high:
|
|
1001
|
+
raise InvalidInputError("'minimum' must be less than 'maximum'.")
|
|
1002
|
+
body = {"id": object_id, "min": format_number(low), "max": format_number(high)}
|
|
1003
|
+
run_command(self._tool(), "colour.set_range", body, object_id=object_id)
|
|
1004
|
+
|
|
1005
|
+
def clear_colour_range(self, object_id: str) -> None:
|
|
1006
|
+
"""Remove the colour range of an object.
|
|
1007
|
+
|
|
1008
|
+
Parameters
|
|
1009
|
+
----------
|
|
1010
|
+
object_id : str
|
|
1011
|
+
The identifier of the object.
|
|
1012
|
+
|
|
1013
|
+
Raises
|
|
1014
|
+
------
|
|
1015
|
+
loop_link.errors.InvalidInputError
|
|
1016
|
+
The id is not valid, or the viewer refused the command.
|
|
1017
|
+
loop_link.errors.MissingFeatureError
|
|
1018
|
+
The viewer does not support the colour commands.
|
|
1019
|
+
loop_link.errors.ViewerClosedError
|
|
1020
|
+
The connection is closed.
|
|
1021
|
+
"""
|
|
1022
|
+
object_id = check_text(object_id, "object_id")
|
|
1023
|
+
run_command(self._tool(), "colour.clear_range", {"id": object_id}, object_id=object_id)
|
|
1024
|
+
|
|
1025
|
+
def set_colour_scale(self, object_id: str, scale: str) -> None:
|
|
1026
|
+
"""Set the colour scale of an object.
|
|
1027
|
+
|
|
1028
|
+
Parameters
|
|
1029
|
+
----------
|
|
1030
|
+
object_id : str
|
|
1031
|
+
The identifier of the object.
|
|
1032
|
+
scale : str
|
|
1033
|
+
The scale, ``"linear"`` or ``"log"``.
|
|
1034
|
+
|
|
1035
|
+
Raises
|
|
1036
|
+
------
|
|
1037
|
+
loop_link.errors.InvalidInputError
|
|
1038
|
+
An argument is not valid, or the viewer refused the command.
|
|
1039
|
+
loop_link.errors.MissingFeatureError
|
|
1040
|
+
The viewer does not support the colour scale.
|
|
1041
|
+
loop_link.errors.ViewerClosedError
|
|
1042
|
+
The connection is closed.
|
|
1043
|
+
"""
|
|
1044
|
+
object_id = check_text(object_id, "object_id")
|
|
1045
|
+
if scale not in _COLOUR_SCALES:
|
|
1046
|
+
raise InvalidInputError(f"'scale' must be 'linear' or 'log'. Got {scale!r}.")
|
|
1047
|
+
body = {"object": object_id, "scale": scale}
|
|
1048
|
+
run_command(self._tool(), "colour.set_scale", body, object_id=object_id)
|
|
1049
|
+
|
|
1050
|
+
def set_object_colour(self, object_id: str, colour: Sequence[int] | None) -> None:
|
|
1051
|
+
"""Set the plain colour of an object.
|
|
1052
|
+
|
|
1053
|
+
Parameters
|
|
1054
|
+
----------
|
|
1055
|
+
object_id : str
|
|
1056
|
+
The identifier of the object.
|
|
1057
|
+
colour : sequence of int or None
|
|
1058
|
+
The red, green and blue values from 0 to 255. ``None`` removes the plain colour.
|
|
1059
|
+
|
|
1060
|
+
Raises
|
|
1061
|
+
------
|
|
1062
|
+
loop_link.errors.InvalidInputError
|
|
1063
|
+
An argument is not valid, or the viewer refused the command.
|
|
1064
|
+
loop_link.errors.MissingFeatureError
|
|
1065
|
+
The viewer does not support the colour commands.
|
|
1066
|
+
loop_link.errors.ViewerClosedError
|
|
1067
|
+
The connection is closed.
|
|
1068
|
+
"""
|
|
1069
|
+
object_id = check_text(object_id, "object_id")
|
|
1070
|
+
value = None if colour is None else list(check_rgb(colour, "colour"))
|
|
1071
|
+
body = {"id": object_id, "colour": value}
|
|
1072
|
+
run_command(self._tool(), "object.set_colour", body, object_id=object_id)
|
|
1073
|
+
|
|
1074
|
+
def apply_colour(self, object_id: str, settings: ColourSettings) -> None:
|
|
1075
|
+
"""Apply the colour settings of an object.
|
|
1076
|
+
|
|
1077
|
+
The commands go in this order: array, colour map, range, scale, plain colour.
|
|
1078
|
+
A field that is ``None`` sends no command.
|
|
1079
|
+
|
|
1080
|
+
Parameters
|
|
1081
|
+
----------
|
|
1082
|
+
object_id : str
|
|
1083
|
+
The identifier of the object.
|
|
1084
|
+
settings : loop_link.commands.ColourSettings
|
|
1085
|
+
The colour settings.
|
|
1086
|
+
|
|
1087
|
+
Raises
|
|
1088
|
+
------
|
|
1089
|
+
loop_link.errors.InvalidInputError
|
|
1090
|
+
An argument is not valid, or the viewer refused a command.
|
|
1091
|
+
loop_link.errors.MissingFeatureError
|
|
1092
|
+
The viewer does not support the colour commands.
|
|
1093
|
+
loop_link.errors.ViewerClosedError
|
|
1094
|
+
The connection is closed.
|
|
1095
|
+
"""
|
|
1096
|
+
object_id = check_text(object_id, "object_id")
|
|
1097
|
+
if not isinstance(settings, ColourSettings):
|
|
1098
|
+
raise InvalidInputError("The settings must be a ColourSettings object.")
|
|
1099
|
+
if settings.array is not None:
|
|
1100
|
+
self.set_colour_property(object_id, settings.array)
|
|
1101
|
+
if settings.colour_map is not None:
|
|
1102
|
+
self.set_colour_map(object_id, settings.colour_map)
|
|
1103
|
+
if settings.range is not None:
|
|
1104
|
+
self.set_colour_range(object_id, *settings.range)
|
|
1105
|
+
if settings.scale is not None:
|
|
1106
|
+
self.set_colour_scale(object_id, settings.scale)
|
|
1107
|
+
if settings.plain is not None:
|
|
1108
|
+
self.set_object_colour(object_id, settings.plain)
|
|
1109
|
+
|
|
1110
|
+
def _read_colour_map_names(self, tool: ToolConnection) -> tuple[str, ...] | None:
|
|
1111
|
+
"""Return the colour map names. Ask the viewer at the first call only."""
|
|
1112
|
+
if self._colour_map_names is None:
|
|
1113
|
+
self._colour_map_names = list_colour_map_names(tool)
|
|
1114
|
+
return self._colour_map_names
|
|
1115
|
+
|
|
1116
|
+
def _check_colour_map(self, tool: ToolConnection, name: str) -> None:
|
|
1117
|
+
"""Raise when the viewer has names and ``name`` is not one of them."""
|
|
1118
|
+
names = self._read_colour_map_names(tool)
|
|
1119
|
+
if names is not None and name not in names:
|
|
1120
|
+
raise InvalidInputError(
|
|
1121
|
+
f"The viewer has no colour map '{name}'. The names are: {', '.join(names)}."
|
|
1122
|
+
)
|
|
1123
|
+
|
|
1124
|
+
# -- fetching -------------------------------------------------------------
|
|
1125
|
+
|
|
1126
|
+
def fetch(
|
|
1127
|
+
self,
|
|
1128
|
+
id: str,
|
|
1129
|
+
*,
|
|
1130
|
+
progress: Callable[[float], None] | None = None,
|
|
1131
|
+
cancel: threading.Event | None = None,
|
|
1132
|
+
) -> FetchResult:
|
|
1133
|
+
"""Read one object from the viewer.
|
|
1134
|
+
|
|
1135
|
+
This method uses the tool connection. It does not open the data connection.
|
|
1136
|
+
|
|
1137
|
+
Parameters
|
|
1138
|
+
----------
|
|
1139
|
+
id : str
|
|
1140
|
+
The identifier of the object.
|
|
1141
|
+
progress : callable, optional
|
|
1142
|
+
The function to call with the fraction done, from 0 to 1.
|
|
1143
|
+
cancel : threading.Event, optional
|
|
1144
|
+
When this event is set, the fetch stops.
|
|
1145
|
+
|
|
1146
|
+
Returns
|
|
1147
|
+
-------
|
|
1148
|
+
FetchResult
|
|
1149
|
+
The object, with its id, type, revision and name.
|
|
1150
|
+
|
|
1151
|
+
Raises
|
|
1152
|
+
------
|
|
1153
|
+
loop_link.errors.InvalidInputError
|
|
1154
|
+
The id is not valid, or the viewer does not know the id.
|
|
1155
|
+
loop_link.errors.CancelledError
|
|
1156
|
+
The ``cancel`` event was set.
|
|
1157
|
+
loop_link.errors.MissingFeatureError
|
|
1158
|
+
The viewer does not support the fetch.
|
|
1159
|
+
loop_link.errors.ViewerClosedError
|
|
1160
|
+
The connection is closed, or the viewer sent an object that is not valid.
|
|
1161
|
+
loop_link.errors.UnsupportedObjectError
|
|
1162
|
+
The viewer sent an object type that this package cannot read.
|
|
1163
|
+
loop_link.errors.NoViewerError
|
|
1164
|
+
No viewer was found.
|
|
1165
|
+
loop_link.errors.TokenError
|
|
1166
|
+
The viewer refused the token.
|
|
1167
|
+
loop_link.errors.ObjectTooLargeError
|
|
1168
|
+
The object is larger than the limit.
|
|
1169
|
+
"""
|
|
1170
|
+
if not isinstance(id, str) or not id:
|
|
1171
|
+
raise InvalidInputError("The id must be a string that is not empty.")
|
|
1172
|
+
tool = self._tool()
|
|
1173
|
+
return fetch_object(tool, id, progress=progress, cancel=cancel)
|
|
1174
|
+
|
|
1175
|
+
# -- closing --------------------------------------------------------------
|
|
1176
|
+
|
|
1177
|
+
def release_data(self) -> None:
|
|
1178
|
+
"""Close the connection so another client can own the scene.
|
|
1179
|
+
|
|
1180
|
+
A later ``send`` opens a new connection. The revision numbers stay. The
|
|
1181
|
+
tool connection stays open. A later ``send`` also opens a new connection
|
|
1182
|
+
after the connection fails.
|
|
1183
|
+
"""
|
|
1184
|
+
self._stop_thread()
|
|
1185
|
+
self._drop_client()
|
|
1186
|
+
|
|
1187
|
+
def close(self) -> None:
|
|
1188
|
+
"""Close the connection and stop all selection watchers. The revision numbers stay."""
|
|
1189
|
+
watchers, self._watchers = self._watchers, []
|
|
1190
|
+
for watcher in watchers:
|
|
1191
|
+
watcher.stop()
|
|
1192
|
+
with self._tool_lock:
|
|
1193
|
+
self._closed = True
|
|
1194
|
+
tool, self._tool_connection = self._tool_connection, None
|
|
1195
|
+
self._colour_map_names = None
|
|
1196
|
+
if tool is not None:
|
|
1197
|
+
tool.close()
|
|
1198
|
+
self._stop_thread()
|
|
1199
|
+
self._drop_client()
|
|
1200
|
+
self._dead = True
|
|
1201
|
+
with self._address_lock:
|
|
1202
|
+
self._address = None
|
|
1203
|
+
|
|
1204
|
+
# -- helpers --------------------------------------------------------------
|
|
1205
|
+
|
|
1206
|
+
def _tool(self) -> ToolConnection:
|
|
1207
|
+
"""Return the tool connection. Make it at the first call."""
|
|
1208
|
+
if self._closed:
|
|
1209
|
+
raise ViewerClosedError
|
|
1210
|
+
with self._tool_lock:
|
|
1211
|
+
if self._closed:
|
|
1212
|
+
raise ViewerClosedError
|
|
1213
|
+
if self._tool_connection is None:
|
|
1214
|
+
self._tool_connection = ToolConnection(
|
|
1215
|
+
timeout=self._timeout, resolve=self._resolve_address
|
|
1216
|
+
)
|
|
1217
|
+
return self._tool_connection
|
|
1218
|
+
|
|
1219
|
+
def _resolve_address(self) -> discovery.ViewerAddress:
|
|
1220
|
+
"""Return the address of the viewer.
|
|
1221
|
+
|
|
1222
|
+
While the data connection or the tool connection is open, the known address
|
|
1223
|
+
is used again, so that both connections go to the same viewer. Otherwise the
|
|
1224
|
+
viewer is found again.
|
|
1225
|
+
"""
|
|
1226
|
+
with self._address_lock:
|
|
1227
|
+
tool = self._tool_connection
|
|
1228
|
+
in_use = (self._client is not None and not self._dead) or (
|
|
1229
|
+
tool is not None and tool.connected
|
|
1230
|
+
)
|
|
1231
|
+
if self._address is None or not in_use:
|
|
1232
|
+
self._address = discovery.find_viewer(
|
|
1233
|
+
port=self._port,
|
|
1234
|
+
token=self._token,
|
|
1235
|
+
host=self._host,
|
|
1236
|
+
settings=self._settings_dir,
|
|
1237
|
+
)
|
|
1238
|
+
return self._address
|
|
1239
|
+
|
|
1240
|
+
def _forget_address(self) -> None:
|
|
1241
|
+
"""Forget the known address and close the tool connection that uses it."""
|
|
1242
|
+
with self._tool_lock:
|
|
1243
|
+
tool = self._tool_connection
|
|
1244
|
+
self._colour_map_names = None
|
|
1245
|
+
if tool is not None:
|
|
1246
|
+
tool.close()
|
|
1247
|
+
with self._address_lock:
|
|
1248
|
+
self._address = None
|
|
1249
|
+
|
|
1250
|
+
def _ensure_connected(self) -> None:
|
|
1251
|
+
if self._closed:
|
|
1252
|
+
raise ViewerClosedError
|
|
1253
|
+
if self._client is None:
|
|
1254
|
+
self.connect()
|
|
1255
|
+
elif self._dead:
|
|
1256
|
+
# The last connection failed: open a new one. If the viewer is gone, give
|
|
1257
|
+
# the error of a closed viewer, as the failed send did.
|
|
1258
|
+
try:
|
|
1259
|
+
self.connect()
|
|
1260
|
+
except NoViewerError as error:
|
|
1261
|
+
raise ViewerClosedError(
|
|
1262
|
+
"The viewer closed the connection and no viewer was found again. "
|
|
1263
|
+
"Start geoviewer and turn the link on, then send again."
|
|
1264
|
+
) from error
|
|
1265
|
+
|
|
1266
|
+
def _drop_client(self) -> None:
|
|
1267
|
+
"""Close the socket, if there is one."""
|
|
1268
|
+
with self._lock:
|
|
1269
|
+
client, self._client = self._client, None
|
|
1270
|
+
self._shared["client"] = None
|
|
1271
|
+
if client is not None:
|
|
1272
|
+
_close_client(client)
|
|
1273
|
+
|
|
1274
|
+
def _next_revision(self, id: str) -> int:
|
|
1275
|
+
return max(self._revisions.get(id, 0), self._inventory_revisions.get(id, 0)) + 1
|
|
1276
|
+
|
|
1277
|
+
def _send_frame(self, data: bytes) -> None:
|
|
1278
|
+
with self._lock:
|
|
1279
|
+
client = self._client
|
|
1280
|
+
if client is None:
|
|
1281
|
+
raise ViewerClosedError
|
|
1282
|
+
try:
|
|
1283
|
+
client.send_binary(data)
|
|
1284
|
+
self._last_send = time.monotonic()
|
|
1285
|
+
self._drain_locked(client, 0.001)
|
|
1286
|
+
except _LINK_ERRORS as error:
|
|
1287
|
+
self._dead = True
|
|
1288
|
+
raise ViewerClosedError from error
|
|
1289
|
+
|
|
1290
|
+
def _drain(self, wait: float) -> None:
|
|
1291
|
+
with self._lock:
|
|
1292
|
+
client = self._client
|
|
1293
|
+
if client is None:
|
|
1294
|
+
raise ViewerClosedError
|
|
1295
|
+
try:
|
|
1296
|
+
self._drain_locked(client, wait)
|
|
1297
|
+
except _LINK_ERRORS as error:
|
|
1298
|
+
self._dead = True
|
|
1299
|
+
raise ViewerClosedError from error
|
|
1300
|
+
|
|
1301
|
+
def _drain_locked(self, client: WebSocketClient, wait: float) -> None:
|
|
1302
|
+
"""Read all waiting frames. The caller holds the lock."""
|
|
1303
|
+
while True:
|
|
1304
|
+
data = client.receive(wait)
|
|
1305
|
+
if data is None:
|
|
1306
|
+
return
|
|
1307
|
+
try:
|
|
1308
|
+
header = protocol.decode_frame(data).header
|
|
1309
|
+
except ProtocolError as error:
|
|
1310
|
+
self._dead = True
|
|
1311
|
+
_close_client(client)
|
|
1312
|
+
raise ViewerClosedError(
|
|
1313
|
+
"The viewer sent a frame that is not valid. The connection is closed."
|
|
1314
|
+
) from error
|
|
1315
|
+
if header.get("type") == "error" and header.get("object") is not None:
|
|
1316
|
+
self._refusals.append(
|
|
1317
|
+
Refusal(
|
|
1318
|
+
str(header["object"]),
|
|
1319
|
+
str(header.get("code", "")),
|
|
1320
|
+
str(header.get("message", "")),
|
|
1321
|
+
)
|
|
1322
|
+
)
|
|
1323
|
+
wait = 0.001
|
|
1324
|
+
|
|
1325
|
+
def _heartbeat_tick(self) -> bool:
|
|
1326
|
+
"""Do one keepalive step. Return False when the thread must stop."""
|
|
1327
|
+
if not self._lock.acquire(blocking=False):
|
|
1328
|
+
return True
|
|
1329
|
+
try:
|
|
1330
|
+
client = self._client
|
|
1331
|
+
if client is None or self._dead:
|
|
1332
|
+
return False
|
|
1333
|
+
try:
|
|
1334
|
+
self._drain_locked(client, 0.001)
|
|
1335
|
+
except _LINK_ERRORS + (ViewerClosedError,):
|
|
1336
|
+
self._dead = True
|
|
1337
|
+
return False
|
|
1338
|
+
if time.monotonic() - self._last_send < self._heartbeat_interval:
|
|
1339
|
+
return True
|
|
1340
|
+
self._seq += 1
|
|
1341
|
+
try:
|
|
1342
|
+
client.send_binary(encode.heartbeat_frame(self._seq))
|
|
1343
|
+
self._last_send = time.monotonic()
|
|
1344
|
+
except _LINK_ERRORS:
|
|
1345
|
+
self._dead = True
|
|
1346
|
+
return False
|
|
1347
|
+
return True
|
|
1348
|
+
finally:
|
|
1349
|
+
self._lock.release()
|
|
1350
|
+
|
|
1351
|
+
def _stop_thread(self) -> None:
|
|
1352
|
+
thread, self._thread = self._thread, None
|
|
1353
|
+
self._stop.set()
|
|
1354
|
+
if thread is not None and thread is not threading.current_thread():
|
|
1355
|
+
thread.join(timeout=2 * self._heartbeat_interval)
|
|
1356
|
+
|
|
1357
|
+
|
|
1358
|
+
def _triple(values: Sequence[float]) -> tuple[float, float, float]:
|
|
1359
|
+
"""Return three floats from a sequence of three numbers."""
|
|
1360
|
+
x, y, z = (float(v) for v in values)
|
|
1361
|
+
return (x, y, z)
|
|
1362
|
+
|
|
1363
|
+
|
|
1364
|
+
def _indices(values: Any, name: str) -> np.ndarray: # noqa: ANN401
|
|
1365
|
+
"""Return a 1-D ``uint32`` array from index values. Raise InvalidInputError if bad."""
|
|
1366
|
+
try:
|
|
1367
|
+
array = np.asarray(values)
|
|
1368
|
+
except (TypeError, ValueError) as error:
|
|
1369
|
+
raise InvalidInputError(f"The {name} must be a list of integers.") from error
|
|
1370
|
+
if array.size == 0 and array.ndim == 1:
|
|
1371
|
+
return np.empty(0, dtype=np.uint32)
|
|
1372
|
+
if array.dtype.kind not in "iu":
|
|
1373
|
+
raise InvalidInputError(f"The {name} must be integers. Do not use float or bool values.")
|
|
1374
|
+
if array.ndim != 1:
|
|
1375
|
+
raise InvalidInputError(f"The {name} must be a 1-D list of integers.")
|
|
1376
|
+
if array.min() < 0 or array.max() > _INDEX_MAX:
|
|
1377
|
+
raise InvalidInputError(f"The {name} must be from 0 to {_INDEX_MAX}.")
|
|
1378
|
+
return array.astype(np.uint32)
|
|
1379
|
+
|
|
1380
|
+
|
|
1381
|
+
def _check_bool(value: object, name: str) -> bool:
|
|
1382
|
+
"""Return a value that must be a ``bool``. Raise InvalidInputError if it is not."""
|
|
1383
|
+
if not isinstance(value, bool):
|
|
1384
|
+
raise InvalidInputError(f"'{name}' must be True or False. Got {value!r}.")
|
|
1385
|
+
return value
|
|
1386
|
+
|
|
1387
|
+
|
|
1388
|
+
def _check_wait(wait: object, timeout: object) -> None:
|
|
1389
|
+
"""Check the ``wait`` and ``timeout`` arguments of a filter call."""
|
|
1390
|
+
_check_bool(wait, "wait")
|
|
1391
|
+
if check_number(timeout, "timeout") <= 0:
|
|
1392
|
+
raise InvalidInputError("'timeout' must be more than zero.")
|
|
1393
|
+
|
|
1394
|
+
|
|
1395
|
+
def _filter_edit(
|
|
1396
|
+
tool: ToolConnection,
|
|
1397
|
+
object_id: str,
|
|
1398
|
+
edit: dict[str, Any],
|
|
1399
|
+
cancel: threading.Event | None = None,
|
|
1400
|
+
timeout: float | None = None,
|
|
1401
|
+
progress: Callable[[float], None] | None = None,
|
|
1402
|
+
) -> Mapping[str, Any]:
|
|
1403
|
+
"""Send one ``filter.edit`` command and wait for its result."""
|
|
1404
|
+
return run_command(
|
|
1405
|
+
tool,
|
|
1406
|
+
"filter.edit",
|
|
1407
|
+
{"object": object_id, "edit": edit},
|
|
1408
|
+
object_id=object_id,
|
|
1409
|
+
cancel=cancel,
|
|
1410
|
+
timeout=timeout,
|
|
1411
|
+
progress=progress,
|
|
1412
|
+
)
|
|
1413
|
+
|
|
1414
|
+
|
|
1415
|
+
def _filter_edits(
|
|
1416
|
+
tool: ToolConnection,
|
|
1417
|
+
object_id: str,
|
|
1418
|
+
edits: Sequence[dict[str, Any]],
|
|
1419
|
+
*,
|
|
1420
|
+
wait: bool,
|
|
1421
|
+
cancel: threading.Event | None,
|
|
1422
|
+
timeout: float,
|
|
1423
|
+
progress: Callable[[float], None] | None,
|
|
1424
|
+
) -> FilterResult:
|
|
1425
|
+
"""Send the edits of a filter call and return the result of the last one.
|
|
1426
|
+
|
|
1427
|
+
With ``wait`` false, the last edit goes with ``post`` and the result is empty.
|
|
1428
|
+
"""
|
|
1429
|
+
result: Mapping[str, Any] = {}
|
|
1430
|
+
last = len(edits) - 1
|
|
1431
|
+
for index, edit in enumerate(edits):
|
|
1432
|
+
if index == last and not wait:
|
|
1433
|
+
body = {"object": object_id, "edit": edit}
|
|
1434
|
+
tool.post(lambda number: encode.command_frame(number, "filter.edit", body))
|
|
1435
|
+
return FilterResult()
|
|
1436
|
+
result = _filter_edit(tool, object_id, edit, cancel, timeout, progress)
|
|
1437
|
+
return FilterResult.from_result(result)
|
|
1438
|
+
|
|
1439
|
+
|
|
1440
|
+
def _close_client(client: WebSocketClient) -> None:
|
|
1441
|
+
"""Close a client. An error on close does not matter."""
|
|
1442
|
+
try:
|
|
1443
|
+
client.close()
|
|
1444
|
+
except Exception:
|
|
1445
|
+
pass
|
|
1446
|
+
|
|
1447
|
+
|
|
1448
|
+
def _raise_hello_error(header: dict[str, Any]) -> None:
|
|
1449
|
+
"""Raise the right error for an ``error`` frame during the hello."""
|
|
1450
|
+
code = header.get("code")
|
|
1451
|
+
message = str(header.get("message", ""))
|
|
1452
|
+
if code == "busy":
|
|
1453
|
+
raise BusyError(message or "The viewer is busy. Wait a moment and try again.")
|
|
1454
|
+
if code == "unsupported_version":
|
|
1455
|
+
supported = header.get("supported")
|
|
1456
|
+
feature = "protocol version"
|
|
1457
|
+
if supported is not None:
|
|
1458
|
+
feature = f"protocol 1.x (the viewer supports: {supported})"
|
|
1459
|
+
raise MissingFeatureError(feature)
|
|
1460
|
+
raise ViewerRefusedError([Refusal(str(header.get("object", "")), str(code), message)])
|
|
1461
|
+
|
|
1462
|
+
|
|
1463
|
+
def _parse_hello(hello: dict[str, Any]) -> tuple[tuple[float, float, float] | None, str]:
|
|
1464
|
+
"""Return the origin and the CRS of a ``hello`` frame. Raise ProtocolError if it is bad."""
|
|
1465
|
+
try:
|
|
1466
|
+
origin = hello.get("origin")
|
|
1467
|
+
crs = hello.get("crs")
|
|
1468
|
+
return (
|
|
1469
|
+
_triple(origin) if origin is not None else None,
|
|
1470
|
+
"" if crs is None else str(crs),
|
|
1471
|
+
)
|
|
1472
|
+
except (TypeError, ValueError, AttributeError) as error:
|
|
1473
|
+
raise ProtocolError("The viewer sent a hello frame that is not valid.") from error
|
|
1474
|
+
|
|
1475
|
+
|
|
1476
|
+
def _parse_inventory(header: dict[str, Any]) -> list[InventoryEntry]:
|
|
1477
|
+
"""Return the entries of a ``scene.inventory`` frame. Raise ProtocolError if it is bad."""
|
|
1478
|
+
try:
|
|
1479
|
+
return [
|
|
1480
|
+
InventoryEntry(
|
|
1481
|
+
id=str(item["id"]),
|
|
1482
|
+
object_type=str(item.get("object_type", "")),
|
|
1483
|
+
revision=int(item.get("revision", 1)),
|
|
1484
|
+
)
|
|
1485
|
+
for item in header.get("entries", [])
|
|
1486
|
+
]
|
|
1487
|
+
except (TypeError, ValueError, KeyError, AttributeError) as error:
|
|
1488
|
+
raise ProtocolError("The viewer sent an inventory frame that is not valid.") from error
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
def _read_early(client: WebSocketClient, wait: float = 0.05) -> None:
|
|
1492
|
+
"""Read frames that wait already. Raise the hello error if one is an ``error`` frame."""
|
|
1493
|
+
for _ in range(4):
|
|
1494
|
+
data = client.receive(wait)
|
|
1495
|
+
if data is None:
|
|
1496
|
+
return
|
|
1497
|
+
header = protocol.decode_frame(data).header
|
|
1498
|
+
if header.get("type") == "error":
|
|
1499
|
+
_raise_hello_error(header)
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
def _heartbeat_loop(
|
|
1503
|
+
ref: weakref.ReferenceType[Viewer], stop: threading.Event, interval: float
|
|
1504
|
+
) -> None:
|
|
1505
|
+
"""Run the keepalive. The thread holds only a weak reference to the viewer."""
|
|
1506
|
+
while not stop.wait(interval):
|
|
1507
|
+
viewer = ref()
|
|
1508
|
+
if viewer is None or not viewer._heartbeat_tick():
|
|
1509
|
+
return
|
|
1510
|
+
del viewer
|
|
1511
|
+
|
|
1512
|
+
|
|
1513
|
+
def _release_shared(shared: dict[str, Any]) -> None:
|
|
1514
|
+
"""Stop the thread and close the socket of a viewer that is gone."""
|
|
1515
|
+
shared["stop"].set()
|
|
1516
|
+
client = shared.get("client")
|
|
1517
|
+
if client is not None:
|
|
1518
|
+
_close_client(client)
|