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/commands.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Filter and colour commands: input checks, colour settings, results and requests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import numbers
|
|
7
|
+
import threading
|
|
8
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from loop_link import encode
|
|
13
|
+
from loop_link.errors import InvalidInputError
|
|
14
|
+
from loop_link.protocol import Frame, ProtocolError
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from loop_link.tool import ToolConnection
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
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
|
+
"parse_colour_map_names",
|
|
29
|
+
"raise_for_command_result",
|
|
30
|
+
"run_command",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
_FEATURE = "filter and colour commands (geoviewer protocol 1.11)"
|
|
34
|
+
_SCALES = ("linear", "log")
|
|
35
|
+
_CODE_MAX = 2**32 - 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def format_number(value: numbers.Real) -> str:
|
|
39
|
+
"""Return the text of a number, as the ``repr`` of its float value.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
value : number
|
|
44
|
+
The number to format.
|
|
45
|
+
|
|
46
|
+
Returns
|
|
47
|
+
-------
|
|
48
|
+
str
|
|
49
|
+
The text of the float value.
|
|
50
|
+
"""
|
|
51
|
+
return repr(float(value))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def check_number(value: object, name: str) -> float:
|
|
55
|
+
"""Check that a value is a finite number and return it as a float.
|
|
56
|
+
|
|
57
|
+
Parameters
|
|
58
|
+
----------
|
|
59
|
+
value : number
|
|
60
|
+
The value to check. ``bool``, NaN and infinity are not valid.
|
|
61
|
+
name : str
|
|
62
|
+
The name of the argument, for the error message.
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
-------
|
|
66
|
+
float
|
|
67
|
+
The value as a float.
|
|
68
|
+
|
|
69
|
+
Raises
|
|
70
|
+
------
|
|
71
|
+
loop_link.errors.InvalidInputError
|
|
72
|
+
The value is not a finite number.
|
|
73
|
+
"""
|
|
74
|
+
if (
|
|
75
|
+
isinstance(value, (bool, str))
|
|
76
|
+
or not isinstance(value, numbers.Real)
|
|
77
|
+
or not math.isfinite(float(value))
|
|
78
|
+
):
|
|
79
|
+
raise InvalidInputError(f"'{name}' must be a finite number. Got {value!r}.")
|
|
80
|
+
return float(value)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def check_text(value: object, name: str) -> str:
|
|
84
|
+
"""Check that a value is a text that is not empty.
|
|
85
|
+
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
value : str
|
|
89
|
+
The value to check.
|
|
90
|
+
name : str
|
|
91
|
+
The name of the argument, for the error message.
|
|
92
|
+
|
|
93
|
+
Returns
|
|
94
|
+
-------
|
|
95
|
+
str
|
|
96
|
+
The text.
|
|
97
|
+
|
|
98
|
+
Raises
|
|
99
|
+
------
|
|
100
|
+
loop_link.errors.InvalidInputError
|
|
101
|
+
The value is not a ``str`` or it is empty.
|
|
102
|
+
"""
|
|
103
|
+
if not isinstance(value, str) or not value:
|
|
104
|
+
raise InvalidInputError(f"'{name}' must be a text that is not empty. Got {value!r}.")
|
|
105
|
+
return value
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _check_int(value: object, name: str, low: int, high: int) -> int:
|
|
109
|
+
"""Return a value as an ``int`` when it is an integer in a range."""
|
|
110
|
+
if isinstance(value, bool) or not isinstance(value, numbers.Integral):
|
|
111
|
+
raise InvalidInputError(f"'{name}' must contain only integers. Got {value!r}.")
|
|
112
|
+
number = int(value)
|
|
113
|
+
if not low <= number <= high:
|
|
114
|
+
raise InvalidInputError(f"'{name}' must contain only integers from {low} to {high}.")
|
|
115
|
+
return number
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def check_rgb(value: object, name: str) -> tuple[int, int, int]:
|
|
119
|
+
"""Check that a value is three integers from 0 to 255.
|
|
120
|
+
|
|
121
|
+
Parameters
|
|
122
|
+
----------
|
|
123
|
+
value : sequence of int
|
|
124
|
+
The value to check.
|
|
125
|
+
name : str
|
|
126
|
+
The name of the argument, for the error message.
|
|
127
|
+
|
|
128
|
+
Returns
|
|
129
|
+
-------
|
|
130
|
+
tuple of int
|
|
131
|
+
The red, green and blue values.
|
|
132
|
+
|
|
133
|
+
Raises
|
|
134
|
+
------
|
|
135
|
+
loop_link.errors.InvalidInputError
|
|
136
|
+
The value is not three integers from 0 to 255.
|
|
137
|
+
"""
|
|
138
|
+
if isinstance(value, (str, bytes)) or not isinstance(value, Sequence) or len(value) != 3:
|
|
139
|
+
raise InvalidInputError(f"'{name}' must be three integers from 0 to 255. Got {value!r}.")
|
|
140
|
+
red, green, blue = (_check_int(item, name, 0, 255) for item in value)
|
|
141
|
+
return (red, green, blue)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def check_codes(values: Iterable[Any], name: str) -> list[int]:
|
|
145
|
+
"""Check that each value is an integer code from 0 to 2**32-1.
|
|
146
|
+
|
|
147
|
+
Parameters
|
|
148
|
+
----------
|
|
149
|
+
values : iterable of int
|
|
150
|
+
The codes to check. A numpy array is valid.
|
|
151
|
+
name : str
|
|
152
|
+
The name of the argument, for the error message.
|
|
153
|
+
|
|
154
|
+
Returns
|
|
155
|
+
-------
|
|
156
|
+
list of int
|
|
157
|
+
The codes as Python integers.
|
|
158
|
+
|
|
159
|
+
Raises
|
|
160
|
+
------
|
|
161
|
+
loop_link.errors.InvalidInputError
|
|
162
|
+
The value is not iterable or one code is not valid.
|
|
163
|
+
"""
|
|
164
|
+
if isinstance(values, (str, bytes)):
|
|
165
|
+
raise InvalidInputError(f"'{name}' must be a list of integer codes. Got {values!r}.")
|
|
166
|
+
try:
|
|
167
|
+
items = list(values)
|
|
168
|
+
except TypeError as error:
|
|
169
|
+
raise InvalidInputError(f"'{name}' must be a list of integer codes.") from error
|
|
170
|
+
return [_check_int(item, name, 0, _CODE_MAX) for item in items]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass(frozen=True)
|
|
174
|
+
class ColourSettings:
|
|
175
|
+
"""The colour settings of one object. A value of ``None`` means no change.
|
|
176
|
+
|
|
177
|
+
Parameters
|
|
178
|
+
----------
|
|
179
|
+
array : str, optional
|
|
180
|
+
The name of the array to colour by.
|
|
181
|
+
colour_map : str, optional
|
|
182
|
+
The name of the colour map.
|
|
183
|
+
range : tuple of float, optional
|
|
184
|
+
The low and high limit of the colour range. The low limit is less than the high limit.
|
|
185
|
+
scale : str, optional
|
|
186
|
+
The colour scale, ``"linear"`` or ``"log"``.
|
|
187
|
+
plain : tuple of int, optional
|
|
188
|
+
The plain colour as red, green and blue values from 0 to 255.
|
|
189
|
+
|
|
190
|
+
Raises
|
|
191
|
+
------
|
|
192
|
+
loop_link.errors.InvalidInputError
|
|
193
|
+
A value is not valid. The message names the field.
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
array: str | None = None
|
|
197
|
+
colour_map: str | None = None
|
|
198
|
+
range: tuple[float, float] | None = None
|
|
199
|
+
scale: str | None = None
|
|
200
|
+
plain: tuple[int, int, int] | None = None
|
|
201
|
+
|
|
202
|
+
def __post_init__(self) -> None:
|
|
203
|
+
"""Check the values and store them in their final form."""
|
|
204
|
+
if self.array is not None:
|
|
205
|
+
check_text(self.array, "array")
|
|
206
|
+
if self.colour_map is not None:
|
|
207
|
+
check_text(self.colour_map, "colour_map")
|
|
208
|
+
if self.range is not None:
|
|
209
|
+
limits = self.range
|
|
210
|
+
if isinstance(limits, (str, bytes)) or not isinstance(limits, Sequence):
|
|
211
|
+
raise InvalidInputError(f"'range' must be two numbers. Got {limits!r}.")
|
|
212
|
+
if len(limits) != 2:
|
|
213
|
+
raise InvalidInputError(f"'range' must be two numbers. Got {limits!r}.")
|
|
214
|
+
low = check_number(limits[0], "range")
|
|
215
|
+
high = check_number(limits[1], "range")
|
|
216
|
+
if not low < high:
|
|
217
|
+
raise InvalidInputError("'range' must have a low limit less than the high limit.")
|
|
218
|
+
object.__setattr__(self, "range", (low, high))
|
|
219
|
+
if self.scale is not None and self.scale not in _SCALES:
|
|
220
|
+
raise InvalidInputError(f"'scale' must be 'linear' or 'log'. Got {self.scale!r}.")
|
|
221
|
+
if self.plain is not None:
|
|
222
|
+
object.__setattr__(self, "plain", check_rgb(self.plain, "plain"))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _count(result: Mapping[str, Any], key: str) -> int | None:
|
|
226
|
+
"""Return a count of a result, or ``None`` when it is absent."""
|
|
227
|
+
value = result.get(key)
|
|
228
|
+
if value is None:
|
|
229
|
+
return None
|
|
230
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
231
|
+
raise ProtocolError(f"The viewer sent a filter result '{key}' that is not valid.")
|
|
232
|
+
return value
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@dataclass(frozen=True)
|
|
236
|
+
class FilterResult:
|
|
237
|
+
"""The result of a filter call. A field is ``None`` when the viewer gives no value.
|
|
238
|
+
|
|
239
|
+
Parameters
|
|
240
|
+
----------
|
|
241
|
+
passing : int, optional
|
|
242
|
+
The number of elements that pass the filters.
|
|
243
|
+
total : int, optional
|
|
244
|
+
The number of elements of the object.
|
|
245
|
+
state : str, optional
|
|
246
|
+
``"unbuilt"`` when the viewer did not build the filters, or ``"building"`` when
|
|
247
|
+
the viewer stopped to wait and the build goes on.
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
passing: int | None = None
|
|
251
|
+
total: int | None = None
|
|
252
|
+
state: str | None = None
|
|
253
|
+
|
|
254
|
+
@classmethod
|
|
255
|
+
def from_result(cls, result: Mapping[str, Any]) -> FilterResult:
|
|
256
|
+
"""Read a ``command.result`` body of ``filter.edit``.
|
|
257
|
+
|
|
258
|
+
Parameters
|
|
259
|
+
----------
|
|
260
|
+
result : mapping
|
|
261
|
+
The ``result`` body, with the status ``done``.
|
|
262
|
+
|
|
263
|
+
Returns
|
|
264
|
+
-------
|
|
265
|
+
FilterResult
|
|
266
|
+
The counts and the state of the body.
|
|
267
|
+
|
|
268
|
+
Raises
|
|
269
|
+
------
|
|
270
|
+
loop_link.protocol.ProtocolError
|
|
271
|
+
A count is not a whole number of 0 or more, or the state is not a text.
|
|
272
|
+
"""
|
|
273
|
+
state = result.get("state")
|
|
274
|
+
if state is not None and not isinstance(state, str):
|
|
275
|
+
raise ProtocolError("The viewer sent a filter result 'state' that is not a text.")
|
|
276
|
+
return cls(_count(result, "passing"), _count(result, "total"), state)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def raise_for_command_result(result: Mapping[str, Any], *, command: str) -> None:
|
|
280
|
+
"""Raise an error when a ``command.result`` body is not ``done``.
|
|
281
|
+
|
|
282
|
+
Parameters
|
|
283
|
+
----------
|
|
284
|
+
result : mapping
|
|
285
|
+
The ``result`` body of the frame.
|
|
286
|
+
command : str
|
|
287
|
+
The name of the command, for the error message.
|
|
288
|
+
|
|
289
|
+
Raises
|
|
290
|
+
------
|
|
291
|
+
loop_link.errors.InvalidInputError
|
|
292
|
+
The status is ``refused``.
|
|
293
|
+
loop_link.protocol.ProtocolError
|
|
294
|
+
The status is not known.
|
|
295
|
+
"""
|
|
296
|
+
status = result.get("status")
|
|
297
|
+
if status == "done":
|
|
298
|
+
return
|
|
299
|
+
if status == "refused":
|
|
300
|
+
raise InvalidInputError(
|
|
301
|
+
f"The viewer refused the command '{command}': {result.get('text', '')}"
|
|
302
|
+
)
|
|
303
|
+
raise ProtocolError(f"The viewer sent an unknown result status '{status}'.")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def parse_colour_map_names(frame: Frame) -> tuple[str, ...] | None:
|
|
307
|
+
"""Read the colour map names from a ``commands`` frame.
|
|
308
|
+
|
|
309
|
+
Parameters
|
|
310
|
+
----------
|
|
311
|
+
frame : loop_link.protocol.Frame
|
|
312
|
+
The ``commands`` frame of the viewer.
|
|
313
|
+
|
|
314
|
+
Returns
|
|
315
|
+
-------
|
|
316
|
+
tuple of str or None
|
|
317
|
+
The names, or ``None`` when the frame has no ``colour.set_map`` entry or the entry
|
|
318
|
+
has no list of names.
|
|
319
|
+
|
|
320
|
+
Raises
|
|
321
|
+
------
|
|
322
|
+
loop_link.protocol.ProtocolError
|
|
323
|
+
The list of names is not a list of ``str``.
|
|
324
|
+
"""
|
|
325
|
+
entries = frame.header.get("commands")
|
|
326
|
+
if not isinstance(entries, list):
|
|
327
|
+
return None
|
|
328
|
+
for entry in entries:
|
|
329
|
+
if not isinstance(entry, Mapping) or entry.get("name") != "colour.set_map":
|
|
330
|
+
continue
|
|
331
|
+
schema = entry.get("input_schema")
|
|
332
|
+
properties = schema.get("properties") if isinstance(schema, Mapping) else None
|
|
333
|
+
name = properties.get("name") if isinstance(properties, Mapping) else None
|
|
334
|
+
if not isinstance(name, Mapping) or "enum" not in name:
|
|
335
|
+
return None
|
|
336
|
+
names = name["enum"]
|
|
337
|
+
if not isinstance(names, list) or not all(isinstance(item, str) for item in names):
|
|
338
|
+
raise ProtocolError("The viewer sent colour map names that are not a list of text.")
|
|
339
|
+
return tuple(names)
|
|
340
|
+
return None
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def run_command(
|
|
344
|
+
tool: ToolConnection,
|
|
345
|
+
command: str,
|
|
346
|
+
input: Mapping[str, Any],
|
|
347
|
+
*,
|
|
348
|
+
object_id: str | None = None,
|
|
349
|
+
cancel: threading.Event | None = None,
|
|
350
|
+
timeout: float | None = None,
|
|
351
|
+
progress: Callable[[float], None] | None = None,
|
|
352
|
+
) -> Mapping[str, Any]:
|
|
353
|
+
"""Send one command and return its result.
|
|
354
|
+
|
|
355
|
+
Parameters
|
|
356
|
+
----------
|
|
357
|
+
tool : loop_link.tool.ToolConnection
|
|
358
|
+
The tool connection.
|
|
359
|
+
command : str
|
|
360
|
+
The name of the command.
|
|
361
|
+
input : mapping
|
|
362
|
+
The input of the command.
|
|
363
|
+
object_id : str, optional
|
|
364
|
+
The identifier of the object that the command is about, for error messages.
|
|
365
|
+
cancel : threading.Event, optional
|
|
366
|
+
When it is set, the request is cancelled.
|
|
367
|
+
timeout : float, optional
|
|
368
|
+
The time in seconds to wait for the next frame.
|
|
369
|
+
progress : callable, optional
|
|
370
|
+
Called with the fraction of each ``command.progress`` frame.
|
|
371
|
+
|
|
372
|
+
Returns
|
|
373
|
+
-------
|
|
374
|
+
mapping
|
|
375
|
+
The ``result`` body, with the status ``done``.
|
|
376
|
+
|
|
377
|
+
Raises
|
|
378
|
+
------
|
|
379
|
+
loop_link.errors.InvalidInputError
|
|
380
|
+
The viewer refused the command.
|
|
381
|
+
loop_link.protocol.ProtocolError
|
|
382
|
+
The result is not a mapping with a ``str`` status, or the status is not known.
|
|
383
|
+
"""
|
|
384
|
+
frame = tool.request(
|
|
385
|
+
lambda number: encode.command_frame(number, command, input),
|
|
386
|
+
until=("command.result",),
|
|
387
|
+
feature=_FEATURE,
|
|
388
|
+
object_id=object_id,
|
|
389
|
+
progress=progress,
|
|
390
|
+
cancel=cancel,
|
|
391
|
+
timeout=timeout,
|
|
392
|
+
)
|
|
393
|
+
result = frame.header.get("result")
|
|
394
|
+
if not isinstance(result, Mapping) or not isinstance(result.get("status"), str):
|
|
395
|
+
raise ProtocolError("The viewer sent a command result that is not valid.")
|
|
396
|
+
raise_for_command_result(result, command=command)
|
|
397
|
+
return result
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def list_colour_map_names(tool: ToolConnection) -> tuple[str, ...] | None:
|
|
401
|
+
"""Ask the viewer for the names of its colour maps.
|
|
402
|
+
|
|
403
|
+
Parameters
|
|
404
|
+
----------
|
|
405
|
+
tool : loop_link.tool.ToolConnection
|
|
406
|
+
The tool connection.
|
|
407
|
+
|
|
408
|
+
Returns
|
|
409
|
+
-------
|
|
410
|
+
tuple of str or None
|
|
411
|
+
The names, or ``None`` when the viewer gives no list.
|
|
412
|
+
"""
|
|
413
|
+
frame = tool.request(
|
|
414
|
+
lambda number: encode.commands_list_frame(number),
|
|
415
|
+
until=("commands",),
|
|
416
|
+
feature=_FEATURE,
|
|
417
|
+
)
|
|
418
|
+
return parse_colour_map_names(frame)
|
loop_link/discovery.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Find a running viewer and the token to talk to it.
|
|
2
|
+
|
|
3
|
+
The functions here only read settings files and test a socket. They never
|
|
4
|
+
start a program.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import os
|
|
12
|
+
import socket
|
|
13
|
+
import sys
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from loop_link.errors import NoViewerError, TokenError
|
|
18
|
+
|
|
19
|
+
DEFAULT_PORT: int = 47615
|
|
20
|
+
|
|
21
|
+
_TOKEN_TEXT = "Set GEOVIEWER_TOKEN, or save a token in the link popup of the viewer."
|
|
22
|
+
_NO_VIEWER_TEXT = (
|
|
23
|
+
"No viewer found. Start geoviewer and turn the link on. " "This library never starts a viewer."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class ViewerAddress:
|
|
29
|
+
"""The address and token of a viewer.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
host : str
|
|
34
|
+
The host name or IP address of the viewer.
|
|
35
|
+
port : int
|
|
36
|
+
The TCP port of the viewer.
|
|
37
|
+
token : str
|
|
38
|
+
The access token of the viewer.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
host: str
|
|
42
|
+
port: int
|
|
43
|
+
token: str
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def settings_dir() -> Path:
|
|
47
|
+
r"""Return the folder where the viewer keeps its settings.
|
|
48
|
+
|
|
49
|
+
Returns
|
|
50
|
+
-------
|
|
51
|
+
pathlib.Path
|
|
52
|
+
``%APPDATA%\\geoviewer`` on Windows, else ``~/.geoviewer``.
|
|
53
|
+
"""
|
|
54
|
+
if sys.platform == "win32":
|
|
55
|
+
appdata = os.environ.get("APPDATA")
|
|
56
|
+
base = Path(appdata) if appdata else Path.home() / "AppData" / "Roaming"
|
|
57
|
+
return base / "geoviewer"
|
|
58
|
+
return Path.home() / ".geoviewer"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _read_json(path: Path) -> object:
|
|
62
|
+
# Return the parsed JSON, or None if the file is missing or damaged.
|
|
63
|
+
try:
|
|
64
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
65
|
+
except (OSError, ValueError):
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _file_token(settings: Path) -> str:
|
|
70
|
+
data = _read_json(settings / "link.json")
|
|
71
|
+
if isinstance(data, dict):
|
|
72
|
+
token = data.get("token")
|
|
73
|
+
if isinstance(token, str):
|
|
74
|
+
return token
|
|
75
|
+
return ""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _resolve_token(token: str | None, settings: Path) -> str:
|
|
79
|
+
if token:
|
|
80
|
+
return token
|
|
81
|
+
env_token = os.environ.get("GEOVIEWER_TOKEN")
|
|
82
|
+
if env_token:
|
|
83
|
+
return env_token
|
|
84
|
+
file_token = _file_token(settings)
|
|
85
|
+
if file_token:
|
|
86
|
+
return file_token
|
|
87
|
+
raise TokenError(_TOKEN_TEXT)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _is_alive(host: str, port: int, timeout: float) -> bool:
|
|
91
|
+
try:
|
|
92
|
+
sock = socket.create_connection((host, port), timeout)
|
|
93
|
+
except OSError:
|
|
94
|
+
return False
|
|
95
|
+
sock.close()
|
|
96
|
+
return True
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _find_port(settings: Path, host: str, timeout: float) -> int:
|
|
100
|
+
live: list[tuple[tuple[bool, int], int]] = []
|
|
101
|
+
folder = settings / "instances"
|
|
102
|
+
try:
|
|
103
|
+
files = sorted(folder.glob("*.json"))
|
|
104
|
+
except OSError:
|
|
105
|
+
files = []
|
|
106
|
+
for path in files:
|
|
107
|
+
data = _read_json(path)
|
|
108
|
+
if not isinstance(data, dict):
|
|
109
|
+
continue
|
|
110
|
+
port = data.get("port")
|
|
111
|
+
kind = data.get("kind")
|
|
112
|
+
focused = data.get("focused", 0)
|
|
113
|
+
if isinstance(focused, bool) or not isinstance(focused, (int, float)):
|
|
114
|
+
focused = 0
|
|
115
|
+
if not math.isfinite(focused):
|
|
116
|
+
focused = 0
|
|
117
|
+
if not isinstance(port, int) or isinstance(port, bool) or not isinstance(kind, str):
|
|
118
|
+
continue
|
|
119
|
+
if _is_alive(host, port, timeout):
|
|
120
|
+
live.append(((kind != "window", -focused), port))
|
|
121
|
+
if live:
|
|
122
|
+
live.sort(key=lambda item: item[0])
|
|
123
|
+
return live[0][1]
|
|
124
|
+
if _is_alive(host, DEFAULT_PORT, timeout):
|
|
125
|
+
return DEFAULT_PORT
|
|
126
|
+
raise NoViewerError(_NO_VIEWER_TEXT)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def find_viewer(
|
|
130
|
+
*,
|
|
131
|
+
port: int | None = None,
|
|
132
|
+
token: str | None = None,
|
|
133
|
+
host: str = "127.0.0.1",
|
|
134
|
+
settings: Path | None = None,
|
|
135
|
+
timeout: float = 0.5,
|
|
136
|
+
) -> ViewerAddress:
|
|
137
|
+
"""Find a running viewer and the token for it.
|
|
138
|
+
|
|
139
|
+
Parameters
|
|
140
|
+
----------
|
|
141
|
+
port : int, optional
|
|
142
|
+
The port of the viewer. If given, it is returned as given: the
|
|
143
|
+
function does not check it and does not read the instance files.
|
|
144
|
+
token : str, optional
|
|
145
|
+
The access token. If not given, the function reads the
|
|
146
|
+
``GEOVIEWER_TOKEN`` environment variable, then ``link.json``.
|
|
147
|
+
host : str
|
|
148
|
+
The host of the viewer.
|
|
149
|
+
settings : pathlib.Path, optional
|
|
150
|
+
The settings folder. The default is :func:`settings_dir`.
|
|
151
|
+
timeout : float
|
|
152
|
+
The time in seconds to wait for each connection test.
|
|
153
|
+
|
|
154
|
+
Returns
|
|
155
|
+
-------
|
|
156
|
+
ViewerAddress
|
|
157
|
+
The host, port and token of the viewer.
|
|
158
|
+
|
|
159
|
+
Raises
|
|
160
|
+
------
|
|
161
|
+
TokenError
|
|
162
|
+
If no token is available.
|
|
163
|
+
NoViewerError
|
|
164
|
+
If no viewer is running.
|
|
165
|
+
"""
|
|
166
|
+
folder = settings if settings is not None else settings_dir()
|
|
167
|
+
resolved = _resolve_token(token, folder)
|
|
168
|
+
if port is not None:
|
|
169
|
+
return ViewerAddress(host=host, port=port, token=resolved)
|
|
170
|
+
return ViewerAddress(host=host, port=_find_port(folder, host, timeout), token=resolved)
|