pingerplot 1.6.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.
- pingerplot/__init__.py +8 -0
- pingerplot/__main__.py +5 -0
- pingerplot/appicon.py +144 -0
- pingerplot/compare.py +257 -0
- pingerplot/ed25519.py +145 -0
- pingerplot/geoip.py +337 -0
- pingerplot/gfx.py +203 -0
- pingerplot/gui.py +1792 -0
- pingerplot/gui_charts.py +409 -0
- pingerplot/gui_history.py +684 -0
- pingerplot/gui_hopinfo.py +125 -0
- pingerplot/gui_recording.py +176 -0
- pingerplot/gui_settings.py +322 -0
- pingerplot/gui_updates.py +270 -0
- pingerplot/gui_widgets.py +248 -0
- pingerplot/headless.py +661 -0
- pingerplot/history.py +823 -0
- pingerplot/icmp.py +305 -0
- pingerplot/icmp_posix.py +456 -0
- pingerplot/investigate.py +205 -0
- pingerplot/launch.py +37 -0
- pingerplot/locating.py +248 -0
- pingerplot/model.py +410 -0
- pingerplot/monitor.py +1404 -0
- pingerplot/places.py +259 -0
- pingerplot/routes.py +112 -0
- pingerplot/selfcheck.py +97 -0
- pingerplot/selftest.py +76 -0
- pingerplot/settings.py +98 -0
- pingerplot/tcpudp.py +479 -0
- pingerplot/theme.py +576 -0
- pingerplot/tkthreads.py +68 -0
- pingerplot/tray.py +373 -0
- pingerplot/trouble.py +129 -0
- pingerplot/update_key.py +8 -0
- pingerplot/updater.py +499 -0
- pingerplot/winplatform.py +366 -0
- pingerplot/worldmap.py +141 -0
- pingerplot/xdg.py +198 -0
- pingerplot-1.6.0.dist-info/METADATA +583 -0
- pingerplot-1.6.0.dist-info/RECORD +45 -0
- pingerplot-1.6.0.dist-info/WHEEL +5 -0
- pingerplot-1.6.0.dist-info/entry_points.txt +5 -0
- pingerplot-1.6.0.dist-info/licenses/LICENSE +21 -0
- pingerplot-1.6.0.dist-info/top_level.txt +1 -0
pingerplot/geoip.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Where a hop's router is and whose network it's on, from ipwho.is.
|
|
2
|
+
|
|
3
|
+
Public hop addresses are looked up (free, HTTPS, no key) on a background
|
|
4
|
+
thread, one at a time and 0.8 s apart. Since 1.5 this runs while monitoring,
|
|
5
|
+
not only when the Map is open, so the hop table, the History page and the map
|
|
6
|
+
can say where a router is and whose it is; Settings -> "Look up where routers
|
|
7
|
+
are" turns it off. Only router addresses are sent: private, LAN, carrier-NAT
|
|
8
|
+
and other non-global addresses never are.
|
|
9
|
+
|
|
10
|
+
Answers are kept on disk (``lookups.json`` in the settings folder) and asked
|
|
11
|
+
again after 30 days, so a router is looked up about once a month, however
|
|
12
|
+
long you monitor. The free service's limits aren't well published, so the
|
|
13
|
+
resolver also stops itself at 500 lookups a day and, told it's asking too
|
|
14
|
+
often (HTTP 429), waits an hour.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import ipaddress
|
|
20
|
+
import json
|
|
21
|
+
import math
|
|
22
|
+
import os
|
|
23
|
+
import queue
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
26
|
+
import urllib.error
|
|
27
|
+
import urllib.parse
|
|
28
|
+
import urllib.request
|
|
29
|
+
from dataclasses import asdict, dataclass
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Optional
|
|
32
|
+
|
|
33
|
+
_URL = "https://ipwho.is/{ip}?fields=success,latitude,longitude,city,region,country,connection"
|
|
34
|
+
_MIN_INTERVAL = 0.8 # seconds between requests (be polite to the free API)
|
|
35
|
+
_MAX_BODY = 64 * 1024 # a location object is ~300 bytes; anything near this is wrong
|
|
36
|
+
_RETRY_S = 60.0 # after a failed lookup, wait this long before asking again
|
|
37
|
+
_KEEP_S = 30 * 86400 # an answer is asked again after this long
|
|
38
|
+
_DAILY_CAP = 500 # lookups a day at most, whatever is being monitored
|
|
39
|
+
_BACKOFF_429_S = 3600.0
|
|
40
|
+
_SAVE_EVERY_S = 10.0
|
|
41
|
+
_MAX_KEPT = 20_000 # entries in the file; the oldest go first
|
|
42
|
+
CACHE_NAME = "lookups.json"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class LookupFailed(Exception):
|
|
46
|
+
"""The service could not be asked (offline, timeout, DNS, HTTP error, a
|
|
47
|
+
captive portal's HTML). Says nothing about the address, so it is retried
|
|
48
|
+
rather than remembered as "no location"."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class RateLimited(LookupFailed):
|
|
52
|
+
"""HTTP 429: the service says we've asked too often."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(slots=True)
|
|
56
|
+
class GeoInfo:
|
|
57
|
+
lat: float
|
|
58
|
+
lon: float
|
|
59
|
+
city: str
|
|
60
|
+
region: str
|
|
61
|
+
country: str
|
|
62
|
+
isp: str
|
|
63
|
+
asn: Optional[int] = None # the network's autonomous system number
|
|
64
|
+
org: str = "" # who the address block is assigned to
|
|
65
|
+
|
|
66
|
+
def network(self) -> str:
|
|
67
|
+
""""AS8075 Example Corp", or what's known of it: the network that
|
|
68
|
+
runs the address (ipwho.is's isp), not whoever the block is assigned
|
|
69
|
+
to (its org), which for a carrier's router is often a customer."""
|
|
70
|
+
name = self.isp or self.org
|
|
71
|
+
if self.asn:
|
|
72
|
+
return f"AS{self.asn} {name}".strip()
|
|
73
|
+
return name
|
|
74
|
+
|
|
75
|
+
def place(self) -> str:
|
|
76
|
+
return ", ".join(x for x in (self.city, self.region, self.country) if x)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _geo_text(value) -> str:
|
|
80
|
+
return value.strip() if isinstance(value, str) else ""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def make_info(lat, lon, city=None, region=None, country=None, isp=None, asn=None,
|
|
84
|
+
org=None) -> GeoInfo:
|
|
85
|
+
"""A GeoInfo from values nobody checked: ipwho.is's answer, or
|
|
86
|
+
lookups.json. A number or a list where text belongs reached
|
|
87
|
+
``", ".join`` in place() and the string code in the hop table, and
|
|
88
|
+
raised inside the refresh (2026-11 review): text fields keep only text,
|
|
89
|
+
the ASN only a real one. Raises ValueError for a position that isn't."""
|
|
90
|
+
lat, lon = float(lat), float(lon)
|
|
91
|
+
if not (math.isfinite(lat) and math.isfinite(lon) and -90 <= lat <= 90 and -180 <= lon <= 180):
|
|
92
|
+
raise ValueError(f"not a position: {lat}, {lon}")
|
|
93
|
+
try:
|
|
94
|
+
asn = int(asn) if isinstance(asn, (int, str)) and asn != "" else None
|
|
95
|
+
except ValueError:
|
|
96
|
+
asn = None
|
|
97
|
+
if asn is not None and not 0 < asn < 2 ** 32:
|
|
98
|
+
asn = None
|
|
99
|
+
return GeoInfo(lat, lon, _geo_text(city), _geo_text(region), _geo_text(country),
|
|
100
|
+
_geo_text(isp), asn, _geo_text(org))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _is_public(ip: str) -> bool:
|
|
104
|
+
"""Only globally routable unicast addresses go to ipwho.is.
|
|
105
|
+
|
|
106
|
+
Excluding what is_private covers wasn't enough: carrier-grade NAT
|
|
107
|
+
(100.64.0.0/10, which is also Tailscale's range) is neither private nor
|
|
108
|
+
global, so a Starlink or mobile-carrier gateway or a tailnet peer went
|
|
109
|
+
out. IPv6 site-local (fec0::/10) even counts as global to ipaddress, and
|
|
110
|
+
an IPv4-mapped, 6to4, Teredo or zone-scoped address carries another
|
|
111
|
+
address inside it."""
|
|
112
|
+
try:
|
|
113
|
+
addr = ipaddress.ip_address(ip)
|
|
114
|
+
except ValueError:
|
|
115
|
+
return False
|
|
116
|
+
if addr.version == 6 and (addr.scope_id or addr.is_site_local or addr.ipv4_mapped
|
|
117
|
+
or addr.sixtofour or addr.teredo):
|
|
118
|
+
return False
|
|
119
|
+
return addr.is_global and not (addr.is_multicast or addr.is_reserved or addr.is_loopback
|
|
120
|
+
or addr.is_link_local or addr.is_unspecified)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class GeoResolver:
|
|
124
|
+
def __init__(self, cache_path: Optional[os.PathLike] = None, clock=time.time) -> None:
|
|
125
|
+
self.cache: dict[str, GeoInfo | None] = {} # None == looked up, no data
|
|
126
|
+
self.failures = 0 # lookups that raised, not just missed
|
|
127
|
+
self._q: queue.Queue[str] = queue.Queue()
|
|
128
|
+
self._seen: set[str] = set()
|
|
129
|
+
self._retry_at: dict[str, float] = {} # ip -> monotonic time it may be retried
|
|
130
|
+
self._lock = threading.Lock()
|
|
131
|
+
self._stop = threading.Event()
|
|
132
|
+
self._thread: threading.Thread | None = None
|
|
133
|
+
self._clock = clock
|
|
134
|
+
self._cache_path = Path(cache_path) if cache_path is not None else None
|
|
135
|
+
self._looked_up: dict[str, float] = {} # ip -> when it was answered (epoch)
|
|
136
|
+
self._dirty = False
|
|
137
|
+
self._last_save = 0.0
|
|
138
|
+
self._paused_until = 0.0 # monotonic; after a 429
|
|
139
|
+
self._day = ""
|
|
140
|
+
self._today = 0
|
|
141
|
+
self.paused = "" # why lookups are paused, if they are
|
|
142
|
+
if self._cache_path is not None:
|
|
143
|
+
self._load()
|
|
144
|
+
|
|
145
|
+
# --- the cache on disk ----------------------------------------------------
|
|
146
|
+
def _load(self) -> None:
|
|
147
|
+
try:
|
|
148
|
+
with open(self._cache_path, "r", encoding="utf-8") as fh:
|
|
149
|
+
data = json.load(fh)
|
|
150
|
+
hosts = data.get("hosts") if isinstance(data, dict) else None
|
|
151
|
+
except (OSError, ValueError):
|
|
152
|
+
return
|
|
153
|
+
if not isinstance(hosts, dict):
|
|
154
|
+
return
|
|
155
|
+
now = self._clock()
|
|
156
|
+
for ip, entry in hosts.items():
|
|
157
|
+
try:
|
|
158
|
+
when = float(entry["t"])
|
|
159
|
+
raw = entry.get("info")
|
|
160
|
+
info = None if raw is None else make_info(**{
|
|
161
|
+
k: raw[k] for k in GeoInfo.__dataclass_fields__ if k in raw})
|
|
162
|
+
except (KeyError, TypeError, ValueError, AttributeError, OverflowError):
|
|
163
|
+
continue
|
|
164
|
+
if not isinstance(ip, str) or now - when > _KEEP_S:
|
|
165
|
+
continue # too old: asked again when next seen
|
|
166
|
+
self.cache[ip] = info
|
|
167
|
+
self._seen.add(ip)
|
|
168
|
+
self._looked_up[ip] = when
|
|
169
|
+
|
|
170
|
+
def save(self) -> bool:
|
|
171
|
+
"""Write the answers to disk (atomically). Never raises."""
|
|
172
|
+
if self._cache_path is None:
|
|
173
|
+
return False
|
|
174
|
+
with self._lock:
|
|
175
|
+
entries = sorted(self._looked_up.items(), key=lambda kv: kv[1])[-_MAX_KEPT:]
|
|
176
|
+
hosts = {ip: {"t": t, "info": None if self.cache.get(ip) is None
|
|
177
|
+
else asdict(self.cache[ip])} for ip, t in entries}
|
|
178
|
+
self._dirty = False
|
|
179
|
+
tmp = self._cache_path.with_name(self._cache_path.name + ".tmp")
|
|
180
|
+
try:
|
|
181
|
+
self._cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
183
|
+
json.dump({"version": 1, "hosts": hosts}, fh)
|
|
184
|
+
os.replace(tmp, self._cache_path)
|
|
185
|
+
self._last_save = time.monotonic()
|
|
186
|
+
return True
|
|
187
|
+
except (OSError, TypeError, ValueError):
|
|
188
|
+
try:
|
|
189
|
+
tmp.unlink()
|
|
190
|
+
except OSError:
|
|
191
|
+
pass
|
|
192
|
+
return False
|
|
193
|
+
|
|
194
|
+
def start(self) -> None:
|
|
195
|
+
if self._thread and self._thread.is_alive():
|
|
196
|
+
return
|
|
197
|
+
self._stop.clear()
|
|
198
|
+
self._thread = threading.Thread(target=self._worker, daemon=True)
|
|
199
|
+
self._thread.start()
|
|
200
|
+
|
|
201
|
+
def stop(self) -> None:
|
|
202
|
+
self._stop.set()
|
|
203
|
+
if self._dirty:
|
|
204
|
+
self.save()
|
|
205
|
+
|
|
206
|
+
def request(self, ip: str | None) -> None:
|
|
207
|
+
if not ip:
|
|
208
|
+
return
|
|
209
|
+
with self._lock:
|
|
210
|
+
if ip in self._seen or self._retry_at.get(ip, 0.0) > time.monotonic():
|
|
211
|
+
return
|
|
212
|
+
self._seen.add(ip)
|
|
213
|
+
if not _is_public(ip):
|
|
214
|
+
with self._lock:
|
|
215
|
+
self.cache[ip] = None
|
|
216
|
+
return
|
|
217
|
+
self._q.put(ip)
|
|
218
|
+
|
|
219
|
+
def get(self, ip: str | None) -> GeoInfo | None:
|
|
220
|
+
if not ip:
|
|
221
|
+
return None
|
|
222
|
+
with self._lock:
|
|
223
|
+
return self.cache.get(ip)
|
|
224
|
+
|
|
225
|
+
def count(self) -> int:
|
|
226
|
+
"""How many lookups have resolved so far.
|
|
227
|
+
|
|
228
|
+
Results arrive on the worker thread, seconds after the Map view asked
|
|
229
|
+
for them. The GUI folds this into its redraw key so newly-located hops
|
|
230
|
+
actually appear: nothing else about the app changes when a lookup
|
|
231
|
+
lands, so without it the map never repaints to show them.
|
|
232
|
+
"""
|
|
233
|
+
with self._lock:
|
|
234
|
+
return len(self.cache)
|
|
235
|
+
|
|
236
|
+
def _held(self) -> bool:
|
|
237
|
+
"""Whether lookups must wait: after a 429, or with today's allowance
|
|
238
|
+
used up. Says why in ``paused``."""
|
|
239
|
+
if time.monotonic() < self._paused_until:
|
|
240
|
+
return True
|
|
241
|
+
day = time.strftime("%Y-%m-%d", time.localtime(self._clock()))
|
|
242
|
+
if day != self._day:
|
|
243
|
+
self._day, self._today = day, 0
|
|
244
|
+
if self._today >= _DAILY_CAP:
|
|
245
|
+
self.paused = f"{_DAILY_CAP} lookups today; the rest wait until tomorrow"
|
|
246
|
+
return True
|
|
247
|
+
self.paused = ""
|
|
248
|
+
return False
|
|
249
|
+
|
|
250
|
+
def _worker(self) -> None:
|
|
251
|
+
while not self._stop.is_set():
|
|
252
|
+
if self._held():
|
|
253
|
+
self._stop.wait(5.0)
|
|
254
|
+
continue
|
|
255
|
+
try:
|
|
256
|
+
ip = self._q.get(timeout=0.5)
|
|
257
|
+
except queue.Empty:
|
|
258
|
+
if self._dirty and time.monotonic() - self._last_save > _SAVE_EVERY_S:
|
|
259
|
+
self.save()
|
|
260
|
+
continue
|
|
261
|
+
self._today += 1
|
|
262
|
+
self._process(ip)
|
|
263
|
+
if self._dirty and time.monotonic() - self._last_save > _SAVE_EVERY_S:
|
|
264
|
+
self.save()
|
|
265
|
+
self._stop.wait(_MIN_INTERVAL)
|
|
266
|
+
|
|
267
|
+
def _process(self, ip: str) -> None:
|
|
268
|
+
try:
|
|
269
|
+
info = self._lookup(ip)
|
|
270
|
+
except RateLimited:
|
|
271
|
+
# Everything waits, and this address goes back in the queue.
|
|
272
|
+
self._paused_until = time.monotonic() + _BACKOFF_429_S
|
|
273
|
+
self.paused = "the lookup service asked us to slow down; trying again in an hour"
|
|
274
|
+
with self._lock:
|
|
275
|
+
self.failures += 1
|
|
276
|
+
self._q.put(ip)
|
|
277
|
+
return
|
|
278
|
+
except LookupFailed:
|
|
279
|
+
# Not an answer about this address. Caching it as "no location"
|
|
280
|
+
# left every hop looked up while offline blank until restart, with
|
|
281
|
+
# the failure counter still at 0. Count it, and let a later redraw
|
|
282
|
+
# ask again once the back-off has passed.
|
|
283
|
+
with self._lock:
|
|
284
|
+
self.failures += 1
|
|
285
|
+
self._seen.discard(ip)
|
|
286
|
+
self._retry_at[ip] = time.monotonic() + _RETRY_S
|
|
287
|
+
return
|
|
288
|
+
except Exception:
|
|
289
|
+
# This thread is started once and never restarted, so anything
|
|
290
|
+
# that escapes _lookup ends geolocation for the rest of the
|
|
291
|
+
# session -- silently, because nothing is watching it. One
|
|
292
|
+
# malformed reply from a third party must not cost the feature.
|
|
293
|
+
info = None
|
|
294
|
+
with self._lock:
|
|
295
|
+
self.failures += 1
|
|
296
|
+
with self._lock:
|
|
297
|
+
self.cache[ip] = info
|
|
298
|
+
self._looked_up[ip] = self._clock()
|
|
299
|
+
self._dirty = True
|
|
300
|
+
|
|
301
|
+
def _lookup(self, ip: str) -> GeoInfo | None:
|
|
302
|
+
try:
|
|
303
|
+
# The canonical form ipaddress gives, never the string as it
|
|
304
|
+
# came in: a loaded session's address could carry "/" or "%".
|
|
305
|
+
req = urllib.request.Request(_URL.format(ip=urllib.parse.quote(
|
|
306
|
+
str(ipaddress.ip_address(ip)), safe=":")),
|
|
307
|
+
headers={"User-Agent": "PingerPlot"})
|
|
308
|
+
with urllib.request.urlopen(req, timeout=6) as resp:
|
|
309
|
+
# Capped: this is one small JSON object from a third party, not
|
|
310
|
+
# a download. urlopen's timeout applies to socket inactivity
|
|
311
|
+
# rather than total transfer, so a slow-drip large body would
|
|
312
|
+
# otherwise be read in full and then handed to json.loads.
|
|
313
|
+
data = json.loads(resp.read(_MAX_BODY).decode("utf-8", "replace"))
|
|
314
|
+
except urllib.error.HTTPError as exc:
|
|
315
|
+
if exc.code == 429:
|
|
316
|
+
raise RateLimited(str(exc)) from exc
|
|
317
|
+
raise LookupFailed(str(exc)) from exc
|
|
318
|
+
except (OSError, ValueError) as exc:
|
|
319
|
+
# OSError covers URLError, other HTTP errors and timeouts;
|
|
320
|
+
# ValueError is a body that is not JSON at all, e.g. a captive
|
|
321
|
+
# portal's login page.
|
|
322
|
+
raise LookupFailed(str(exc)) from exc
|
|
323
|
+
# json.loads returns whatever the body held: a captive portal, a proxy
|
|
324
|
+
# error page or a CDN interstitial can all be valid JSON that is not an
|
|
325
|
+
# object. Only an object has the fields below.
|
|
326
|
+
if not isinstance(data, dict) or not data.get("success"):
|
|
327
|
+
return None
|
|
328
|
+
try:
|
|
329
|
+
conn = data.get("connection") or {}
|
|
330
|
+
if not isinstance(conn, dict):
|
|
331
|
+
conn = {}
|
|
332
|
+
return make_info(data["latitude"], data["longitude"], data.get("city"),
|
|
333
|
+
data.get("region"), data.get("country"),
|
|
334
|
+
_geo_text(conn.get("isp")) or conn.get("org"),
|
|
335
|
+
conn.get("asn"), conn.get("org"))
|
|
336
|
+
except (KeyError, TypeError, ValueError, OverflowError):
|
|
337
|
+
return None
|
pingerplot/gfx.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Small antialiased raster drawing, PNG and ICO encoding. Standard library only.
|
|
2
|
+
|
|
3
|
+
The theme draws its rounded buttons, fields, check boxes and switches at run
|
|
4
|
+
time, in the current accent colour and at the screen's scale, rather than
|
|
5
|
+
shipping fixed images; the tray icons are drawn the same way. Shapes are
|
|
6
|
+
signed distance functions in pixel units, so an edge's coverage is just
|
|
7
|
+
clamp(0.5 - distance).
|
|
8
|
+
|
|
9
|
+
Adapted from UniFi Stock Watcher, a sibling project with the same conventions.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import math
|
|
15
|
+
import struct
|
|
16
|
+
import zlib
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def hex_rgb(h):
|
|
20
|
+
h = h.lstrip("#")
|
|
21
|
+
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def rgb_hex(rgb):
|
|
25
|
+
return "#{:02x}{:02x}{:02x}".format(*(max(0, min(255, round(c))) for c in rgb[:3]))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def mix(a, b, t):
|
|
29
|
+
"""Blend colour a towards b by t (0..1); hex in, hex out."""
|
|
30
|
+
ra, rb = hex_rgb(a), hex_rgb(b)
|
|
31
|
+
return rgb_hex([ra[i] + (rb[i] - ra[i]) * t for i in range(3)])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def luminance(h):
|
|
35
|
+
def ch(c):
|
|
36
|
+
c /= 255
|
|
37
|
+
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
|
|
38
|
+
r, g, b = (ch(c) for c in hex_rgb(h))
|
|
39
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def contrast(a, b):
|
|
43
|
+
la, lb = sorted((luminance(a), luminance(b)), reverse=True)
|
|
44
|
+
return (la + 0.05) / (lb + 0.05)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# --- Signed distance functions ------------------------------------------------
|
|
48
|
+
|
|
49
|
+
def sd_rrect(x0, y0, x1, y1, r):
|
|
50
|
+
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
|
|
51
|
+
hx, hy = (x1 - x0) / 2 - r, (y1 - y0) / 2 - r
|
|
52
|
+
|
|
53
|
+
def d(px, py):
|
|
54
|
+
qx, qy = abs(px - cx) - hx, abs(py - cy) - hy
|
|
55
|
+
return math.hypot(max(qx, 0.0), max(qy, 0.0)) + min(max(qx, qy), 0.0) - r
|
|
56
|
+
return d
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def sd_circle(cx, cy, r):
|
|
60
|
+
return lambda px, py: math.hypot(px - cx, py - cy) - r
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def sd_polyline(points, width):
|
|
64
|
+
"""A stroked polyline with round caps and joins."""
|
|
65
|
+
segs = list(zip(points, points[1:]))
|
|
66
|
+
hw = width / 2
|
|
67
|
+
|
|
68
|
+
def d(px, py):
|
|
69
|
+
best = 1e9
|
|
70
|
+
for (ax, ay), (bx, by) in segs:
|
|
71
|
+
vx, vy, wx, wy = bx - ax, by - ay, px - ax, py - ay
|
|
72
|
+
ll = vx * vx + vy * vy
|
|
73
|
+
t = 0.0 if ll == 0 else max(0.0, min(1.0, (wx * vx + wy * vy) / ll))
|
|
74
|
+
best = min(best, math.hypot(wx - vx * t, wy - vy * t))
|
|
75
|
+
return best - hw
|
|
76
|
+
return d
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sd_arc(cx, cy, r, width, a0, a1):
|
|
80
|
+
"""A stroked circular arc from angle a0 to a1 (radians, counter-clockwise
|
|
81
|
+
from +x with y pointing down the screen), with round caps."""
|
|
82
|
+
hw = width / 2
|
|
83
|
+
ends = [(cx + r * math.cos(a), cy - r * math.sin(a)) for a in (a0, a1)]
|
|
84
|
+
|
|
85
|
+
def d(px, py):
|
|
86
|
+
ang = math.atan2(cy - py, px - cx)
|
|
87
|
+
if a0 <= ang <= a1:
|
|
88
|
+
return abs(math.hypot(px - cx, py - cy) - r) - hw
|
|
89
|
+
return min(math.hypot(px - ex, py - ey) for ex, ey in ends) - hw
|
|
90
|
+
return d
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def sd_union(*fs):
|
|
94
|
+
return lambda px, py: min(f(px, py) for f in fs)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def sd_subtract(a, b):
|
|
98
|
+
return lambda px, py: max(a(px, py), -b(px, py))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --- Raster ---------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
class Raster:
|
|
104
|
+
"""Premultiplied RGBA float buffer."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, w, h):
|
|
107
|
+
self.w, self.h = w, h
|
|
108
|
+
self.px = [0.0] * (w * h * 4)
|
|
109
|
+
|
|
110
|
+
def draw(self, sdf, colour, alpha=1.0, bbox=None):
|
|
111
|
+
"""Composite shape ``sdf`` over the buffer in ``colour`` (hex).
|
|
112
|
+
bbox=(x0, y0, x1, y1) limits the pixels visited."""
|
|
113
|
+
x0, y0, x1, y1 = bbox or (0, 0, self.w, self.h)
|
|
114
|
+
x0, y0 = max(0, int(x0)), max(0, int(y0))
|
|
115
|
+
x1, y1 = min(self.w, int(math.ceil(x1))), min(self.h, int(math.ceil(y1)))
|
|
116
|
+
rgb = hex_rgb(colour)
|
|
117
|
+
px, w = self.px, self.w
|
|
118
|
+
for y in range(y0, y1):
|
|
119
|
+
cy = y + 0.5
|
|
120
|
+
row = y * w
|
|
121
|
+
for x in range(x0, x1):
|
|
122
|
+
cov = 0.5 - sdf(x + 0.5, cy)
|
|
123
|
+
if cov <= 0:
|
|
124
|
+
continue
|
|
125
|
+
a = (1.0 if cov >= 1 else cov) * alpha
|
|
126
|
+
i = (row + x) * 4
|
|
127
|
+
inv = 1 - a
|
|
128
|
+
px[i] = rgb[0] / 255 * a + px[i] * inv
|
|
129
|
+
px[i + 1] = rgb[1] / 255 * a + px[i + 1] * inv
|
|
130
|
+
px[i + 2] = rgb[2] / 255 * a + px[i + 2] * inv
|
|
131
|
+
px[i + 3] = a + px[i + 3] * inv
|
|
132
|
+
return self
|
|
133
|
+
|
|
134
|
+
def rgba_bytes(self):
|
|
135
|
+
out = bytearray(self.w * self.h * 4)
|
|
136
|
+
p = self.px
|
|
137
|
+
for i in range(0, len(p), 4):
|
|
138
|
+
a = p[i + 3]
|
|
139
|
+
if a <= 0:
|
|
140
|
+
continue
|
|
141
|
+
out[i] = min(255, round(p[i] / a * 255))
|
|
142
|
+
out[i + 1] = min(255, round(p[i + 1] / a * 255))
|
|
143
|
+
out[i + 2] = min(255, round(p[i + 2] / a * 255))
|
|
144
|
+
out[i + 3] = min(255, round(a * 255))
|
|
145
|
+
return bytes(out)
|
|
146
|
+
|
|
147
|
+
def png(self):
|
|
148
|
+
return png_bytes(self.w, self.h, self.rgba_bytes())
|
|
149
|
+
|
|
150
|
+
def png_b64(self):
|
|
151
|
+
return base64.b64encode(self.png()).decode("ascii")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def expand9(rgba, w, h, bx, by, nw, nh):
|
|
155
|
+
"""Grow a 9-slice image's middle to nw x nh by repeating its centre column
|
|
156
|
+
and row (which, for the shapes drawn here, are uniform).
|
|
157
|
+
|
|
158
|
+
ttk image elements *tile* the middle of an image rather than stretching
|
|
159
|
+
it. With a few-pixel middle, a 1000-pixel panel was ~1000 alpha-blended
|
|
160
|
+
blits per redraw. Drawing small and growing here keeps the drawing cheap
|
|
161
|
+
and the blits few.
|
|
162
|
+
"""
|
|
163
|
+
stride = w * 4
|
|
164
|
+
rows = [rgba[y * stride:(y + 1) * stride] for y in range(h)]
|
|
165
|
+
grow_x = w - 2 * bx > 0 and nw > w
|
|
166
|
+
|
|
167
|
+
def widen(row):
|
|
168
|
+
if not grow_x:
|
|
169
|
+
return row
|
|
170
|
+
return row[:bx * 4] + row[bx * 4:(bx + 1) * 4] * (nw - 2 * bx) + row[(w - bx) * 4:]
|
|
171
|
+
out_w = nw if grow_x else w
|
|
172
|
+
if h - 2 * by > 0 and nh > h:
|
|
173
|
+
mid = widen(rows[by])
|
|
174
|
+
out = ([widen(r) for r in rows[:by]] + [mid] * (nh - 2 * by)
|
|
175
|
+
+ [widen(r) for r in rows[h - by:]])
|
|
176
|
+
else:
|
|
177
|
+
out = [widen(r) for r in rows]
|
|
178
|
+
return b"".join(out), out_w, len(out)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def png_bytes(w, h, rgba):
|
|
182
|
+
def chunk(tag, data):
|
|
183
|
+
c = struct.pack(">I", len(data)) + tag + data
|
|
184
|
+
return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
|
185
|
+
stride = w * 4
|
|
186
|
+
raw = b"".join(b"\x00" + rgba[y * stride:(y + 1) * stride] for y in range(h))
|
|
187
|
+
return (b"\x89PNG\r\n\x1a\n"
|
|
188
|
+
+ chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
|
|
189
|
+
+ chunk(b"IDAT", zlib.compress(raw, 6))
|
|
190
|
+
+ chunk(b"IEND", b""))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def ico_bytes(pngs):
|
|
194
|
+
"""An .ico holding PNG-compressed images, given [(size, png_bytes)]."""
|
|
195
|
+
header = struct.pack("<HHH", 0, 1, len(pngs))
|
|
196
|
+
entries, blobs = b"", b""
|
|
197
|
+
offset = 6 + 16 * len(pngs)
|
|
198
|
+
for size, data in pngs:
|
|
199
|
+
s = 0 if size >= 256 else size
|
|
200
|
+
entries += struct.pack("<BBBBHHII", s, s, 0, 0, 1, 32, len(data), offset)
|
|
201
|
+
blobs += data
|
|
202
|
+
offset += len(data)
|
|
203
|
+
return header + entries + blobs
|