Four things asked for in turn, landing together because they run through the same files. THE MAPS. The tiles were already cached and always had been -- a second evening on the same view was measured at nought network requests -- but the work done on them was not. Every window open decoded forty PNGs and resampled a megapixel and a half into this program's own projection, for an answer that cannot have changed, because a coastline does not move. The finished map is kept beside the tiles now: 0.61 seconds become 0.01, byte for byte identical, two hundred kilobytes a view. Both windows and both kinds of still picture get it, all four reaching the ground through one function. A map with squares missing is deliberately not kept, since caching a hole would keep it for a month and the point of calling a partial map provisional is that it is asked for again. And because this adds a disk consumer, the whole cache is now pruned to four hundred megabytes, least recently *used* first: a tile fetched a year ago and looked at last night is the receiver's own neighbourhood, and discarding that to keep last week's holiday is the wrong way round. THE LOOKUPS. APRS and FT8 now ask who each station is licensed to. Every other mode that hears a callsign already did -- speech transcripts, Morse idents, the recording browser -- and all five resolve through one file, so a callsign heard on two bands is asked about once. The rules for finding the licensed callsign inside a heard one are now in one place rather than per band, because getting them wrong is silent: a register asked about W1AW-9 returns nothing, which looks exactly like a station that is not licensed. An SSID, a rover suffix, a guest prefix, a digipeater alias and an unspelled hash all come off or are refused. The bug worth recording is that the first cut of this did the lookups and threw them away. The book has to be told to save and was not, so every evening would have asked the register about the same net again -- which is the one thing caching them was for, and is invisible from inside a single run because the answers are all in memory while it lasts. Caught by looking at the file on disk rather than at the display. There is a test for each side of it now, and a register of which modules resolve callsigns at all, which fails when a new one starts so that somebody has to decide whether it should. THE REGISTER. c in saunterbrowse opens everything ever looked up: sixty-odd callsigns and sixteen hundred aircraft here, every field of each in two columns because a licence has a dozen and a screen is wider than it is tall. tab switches, / searches every field rather than the name -- the question is usually "who was in Arizona" rather than "which callsign" -- and g opens the place in a browser. Only the coordinates go into that link: a map does not need to be told whose licence it is looking at, and the link is the one part of this that leaves the machine. A headless box, which is the normal case for a receiver, gets the coordinates printed instead. Callsigns no register could place are kept rather than dropped, because "asked about, and in no register reachable from here" is a fact about a station. THE FRONT OF IT. A title screen for each program: five rows of blocks cut by hand, a figlet dependency to draw eleven letters being the largest thing that would then be in the requirements, coloured blue to red across the width, which is the ramp every waterfall here already uses because it is what a spectrum looks like. The interesting part is where it does not appear -- everything here can be piped into something else and a banner in the middle of that is corruption rather than decoration, so anything that is not a terminal gets nothing, --help is untouched because it is drawn after parsing, --no-splash turns it off for a run and BANDSAUNTER_NO_SPLASH=1 for good. And the address. INSTALL.md said "git clone <the repository>" for a long time: a placeholder in the first command anybody types, unnoticed because nothing reads install instructions except somebody installing, who then cannot. It is filled in, along with the readme, the metadata, both manuals and the Homepage field of all three packages. The tile server's User-Agent pointed at a topic listing on somebody else's site for want of an address of its own; the usage policy of that service asks for one naming the application and giving somewhere to look it up, so an operator with a question about the traffic has somebody to ask, and now it gives the real one. Seven tests so the placeholder cannot come back, verified by putting it back and watching two of them fail. One thing forced by all this: the keys page in saunterbrowse was exactly as tall as an eighty-by-twenty-four terminal, so the register entry pushed "q quit" off the bottom. A test caught it. Home and End have merged into the Page Up line, which were always the same thought. THE WINDOWS. They open maximised now, this being a map and the thing anybody wants more of being map; f goes to true full screen and back, and is written along the top of the screen because a window with no frame is one somebody has to know a key to get out of. Maximised rather than frameless by default, because the title bar is where the band and the frequency are written. And a map made bigger now gets a sharper map, which it did not. The window only ever re-examined the ground when the view left the box that had been fetched, so a window opened at its default size and taken to the whole screen kept the map it started with until an aircraft wandered far enough to move it -- on a quiet band, a long time to look at a blurred coastline. Measured before it was believed: 1100 to 1920 asked for nothing and stretched a 1364-pixel map across 1920, then across 3840. It now compares map pixels per degree in hand against what the view wants, and asks when it is being blown up by more than fifteen per cent. That comparison has to be per degree rather than pixel against pixel, which a surviving mutation was what established: the fetched box is a quarter wider than the view, so a map with exactly as many pixels as the window is wide has only four fifths of them on the screen. The two ways of measuring agree everywhere except a narrow band, and the realistic case sits inside it. There is a test pinning that case now. Asking is safe at any size, because the request is keyed on the window's dimensions: once answered, nothing more is asked, which is what stops a window larger than the tile budget can cover from asking all evening. The braille, while this was open. The banners were blocks in capitals; they are braille in mixed case, two dots wide and four tall to a character, which is eight times the detail and is what makes room for two heights of letter at once -- a five-row block font has no second height to spend, so the name came out shouted. Two attempts failed first: thin one-dot strokes came out as confetti, because braille dots render as dots and a one-dot stroke reads as a dotted line rather than a line. What worked was cutting the font small, at cap height seven where there is only one way to draw each letter, and doubling it. Coloured deep blue through cyan to a cool white, which is deliberately not the waterfall ramp the rest of the program draws in: that one has to run to red because it stands in for a spectrum, and a title screen stands in for nothing. One hundred and four new tests. Full suite 2892 passed. Built as 2026-09-24_01. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
1887 lines
86 KiB
Python
1887 lines
86 KiB
Python
"""The sky in a window, while it is happening.
|
|
|
|
The terminal board says what is overhead; this says where. A real map, the
|
|
aircraft on it moving as the frames arrive, and beside each one a box with
|
|
everything known about it -- what it is, who flies it, where it came from,
|
|
how high, how fast, how far away and how long since it last said anything.
|
|
|
|
Qt is asked for and not required. Everything here is behind a lazy import,
|
|
so a machine with no Qt installed loses this window and nothing else: the
|
|
passive capture, the terminal board, the logs and the animations all work
|
|
exactly as they did. Four bindings are tried because distributions disagree
|
|
about which one to package, and the differences between them are two lines
|
|
of shim -- Qt 6 scopes its enumerations where Qt 5 did not, and PySide spells
|
|
Signal the way PyQt spells pyqtSignal.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
import time
|
|
from collections import deque
|
|
from dataclasses import dataclass
|
|
|
|
import numpy as np
|
|
|
|
from .flags import iso_for
|
|
from .flightlog import (DEFAULT_SPEED_UNIT, distance_label, distance_nm,
|
|
in_distance, in_speed, speed_label)
|
|
from .flightmap import LEADER_DASH as _LEADER_DASH
|
|
from .flightmap import Projection, altitude_step
|
|
from .ui import compass
|
|
|
|
# ``SkyView`` and ``Window`` are part of this module's interface too, but
|
|
# they are built on first use -- see __getattr__ at the foot of the file --
|
|
# so that importing it costs nothing on a machine with no Qt on it, and so
|
|
# they cannot be listed here.
|
|
__all__ = ["available", "binding", "show", "fetch_ground", "Sky", "Blip",
|
|
"blip_for", "place_box", "glide", "dash_for", "wrap_value",
|
|
"WRAP_CHARS",
|
|
"MISSING_QT"]
|
|
|
|
BINDINGS = ("PyQt6", "PyQt5", "PySide6", "PySide2")
|
|
|
|
MISSING_QT = (
|
|
"This needs Qt, which is not installed.\n"
|
|
" Debian/Ubuntu: sudo apt install python3-pyqt6\n"
|
|
" Fedora: sudo dnf install python3-pyqt6\n"
|
|
" Arch: sudo pacman -S python-pyqt6\n"
|
|
" or: pip install PyQt6\n"
|
|
"Everything else works without it: passive capture still records, and "
|
|
"`bandsaunter flights` still draws the map afterwards."
|
|
)
|
|
|
|
# How often the window redraws itself. Positions arrive about twice a second
|
|
# and nothing on the picture moves faster than an aeroplane, so this is
|
|
# generous already; a busy sky is drawn perfectly well at this rate.
|
|
REDRAW_MS = 200
|
|
|
|
# The trail behind each aircraft, in positions rather than seconds, because
|
|
# it is drawn every frame and wants a hard bound.
|
|
TRAIL_POINTS = 400
|
|
|
|
# How far the worked-out middle of the map has to drift before it is moved.
|
|
# Below this it is noise from aircraft arriving and leaving, and moving the
|
|
# map for it costs the tiles that were fetched for the old view.
|
|
RESETTLE_NM = 12.0
|
|
|
|
# How much map to fetch beyond what is being shown. A window that fetched
|
|
# exactly what it needed would fetch again on every resize and every small
|
|
# drift. Modest, because the fetch is now at the picture's own resolution
|
|
# and every extra degree of margin is a ring of tiles: with the middle of
|
|
# the map settling rather than wandering, a little is enough.
|
|
GROUND_MARGIN = 0.12
|
|
|
|
# How much stretching of the map underneath to put up with before fetching a
|
|
# sharper one. Something is needed: a window dragged one pixel wider must not
|
|
# refetch, and a window taken from a quarter of the screen to all of it must.
|
|
# Fifteen per cent is about where the lettering on a coastline starts to look
|
|
# soft, and is comfortably more than any resize that was not deliberate.
|
|
GROUND_STRETCH = 0.15
|
|
|
|
# What to do about a map that came back with squares missing from it. The
|
|
# usual cause is a resize: the window grows, a sharper zoom is chosen, and a
|
|
# hundred tiles that have never been on this disk are asked for at once --
|
|
# whereupon a volunteer-funded server refuses some of them. The fetch
|
|
# retries its own misses, so anything left is a server asking to be left
|
|
# alone for a bit, and the wait is long enough to be that. Counted as well
|
|
# as timed because a square can be missing for good, and asking all night
|
|
# for a tile that does not exist is the same discourtesy more slowly.
|
|
GROUND_RETRY_S = 25.0
|
|
GROUND_TRIES = 4
|
|
|
|
# The widest a line in a box is allowed to get before it is folded. An
|
|
# airport's full name and the town it is in run to forty characters on their
|
|
# own and a route is two of them, so one flight from Los Angeles to Dallas
|
|
# Fort Worth would otherwise make its box wider than the map it sits on.
|
|
WRAP_CHARS = 30
|
|
|
|
# The flag is drawn at its own size: the box font is about eleven pixels
|
|
# tall, so twelve by eight sits on a line without crowding it.
|
|
FLAG_PIXELS = 12
|
|
|
|
# Below this an aircraft keeps its symbol and loses its box.
|
|
LABEL_WHILE = 0.40
|
|
|
|
# The dashes on the line from a box to its aircraft, in pixels on and off.
|
|
# Taken from the drawing that also uses it rather than written down twice:
|
|
# the two pictures are meant to look like the same program, and two copies
|
|
# of a number are two chances to change only one of them.
|
|
LEADER_DASH = tuple(float(step) for step in _LEADER_DASH)
|
|
|
|
|
|
def dash_for(pattern, width: float) -> list:
|
|
"""A dash pattern in pixels, as the pen drawing it wants to be told.
|
|
|
|
Qt measures a dash pattern in multiples of the pen's own width, so the
|
|
same pattern handed to a wide pen and a narrow one gives dashes of
|
|
different lengths. A glowing line is the same line drawn two or three
|
|
times at different widths, so without this its halo would have dashes
|
|
three times the length of its core and the line would come out as beads
|
|
rather than as a dashed line.
|
|
"""
|
|
width = max(0.1, float(width))
|
|
return [max(0.1, float(step) / width) for step in pattern]
|
|
|
|
# How long a box takes to swing across when it has to move, and how often to
|
|
# repaint while one is on its way. The ordinary redraw is five times a
|
|
# second, which is plenty for aeroplanes -- they move a pixel or two between
|
|
# frames -- but a box crossing the window in five steps is a slideshow, so
|
|
# the picture is redrawn faster for as long as anything is actually moving
|
|
# and drops back to the slow rate the moment everything has settled.
|
|
BOX_GLIDE = 0.45
|
|
BOX_GLIDE_MS = 33
|
|
BOX_SETTLED_PX = 0.4
|
|
|
|
|
|
def _alpha(strength: float) -> int:
|
|
"""How opaque something at this strength is drawn."""
|
|
return max(0, min(255, int(round(255 * strength))))
|
|
|
|
|
|
def _qt():
|
|
"""The first Qt binding that imports, or None.
|
|
|
|
Cached on the function, because working this out on every paint would be
|
|
silly and because the answer cannot change while the program runs.
|
|
"""
|
|
if getattr(_qt, "_found", "?") != "?":
|
|
return _qt._found
|
|
for name in BINDINGS:
|
|
try:
|
|
core = __import__(f"{name}.QtCore", fromlist=["QtCore"])
|
|
gui = __import__(f"{name}.QtGui", fromlist=["QtGui"])
|
|
widgets = __import__(f"{name}.QtWidgets", fromlist=["QtWidgets"])
|
|
except ImportError:
|
|
continue
|
|
signal = getattr(core, "pyqtSignal", None) or getattr(core, "Signal")
|
|
_qt._found = (name, core, gui, widgets, signal)
|
|
return _qt._found
|
|
_qt._found = None
|
|
return None
|
|
|
|
|
|
def available() -> bool:
|
|
"""Whether a window can be opened at all."""
|
|
return _qt() is not None
|
|
|
|
|
|
def binding() -> str:
|
|
"""Which Qt is being used, for saying so on the screen."""
|
|
found = _qt()
|
|
return found[0] if found else ""
|
|
|
|
|
|
def _enum(owner, group: str, name: str):
|
|
"""Qt 6 scopes its enumerations; Qt 5 hangs them on the class."""
|
|
return getattr(getattr(owner, group, owner), name)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# What the window is told about one aircraft
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class Blip:
|
|
"""One aircraft, as far as the window is concerned.
|
|
|
|
A flat copy rather than the live object, taken on the listening thread:
|
|
the registry is being written to as fast as frames arrive, and painting
|
|
from underneath that is how a display ends up drawing half of one
|
|
aircraft and half of another.
|
|
"""
|
|
|
|
icao: str = ""
|
|
callsign: str = ""
|
|
latitude: float = 0.0
|
|
longitude: float = 0.0
|
|
altitude_ft: int = 0
|
|
ground_speed_kt: float = 0.0
|
|
track_deg: float = 0.0
|
|
vertical_rate_fpm: int = 0
|
|
messages: int = 0
|
|
category: str = "" # what it said it was: heavy, rotorcraft...
|
|
first_seen: float = 0.0
|
|
last_seen: float = 0.0
|
|
# Everything below comes from a register rather than off the air.
|
|
registration: str = ""
|
|
type_code: str = ""
|
|
model: str = ""
|
|
manufacturer: str = ""
|
|
operator: str = ""
|
|
country: str = ""
|
|
country_code: str = "" # two letters, for the flag beside it
|
|
origin: str = ""
|
|
origin_country: str = "" # two letters, for the flag beside it
|
|
destination: str = ""
|
|
destination_country: str = ""
|
|
# Whether this aircraft could be flying the route its callsign is given.
|
|
# A callsign is a flight number rather than a leg, so often it could not.
|
|
route_fits: bool = True
|
|
|
|
# The three hooks that let this window draw something that is not an
|
|
# aeroplane. All defaulted, so an aircraft is exactly what it was.
|
|
#
|
|
# A mark on a map wants three things decided: what shape it is, what
|
|
# colour, and what its box says. For an aeroplane all three follow from
|
|
# the aeroplane -- a triangle along the heading, a colour off the
|
|
# altitude ramp, and a box built from the registers. For anything else
|
|
# they have to be given, and giving them is cheaper than a second window.
|
|
shape: str = "aircraft" # aircraft, vehicle or station
|
|
colour_index: int | None = None # a palette index, or off the ramp
|
|
details: tuple = () # (label, value, flag) rows for the box
|
|
|
|
@property
|
|
def located(self) -> bool:
|
|
return bool(self.latitude or self.longitude)
|
|
|
|
@property
|
|
def name(self) -> str:
|
|
return self.callsign or self.icao
|
|
|
|
def lines(self, unit: str, home=None) -> list[tuple[str, str, str]]:
|
|
"""The box's contents: a label, a value and a flag, a line at a time.
|
|
|
|
Given outright where the mark is not an aeroplane, because there is
|
|
nothing about a weather station that an altitude ramp and an airline
|
|
register can say.
|
|
|
|
The flag is a two-letter country code the drawing turns into twelve
|
|
pixels of one, and is empty for every line that is only words.
|
|
|
|
Everything that is known and nothing that is not -- an empty line for
|
|
a register that has not answered yet would leave a box full of gaps
|
|
that never fill in.
|
|
"""
|
|
if self.details:
|
|
return list(self.details)
|
|
out: list[tuple[str, str, str]] = []
|
|
# What sort of aircraft it is: the emitter category, which came off
|
|
# the air with the callsign, and whether the address is a military
|
|
# one, which comes off no air at all.
|
|
from .flights import aircraft_class
|
|
|
|
sort_of = aircraft_class(self.icao, self.category)
|
|
if sort_of:
|
|
out.append(("class", sort_of, ""))
|
|
kind = " ".join(x for x in (self.manufacturer, self.model) if x)
|
|
if self.type_code and self.registration:
|
|
out.append((self.type_code, self.registration, ""))
|
|
elif self.registration:
|
|
out.append(("reg", self.registration, ""))
|
|
if kind:
|
|
out.append(("", kind, ""))
|
|
if self.operator:
|
|
out.append(("", self.operator, ""))
|
|
# The two ends of the flight on their own lines rather than joined by
|
|
# an arrow, so that each can carry the flag of the country it is in.
|
|
if self.route_fits and self.origin:
|
|
out.append(("from", self.origin, self.origin_country))
|
|
if self.route_fits and self.destination:
|
|
out.append(("to", self.destination, self.destination_country))
|
|
if self.altitude_ft:
|
|
climb = ""
|
|
if self.vertical_rate_fpm > 100:
|
|
climb = f" ↑{self.vertical_rate_fpm:,} fpm"
|
|
elif self.vertical_rate_fpm < -100:
|
|
climb = f" ↓{abs(self.vertical_rate_fpm):,} fpm"
|
|
out.append(("alt", f"{self.altitude_ft:,} ft{climb}", ""))
|
|
if self.ground_speed_kt:
|
|
out.append(("gs", f"{in_speed(self.ground_speed_kt, unit):.0f} "
|
|
f"{speed_label(unit)} "
|
|
f"{self.track_deg:03.0f}° "
|
|
f"{compass(self.track_deg)}", ""))
|
|
if self.located and home is not None:
|
|
away = distance_nm(home[0], home[1], self.latitude, self.longitude)
|
|
out.append(("range", f"{in_distance(away, unit):.0f} "
|
|
f"{distance_label(unit)} "
|
|
f"{self._bearing(home):03.0f}°", ""))
|
|
if self.located:
|
|
out.append(("pos", f"{self.latitude:.4f}, "
|
|
f"{self.longitude:.4f}", ""))
|
|
age = max(0.0, time.time() - self.last_seen)
|
|
out.append(("", f"{self.messages:,} frames {age:.0f}s ago", ""))
|
|
if self.country:
|
|
out.append(("reg'd", self.country, self.country_code))
|
|
return out
|
|
|
|
def _bearing(self, home) -> float:
|
|
p1, p2 = math.radians(home[0]), math.radians(self.latitude)
|
|
dl = math.radians(self.longitude - home[1])
|
|
y = math.sin(dl) * math.cos(p2)
|
|
x = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)
|
|
return math.degrees(math.atan2(y, x)) % 360.0
|
|
|
|
|
|
def wrap_value(text: str, width: int = WRAP_CHARS) -> list[str]:
|
|
"""Fold one line of a box onto as many lines as it needs.
|
|
|
|
A route is broken at the arrow before anything else, so that the two ends
|
|
of the flight stay whole and sit under one another where they can be read
|
|
as a pair. Everything else is folded between words, and a single word
|
|
longer than the whole width -- which is nothing an aircraft has ever sent,
|
|
but is exactly the sort of thing a register will one day return -- is cut
|
|
rather than allowed to widen the box on its own.
|
|
"""
|
|
text = (text or "").strip()
|
|
if len(text) <= width:
|
|
return [text]
|
|
if " → " in text:
|
|
origin, destination = text.split(" → ", 1)
|
|
folded = wrap_value(origin, width)
|
|
onward = wrap_value(destination, max(4, width - 2))
|
|
return folded + [f"→ {piece}" if i == 0 else f" {piece}"
|
|
for i, piece in enumerate(onward)]
|
|
out: list[str] = []
|
|
line = ""
|
|
for word in text.split():
|
|
while len(word) > width:
|
|
if line:
|
|
out.append(line)
|
|
line = ""
|
|
out.append(word[:width])
|
|
word = word[width:]
|
|
if line and len(line) + 1 + len(word) > width:
|
|
out.append(line)
|
|
line = word
|
|
else:
|
|
line = f"{line} {word}".strip()
|
|
if line:
|
|
out.append(line)
|
|
return out or [text]
|
|
|
|
|
|
def blip_for(craft, entry=None) -> Blip:
|
|
"""One aircraft as the window wants it, with whatever a register said."""
|
|
blip = Blip(icao=craft.icao, callsign=craft.callsign,
|
|
latitude=craft.latitude, longitude=craft.longitude,
|
|
altitude_ft=craft.altitude_ft,
|
|
ground_speed_kt=craft.ground_speed_kt,
|
|
track_deg=craft.track_deg,
|
|
vertical_rate_fpm=craft.vertical_rate_fpm,
|
|
messages=craft.messages, first_seen=craft.first_seen,
|
|
last_seen=craft.last_seen,
|
|
category=getattr(craft, "category", ""))
|
|
if entry is not None:
|
|
blip.registration = entry.registration
|
|
blip.type_code = entry.type_code
|
|
blip.model = entry.model
|
|
blip.manufacturer = entry.manufacturer
|
|
blip.operator = entry.operator or entry.airline
|
|
blip.country = entry.owner_country or entry.country
|
|
blip.country_code = iso_for(blip.country)
|
|
blip.origin = entry.origin or entry.origin_code
|
|
blip.origin_country = entry.origin_country
|
|
blip.destination = entry.destination or entry.destination_code
|
|
blip.destination_country = entry.destination_country
|
|
if blip.located:
|
|
from .flights import route_fits
|
|
|
|
blip.route_fits = route_fits(entry, blip.latitude, blip.longitude)
|
|
return blip
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# What the listening thread and the painting thread share
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class Sky:
|
|
"""Everything the window draws, written by one thread and read by another.
|
|
|
|
Plain locking rather than Qt's signals, so that none of this depends on
|
|
which binding was found -- and so that the whole of it can be tested
|
|
without a window at all.
|
|
"""
|
|
|
|
def __init__(self, unit: str = DEFAULT_SPEED_UNIT, hold: float = 45.0,
|
|
home=None, radius_nm: float = 100.0,
|
|
brightness: float = 0.70, fade: float = 20.0,
|
|
airports: bool = False, rings: bool = False,
|
|
box_opacity: float = 0.85, pulse: float = 0.0,
|
|
echo: float = 0.0, echo_reach: float = 0.0,
|
|
fades: bool = True, channel: str = "1090 MHz",
|
|
subject: str = "overhead", counted: str = "frames",
|
|
waiting: str = ""):
|
|
import threading
|
|
|
|
self.unit = unit
|
|
# Whether a mark that has gone quiet leaves the picture.
|
|
#
|
|
# An aeroplane that stops transmitting has flown out of range, and
|
|
# showing it an hour later where it was would be drawing something
|
|
# that is certainly not there. A fixed amateur station that stops
|
|
# transmitting is still where it was -- it beacons every half hour,
|
|
# and the gaps are silence rather than absence -- so the picture
|
|
# accumulates instead, and an evening's listening fills a map.
|
|
self.fades = bool(fades)
|
|
# What the strip along the top says it is looking at.
|
|
self.channel = channel
|
|
self.subject = subject
|
|
self.counted = counted
|
|
# What the empty picture says while there is nothing to draw on it.
|
|
# Said here rather than in the drawing, because what has to arrive
|
|
# before a mark can be placed is a fact about the signal and not
|
|
# about the window: an aeroplane needs two position frames of
|
|
# opposite parity, and an amateur station needs to have mentioned
|
|
# where it is, which not all of them ever do.
|
|
self.waiting = waiting or (
|
|
f"listening on {channel}\n\n"
|
|
"nothing placed yet — an aircraft is on the map once an even\n"
|
|
"and an odd position frame have both arrived")
|
|
self.hold = hold
|
|
self.home = home
|
|
self.radius_nm = radius_nm
|
|
self.brightness = brightness
|
|
self.fade = fade
|
|
# Off unless asked for, because saying yes means a question to a
|
|
# network the first time an area is drawn. The program turns it on;
|
|
# anything using this as a library has to say so on purpose.
|
|
self.show_airports = airports
|
|
self.show_rings = rings
|
|
# How solid the card behind each information box is. Nothing at
|
|
# all puts the words straight on the map, which is readable over
|
|
# water and not over a city.
|
|
self.box_opacity = max(0.0, min(1.0, float(box_opacity)))
|
|
# Seconds a pulse takes and seconds between echoes; nought for off.
|
|
self.pulse = max(0.0, float(pulse))
|
|
self.echo = max(0.0, float(echo))
|
|
self.echo_reach = max(0.0, float(echo_reach))
|
|
self.frames = 0
|
|
self.aircraft_seen = 0
|
|
self.started = time.time()
|
|
self.log_name = ""
|
|
self.note = ""
|
|
self.stopping = False
|
|
# Set when the listening has finished of its own accord -- the time
|
|
# asked for has run out, or the receiver stopped. The window shuts
|
|
# itself when it sees this, so that "listen for ten minutes" means
|
|
# the same thing whether or not there is a window open.
|
|
self.finished = False
|
|
self._lock = threading.Lock()
|
|
self._blips: dict[str, Blip] = {}
|
|
self._trails: dict[str, deque] = {}
|
|
self._ground = None
|
|
self._ground_for = None
|
|
self._ground_box = None
|
|
self._ground_serial = 0
|
|
# Whether the map in hand is the whole of what was asked for, when
|
|
# it arrived, and how many times it has been asked for since.
|
|
self._ground_settled = True
|
|
self._ground_at = 0.0
|
|
self._ground_tries = 0
|
|
self._ground_ask = None
|
|
# The aerodromes under the view, fetched with the map and kept the
|
|
# same way: they come from the same place, cover the same box, and
|
|
# go stale at the same moment.
|
|
self._airports: list | None = None
|
|
self._airports_box = None
|
|
self._airports_want = None
|
|
self._wanted = None
|
|
self._settled = None
|
|
|
|
# -- written by the listener ------------------------------------------
|
|
def update(self, blips, frames: int, seen: int) -> None:
|
|
with self._lock:
|
|
self.frames = frames
|
|
self.aircraft_seen = seen
|
|
for blip in blips:
|
|
self._blips[blip.icao] = blip
|
|
if blip.located:
|
|
trail = self._trails.setdefault(
|
|
blip.icao, deque(maxlen=TRAIL_POINTS))
|
|
here = (blip.latitude, blip.longitude, blip.altitude_ft)
|
|
if not trail or trail[-1][:2] != here[:2]:
|
|
trail.append(here)
|
|
|
|
def set_ground(self, levels, key, box=None, settled: bool = True) -> None:
|
|
"""Keep the map that was fetched, and the piece of world it covers.
|
|
|
|
A failed fetch is kept too, as nothing: otherwise a machine with no
|
|
network asks for the same tiles five times a second all night.
|
|
|
|
``settled`` is whether this is the whole map or only most of it.
|
|
Most of it is still worth drawing -- the alternative is a bare grid
|
|
-- but it is not worth keeping for the life of the view, so an
|
|
unsettled map may be asked for again.
|
|
"""
|
|
with self._lock:
|
|
if key != self._ground_for:
|
|
self._ground_tries = 0
|
|
self._ground, self._ground_for = levels, key
|
|
self._ground_box = box
|
|
self._ground_settled = bool(settled)
|
|
self._ground_at = time.time()
|
|
if not settled:
|
|
self._ground_tries += 1
|
|
# Counted rather than compared: the drawing side keeps the
|
|
# dimmed pixels it made last time, and needs to know whether
|
|
# what it made them from is still the same map.
|
|
self._ground_serial += 1
|
|
if self._wanted is not None and self._wanted[0] == key:
|
|
self._wanted = None
|
|
|
|
def set_airports(self, found, box) -> None:
|
|
"""Keep the aerodromes fetched, and the piece of world they cover.
|
|
|
|
An empty answer is kept as an empty list rather than as nothing at
|
|
all: an area with no aerodromes in it has been asked about and
|
|
answered, and asking again five times a second for the rest of the
|
|
night would be the wrong lesson to draw from it.
|
|
"""
|
|
with self._lock:
|
|
self._airports = list(found or [])
|
|
self._airports_box = box
|
|
if self._airports_want == box:
|
|
self._airports_want = None
|
|
|
|
def want_airports(self, box) -> None:
|
|
"""Say which aerodromes are needed. Painting never waits."""
|
|
with self._lock:
|
|
if self._airports_box != box:
|
|
self._airports_want = box
|
|
|
|
def wanted_airports(self):
|
|
with self._lock:
|
|
return self._airports_want
|
|
|
|
def airports_covering(self, south, west, north, east):
|
|
"""The aerodromes fetched, or None if what is here does not cover.
|
|
|
|
Held to the same rule as the map: what was asked for covers rather
|
|
more world than is being shown, so a view that has drifted inside it
|
|
is answered from what is already here. A view that has moved
|
|
outside it is answered with None -- not an empty list, which would
|
|
mean "asked, and there are none" -- so that the caller knows to ask.
|
|
"""
|
|
with self._lock:
|
|
found, box = self._airports, self._airports_box
|
|
if found is None or box is None:
|
|
return None
|
|
if (south >= box[0] and west >= box[1]
|
|
and north <= box[2] and east <= box[3]):
|
|
return found
|
|
return None
|
|
|
|
def ground_serial(self) -> int:
|
|
"""Which map is in hand. Changes whenever a new one is fetched."""
|
|
with self._lock:
|
|
return self._ground_serial
|
|
|
|
def ground_settled(self) -> bool:
|
|
"""Whether the map in hand is the whole of what was asked for."""
|
|
with self._lock:
|
|
return self._ground_settled
|
|
|
|
def want_ground(self, key, box, size) -> None:
|
|
"""Say which map is needed. Painting must never wait on a network."""
|
|
with self._lock:
|
|
if self._ground_for != key:
|
|
self._wanted = (key, box, size)
|
|
self._ground_ask = (key, box, size)
|
|
|
|
def reask_ground(self) -> None:
|
|
"""Ask again for a map that came back with squares missing from it.
|
|
|
|
For the map already in hand, under the key it was fetched with,
|
|
rather than for whatever the view happens to be this frame. The
|
|
view drifts a pixel at a time inside the box that was fetched and is
|
|
answered from it without asking for anything; asking on each of
|
|
those drifts would be a refetch every frame rather than a retry.
|
|
|
|
There was a check here that the remembered request was still the one
|
|
the map in hand came from. It could not be made to fail: a request
|
|
for a different view is only ever taken up after ``_wanted`` has
|
|
been filled, and a filled ``_wanted`` has already returned above.
|
|
Code that cannot be made to matter is code that is not doing
|
|
anything, so it went.
|
|
"""
|
|
with self._lock:
|
|
if self._ground_settled or self._wanted is not None:
|
|
return
|
|
if self._ground_tries >= GROUND_TRIES:
|
|
return
|
|
if time.time() - self._ground_at >= GROUND_RETRY_S:
|
|
self._wanted = self._ground_ask
|
|
|
|
def wanted_ground(self):
|
|
with self._lock:
|
|
return self._wanted
|
|
|
|
def ground_covering(self, south, west, north, east):
|
|
"""The map already fetched, if it covers this view, and its box.
|
|
|
|
What is asked for is a slightly different piece of the world every
|
|
time the middle shifts or the window is resized, and refetching for
|
|
each of those would leave the ground blank while it happened. The
|
|
fetched piece is bigger than the piece being shown for exactly this
|
|
reason, and anything inside it is taken from what is already here.
|
|
"""
|
|
with self._lock:
|
|
levels, box = self._ground, self._ground_box
|
|
if levels is None or box is None:
|
|
return None, None
|
|
if (south >= box[0] and west >= box[1]
|
|
and north <= box[2] and east <= box[3]):
|
|
return levels, box
|
|
return None, None
|
|
|
|
# -- read by the window -----------------------------------------------
|
|
def flying(self, now: float | None = None) -> list[Blip]:
|
|
"""What is overhead, oldest first heard at the top.
|
|
|
|
An aircraft nothing has been heard from for a while has gone out of
|
|
range; it stays in the log and fades off the picture.
|
|
"""
|
|
now = time.time() if now is None else now
|
|
if not self.fades:
|
|
with self._lock:
|
|
out = [b for b in self._blips.values() if b.located]
|
|
# Most recently heard first, because that is the order the boxes
|
|
# are laid out in and a map that has been accumulating all
|
|
# evening has more marks than it has room for boxes. The ones
|
|
# worth reading are the ones that just spoke.
|
|
out.sort(key=lambda b: (-b.last_seen, b.name))
|
|
return out
|
|
limit = self.hold + max(0.0, self.fade)
|
|
with self._lock:
|
|
out = [b for b in self._blips.values()
|
|
if now - b.last_seen <= limit and b.located]
|
|
out.sort(key=lambda b: (b.first_seen, b.icao))
|
|
return out
|
|
|
|
def strength(self, blip: Blip, now: float | None = None) -> float:
|
|
"""How strongly to draw one aircraft: full, then fading, then gone.
|
|
|
|
Taking an aircraft off the picture between one frame and the next
|
|
says it stopped existing. Fading it says it stopped talking, which
|
|
is what actually happened.
|
|
"""
|
|
if not self.fades:
|
|
return 1.0
|
|
now = time.time() if now is None else now
|
|
age = max(0.0, now - blip.last_seen)
|
|
if age <= self.hold or self.fade <= 0:
|
|
return 1.0 if age <= self.hold else 0.0
|
|
return max(0.0, 1.0 - (age - self.hold) / self.fade)
|
|
|
|
def trail(self, icao: str) -> list:
|
|
with self._lock:
|
|
return list(self._trails.get(icao, ()))
|
|
|
|
def ground(self, key):
|
|
"""The map underneath, if the one we have is for this view."""
|
|
with self._lock:
|
|
return self._ground if self._ground_for == key else None
|
|
|
|
def centre(self):
|
|
"""Where to put the middle of the map.
|
|
|
|
Whatever the receiver was told, or the middle of everything heard so
|
|
far -- a median, so one bad position cannot move it.
|
|
|
|
Once settled it is left alone. Recomputing it every time the picture
|
|
is painted moves the map by a fraction of a mile whenever an aircraft
|
|
appears or leaves, which throws away the tiles fetched for the old
|
|
view and leaves the ground blank while new ones are fetched: the map
|
|
blinks out several times a minute for no reason anybody watching
|
|
could see. It only moves again if it has drifted far enough to
|
|
matter, which happens once, early, and then never.
|
|
"""
|
|
if self.home is not None:
|
|
return self.home
|
|
with self._lock:
|
|
settled = self._settled
|
|
lats = sorted(b.latitude for b in self._blips.values() if b.located)
|
|
lons = sorted(b.longitude for b in self._blips.values() if b.located)
|
|
if not lats:
|
|
return settled
|
|
middle = lats[len(lats) // 2], lons[len(lons) // 2]
|
|
if settled is not None and \
|
|
distance_nm(settled[0], settled[1], *middle) < RESETTLE_NM:
|
|
return settled
|
|
with self._lock:
|
|
self._settled = middle
|
|
return middle
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Laying the boxes out
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _clear(bx: int, by: int, width: int, height: int, taken: list) -> bool:
|
|
return not any(bx < t[0] + t[2] and t[0] < bx + width
|
|
and by < t[1] + t[3] and t[1] < by + height for t in taken)
|
|
|
|
|
|
def glide(current: tuple[float, float], target: tuple[float, float],
|
|
elapsed: float, seconds: float = BOX_GLIDE) -> tuple[float, float]:
|
|
"""One step of a box on its way to where it now belongs.
|
|
|
|
Boxes are placed afresh every frame, so a box whose spot has been taken
|
|
by something else jumps to its new one between one frame and the next.
|
|
The jump is the problem: the eye reads a thing that teleports as a
|
|
different thing, and on a busy screen several of them teleport at once.
|
|
Easing it means the same box is still the same box, and the movement
|
|
itself says that something moved rather than appeared.
|
|
|
|
Eased by the distance left rather than by a count of frames, so it is
|
|
the same swing whatever the redraw rate is doing, and so a window that
|
|
was buried under another for ten seconds does not spend the next half
|
|
second replaying moves nobody watched: a long enough gap arrives.
|
|
"""
|
|
cx, cy = current
|
|
tx, ty = target
|
|
if seconds <= 0.0:
|
|
return (float(tx), float(ty))
|
|
if elapsed <= 0.0:
|
|
return (float(cx), float(cy))
|
|
# Three time constants, so `seconds` is most of the way there rather
|
|
# than a fraction of the way there.
|
|
part = 1.0 - math.exp(-3.0 * elapsed / seconds)
|
|
nx, ny = cx + (tx - cx) * part, cy + (ty - cy) * part
|
|
if abs(tx - nx) < BOX_SETTLED_PX and abs(ty - ny) < BOX_SETTLED_PX:
|
|
return (float(tx), float(ty)) # arrived; stop asking for frames
|
|
return (nx, ny)
|
|
|
|
|
|
def place_box(x: int, y: int, width: int, height: int, taken: list,
|
|
bounds: tuple[int, int, int, int]) -> tuple[int, int]:
|
|
"""Where to put an aircraft's box so that it covers nothing that matters.
|
|
|
|
The eight places beside the symbol are tried first, because a box next
|
|
to the thing it describes needs no explaining. When those are taken --
|
|
which happens as soon as a few aircraft are close together -- it works
|
|
outwards in rings, accepting a longer leader line in exchange for a box
|
|
that can be read. Only when the screen is genuinely full does it give
|
|
up and overlap, since a box in an awkward place still says what the
|
|
aircraft is and no box at all does not.
|
|
"""
|
|
left, top, right, bottom = bounds
|
|
gap = 14
|
|
|
|
def fits(bx, by):
|
|
bx = max(left, min(int(bx), right - width))
|
|
by = max(top, min(int(by), bottom - height))
|
|
return (bx, by) if _clear(bx, by, width, height, taken) else None
|
|
|
|
beside = ((x + gap, y - height // 2), (x - gap - width, y - height // 2),
|
|
(x + gap, y + gap), (x - gap - width, y + gap),
|
|
(x + gap, y - gap - height), (x - gap - width, y - gap - height),
|
|
(x - width // 2, y + gap), (x - width // 2, y - gap - height))
|
|
for spot in beside:
|
|
found = fits(*spot)
|
|
if found:
|
|
return found
|
|
for reach in (1.4, 1.9, 2.6, 3.4, 4.4, 5.6):
|
|
for step in range(16):
|
|
angle = math.tau * step / 16
|
|
found = fits(x + math.cos(angle) * width * reach - width / 2,
|
|
y + math.sin(angle) * height * reach - height / 2)
|
|
if found:
|
|
return found
|
|
return (max(left, min(x + gap, right - width)),
|
|
max(top, min(y - height // 2, bottom - height)))
|
|
|
|
|
|
def _build():
|
|
"""Define the window classes, now that we know Qt is here."""
|
|
if getattr(_build, "_made", None) is not None:
|
|
return _build._made
|
|
found = _qt()
|
|
if found is None:
|
|
return None
|
|
_name, QtCore, QtGui, QtWidgets, _signal = found
|
|
|
|
from .flightmap import (AIRPORT, BG, DIM, GRID, GROUND, GROUND_SHADES,
|
|
HOME, INK, LEADER, PALETTE, PANEL, RAMP,
|
|
_degrees, _grid_step)
|
|
|
|
Qt = QtCore.Qt
|
|
QPointF, QRectF, QTimer = QtCore.QPointF, QtCore.QRectF, QtCore.QTimer
|
|
QColor, QFont, QImage = QtGui.QColor, QtGui.QFont, QtGui.QImage
|
|
QPainter, QPen, QPolygonF = QtGui.QPainter, QtGui.QPen, QtGui.QPolygonF
|
|
|
|
NO_PEN = _enum(Qt, "PenStyle", "NoPen")
|
|
ROUND_CAP = _enum(Qt, "PenCapStyle", "RoundCap")
|
|
ROUND_JOIN = _enum(Qt, "PenJoinStyle", "RoundJoin")
|
|
_NO_BRUSH = QtGui.QBrush(_enum(Qt, "BrushStyle", "NoBrush"))
|
|
DOTTED = _enum(Qt, "PenStyle", "DotLine")
|
|
RGB888 = _enum(QImage, "Format", "Format_RGB888")
|
|
ANTIALIAS = _enum(QPainter, "RenderHint", "Antialiasing")
|
|
MONOSPACE = _enum(QFont, "StyleHint", "Monospace")
|
|
KEY_Q = _enum(Qt, "Key", "Key_Q")
|
|
KEY_ESCAPE = _enum(Qt, "Key", "Key_Escape")
|
|
|
|
def rgb(index, alpha=255) -> QColor:
|
|
r, g, b = (int(v) for v in PALETTE[index])
|
|
return QColor(r, g, b, alpha)
|
|
|
|
def craft_colour(feet, alpha=255) -> QColor:
|
|
return rgb(RAMP + altitude_step(feet), alpha)
|
|
|
|
def _lifted(colour, level: float) -> QColor:
|
|
"""One colour walked towards white, and dimmed below the middle.
|
|
|
|
The bright end is a swell towards the peak colour the pictures use;
|
|
the dim end is the same colour with the life taken out of it, so
|
|
that a pulse is a change in brightness rather than in hue.
|
|
"""
|
|
from .flightmap import HOT_LIFT
|
|
|
|
out = QColor(colour)
|
|
if level >= 0.5:
|
|
part = (level - 0.5) * 2.0 * HOT_LIFT
|
|
out.setRgb(*(int(round(c + (255 - c) * part))
|
|
for c in (colour.red(), colour.green(),
|
|
colour.blue())), colour.alpha())
|
|
else:
|
|
part = 0.45 + 0.55 * (level * 2.0)
|
|
out.setRgb(*(int(round(c * part))
|
|
for c in (colour.red(), colour.green(),
|
|
colour.blue())), colour.alpha())
|
|
return out
|
|
|
|
def glow_line(painter, colour, width: float, draw, core=True,
|
|
dash=None) -> None:
|
|
"""Lay one line down two or three times, wider and fainter each pass.
|
|
|
|
A vector display holds a beam on the phosphor, and the phosphor
|
|
spreads the light and keeps glowing after the beam has moved on, so
|
|
a line on one of those screens is a bright core inside a halo. This
|
|
is that, done the only way a painter can do it cheaply: the halo
|
|
first, in a wide soft pen, and the core last on top of it.
|
|
|
|
``draw`` is handed a pen and asked to draw with it, so the same
|
|
thing works for a polyline, a rectangle or a leader. ``core=False``
|
|
lays down the halo alone, for a shape whose core wants drawing some
|
|
other way -- unsmoothed, or filled rather than stroked.
|
|
|
|
``dash`` is a pattern in pixels. Qt measures a dash pattern in pen
|
|
widths, so each pass divides the pattern by its own width: without
|
|
that, the halo's dashes would be three times the length of the
|
|
core's and the line would come out as beads rather than as a dashed
|
|
line.
|
|
"""
|
|
from .flightmap import THEME
|
|
|
|
def pen_for(colour, width):
|
|
pen = QPen(colour, width)
|
|
if dash:
|
|
pen.setDashPattern(dash_for(dash, width))
|
|
return pen
|
|
|
|
rings = THEME.glow
|
|
if rings:
|
|
part = THEME.glow_part
|
|
for ring in range(rings, 0, -1):
|
|
faint = QColor(colour)
|
|
faint.setAlpha(max(6, int(colour.alpha() * part ** ring)))
|
|
pen = pen_for(faint, width + ring * 2.4)
|
|
pen.setCapStyle(ROUND_CAP)
|
|
pen.setJoinStyle(ROUND_JOIN)
|
|
draw(pen)
|
|
if core:
|
|
draw(pen_for(colour, width))
|
|
|
|
class SkyView(QtWidgets.QWidget):
|
|
"""The map, the aircraft on it, and a box beside each one."""
|
|
|
|
def __init__(self, sky: Sky, parent=None):
|
|
super().__init__(parent)
|
|
self.sky = sky
|
|
self.detail = 2 # 2 full, 1 compact, 0 symbol only
|
|
self.trails = True
|
|
self.show_ground = True
|
|
self._ground_pixels = None # kept alive for the QImage
|
|
self._ground_ready = None # what those pixels were made from
|
|
# Where each aircraft's box is, and where it is going: kept as
|
|
# an offset from the symbol rather than a place on the screen,
|
|
# so that a box follows its aeroplane across the window without
|
|
# that counting as a move to be animated.
|
|
self._box_at: dict[str, tuple[float, float]] = {}
|
|
self._box_want: dict[str, tuple[int, int]] = {}
|
|
self._box_seen: set[str] = set()
|
|
self._box_moving = False
|
|
self._glide_at = 0.0
|
|
self._glide_step = 0.0
|
|
self._glide_timer = QTimer(self)
|
|
self._glide_timer.setSingleShot(True)
|
|
self._glide_timer.timeout.connect(self.update)
|
|
self.setMinimumSize(480, 360)
|
|
small = QFont()
|
|
small.setStyleHint(MONOSPACE)
|
|
small.setFamily("monospace")
|
|
small.setPointSize(8)
|
|
self.text_font = small
|
|
head = QFont(small)
|
|
head.setBold(True)
|
|
self.head_font = head
|
|
|
|
# -- geometry -----------------------------------------------------
|
|
def projection(self) -> Projection | None:
|
|
"""The piece of the world the window is showing."""
|
|
from .flightlog import box_around
|
|
|
|
middle = self.sky.centre()
|
|
if middle is None or self.sky.radius_nm <= 0:
|
|
# A radius of nothing is a box of nothing, and every pixel
|
|
# of the window then maps to the same point: the grid asks
|
|
# for a line every fraction of a degree across a span of
|
|
# zero, and the drawing dies rather than being unreadable.
|
|
# There is nothing to show, which is what None means here.
|
|
return None
|
|
south, west, north, east = box_around(middle[0], middle[1],
|
|
self.sky.radius_nm)
|
|
width, height = max(1, self.width()), max(1, self.height())
|
|
# The box is as tall as it is wide in miles; the window is not,
|
|
# so the shorter side decides the scale and the longer one shows
|
|
# more of the world than was asked for.
|
|
across = (east - west) * math.cos(math.radians(middle[0]))
|
|
down = north - south
|
|
if width / max(1e-9, across) < height / max(1e-9, down):
|
|
grow = (width / height) * down / max(1e-9, across)
|
|
middle_lon = (west + east) / 2
|
|
half = (east - west) * grow / 2
|
|
west, east = middle_lon - half, middle_lon + half
|
|
else:
|
|
grow = (height / width) * across / max(1e-9, down)
|
|
middle_lat = (south + north) / 2
|
|
half = (north - south) * grow / 2
|
|
south, north = middle_lat - half, middle_lat + half
|
|
return Projection(south=south, west=west, north=north, east=east,
|
|
left=0, top=0, width=width, height=height)
|
|
|
|
@staticmethod
|
|
def ground_box(view: Projection):
|
|
"""The piece of world to fetch: what is shown, and some around it."""
|
|
down = (view.north - view.south) * GROUND_MARGIN
|
|
across = (view.east - view.west) * GROUND_MARGIN
|
|
return (max(-85.0, view.south - down), view.west - across,
|
|
min(85.0, view.north + down), view.east + across)
|
|
|
|
def ground_key(self, view: Projection):
|
|
"""What the map underneath was fetched for, rounded so that a
|
|
pixel of drift does not throw it away."""
|
|
box = self.ground_box(view)
|
|
return (round(box[0], 2), round(box[1], 2), round(box[2], 2),
|
|
round(box[3], 2), view.width, view.height)
|
|
|
|
# -- painting -----------------------------------------------------
|
|
def paintEvent(self, event) -> None:
|
|
painter = QPainter(self)
|
|
painter.setRenderHint(ANTIALIAS, True)
|
|
painter.fillRect(self.rect(), rgb(BG))
|
|
view = self.projection()
|
|
if view is None:
|
|
self._draw_waiting(painter)
|
|
self._draw_header(painter, 0)
|
|
painter.end()
|
|
return
|
|
if self.show_ground:
|
|
self._draw_ground(painter, view)
|
|
self._draw_rings(painter, view)
|
|
self._draw_graticule(painter, view)
|
|
self._draw_airports(painter, view)
|
|
flying = self.sky.flying()
|
|
if self.trails:
|
|
for blip in flying:
|
|
self._draw_trail(painter, view, blip,
|
|
self.sky.strength(blip))
|
|
# The symbols go down first and their own space is spoken for,
|
|
# so that one aircraft's box cannot be placed on top of another
|
|
# aircraft -- which is the one thing on the picture that has to
|
|
# stay visible.
|
|
now = time.time()
|
|
# One step for every box on the picture, so that they all swing
|
|
# at the same rate whatever the frame took.
|
|
self._glide_step = (now - self._glide_at) if self._glide_at else 0.0
|
|
self._glide_at = now
|
|
self._box_seen = set()
|
|
self._box_moving = False
|
|
placed = [(blip, view.xy(blip.latitude, blip.longitude),
|
|
self.sky.strength(blip, now)) for blip in flying]
|
|
taken: list[tuple[int, int, int, int]] = []
|
|
for blip, (x, y), strength in placed:
|
|
colour = (rgb(blip.colour_index, _alpha(strength))
|
|
if blip.colour_index is not None
|
|
else craft_colour(blip.altitude_ft,
|
|
_alpha(strength)))
|
|
# The echo goes down before the aeroplane, so the ring
|
|
# passes under the thing that sent it out.
|
|
if strength >= 1.0:
|
|
self._draw_echo(painter, x, y, colour, blip.icao)
|
|
self._draw_symbol(painter, x, y, blip.track_deg, colour,
|
|
strength, blip.icao, blip.shape)
|
|
taken.append((x - 11, y - 11, 22, 22))
|
|
labels = [self._lay_out(blip, x, y, taken, strength)
|
|
for blip, (x, y), strength in placed]
|
|
# A box on its way somewhere is drawn last, over the ones that
|
|
# are standing still. It crosses its neighbours for a moment,
|
|
# and the one that is moving is the one the eye is following,
|
|
# so it is the one that has to stay readable while it does.
|
|
for laid in sorted((x for x in labels if x is not None),
|
|
key=lambda laid: laid[0]):
|
|
self._paint_label(painter, laid)
|
|
# The flag goes down after everything else and nothing is drawn
|
|
# after it: it says where the receiver is standing, which is the
|
|
# one thing on the picture that must never end up behind an
|
|
# aeroplane that happened to fly over it, or behind the box
|
|
# belonging to one.
|
|
self._draw_home(painter, view)
|
|
# An aircraft with no box this time -- gone, faded past reading,
|
|
# or the detail turned down -- is forgotten, so one that comes
|
|
# back is placed afresh instead of gliding in from wherever it
|
|
# was standing minutes ago.
|
|
for gone in set(self._box_at) - self._box_seen:
|
|
self._box_at.pop(gone, None)
|
|
self._box_want.pop(gone, None)
|
|
self._draw_scale(painter, view)
|
|
# Counted as overhead only while it is still being heard: one
|
|
# that has gone quiet is on the picture, fading, and saying it
|
|
# is overhead would be saying more than was heard.
|
|
self._draw_header(painter,
|
|
sum(1 for _b, _xy, s in placed if s >= 1.0))
|
|
painter.end()
|
|
# Only while something is actually moving: the rest of the time
|
|
# the ordinary five-a-second redraw is what runs.
|
|
# A pulse and an echo are never finished, so while either is
|
|
# on the window keeps asking for frames the way it does while a
|
|
# box is on its way somewhere.
|
|
alive = (self._box_moving
|
|
or ((self.sky.pulse > 0 or self.sky.echo > 0)
|
|
and any(s >= 1.0 for _b, _xy, s in placed)))
|
|
if alive and not self._glide_timer.isActive():
|
|
self._glide_timer.start(BOX_GLIDE_MS)
|
|
|
|
def _draw_waiting(self, painter) -> None:
|
|
painter.setFont(self.text_font)
|
|
painter.setPen(rgb(INK))
|
|
painter.drawText(self.rect(), _enum(Qt, "AlignmentFlag",
|
|
"AlignCenter"),
|
|
self.sky.waiting)
|
|
|
|
def _draw_ground(self, painter, view) -> None:
|
|
levels, box = self.sky.ground_covering(view.south, view.west,
|
|
view.north, view.east)
|
|
if levels is None:
|
|
# Ask for it and carry on drawing. The map arrives when it
|
|
# arrives; the aircraft are the part that cannot wait.
|
|
# Asked for at the size the bigger box needs to hold the
|
|
# same detail as the window, rather than at the window's
|
|
# own size: fetching a third more world into the same
|
|
# pixels and then cutting the middle out of it is how a
|
|
# sharp map ends up looking like a photograph of a map.
|
|
scale = 1.0 + 2.0 * GROUND_MARGIN
|
|
self.sky.want_ground(self.ground_key(view),
|
|
self.ground_box(view),
|
|
(int(view.width * scale),
|
|
int(view.height * scale)))
|
|
return
|
|
# Most of a map, with squares missing where tiles did not
|
|
# arrive. Drawn -- it is most of a map -- and asked for again,
|
|
# which is rate-limited inside and does nothing at all once the
|
|
# map is whole.
|
|
self.sky.reask_ground()
|
|
|
|
# And a map fetched for a smaller window is still a map of the
|
|
# right piece of world, so nothing above notices that it is now
|
|
# being stretched. A window opened at its default size and then
|
|
# taken to the whole screen used to keep the map it started with
|
|
# until an aircraft wandered far enough to move the view out of
|
|
# the fetched box, which on a quiet band is a long time to look
|
|
# at a blurred coastline.
|
|
if self._stretched(levels, box, view):
|
|
scale = 1.0 + 2.0 * GROUND_MARGIN
|
|
self.sky.want_ground(self.ground_key(view),
|
|
self.ground_box(view),
|
|
(int(view.width * scale),
|
|
int(view.height * scale)))
|
|
# Cutting the view out of the fetched map, dimming it and
|
|
# looking every level up in the palette is about seventy
|
|
# milliseconds over two megapixels, and none of it changes
|
|
# between one frame and the next unless the view, the window,
|
|
# the brightness or the map itself has. Doing it every frame
|
|
# put a ceiling of a dozen frames a second on the window and
|
|
# spent a whole core holding it there.
|
|
key = (self.sky.ground_serial(), self.sky.brightness,
|
|
view.south, view.west, view.north, view.east,
|
|
view.width, view.height)
|
|
if key != getattr(self, "_ground_ready", None):
|
|
from .flightmap import dim_ground
|
|
|
|
shades = dim_ground(self._crop(levels, box, view),
|
|
self.sky.brightness)
|
|
self._ground_pixels = np.ascontiguousarray(
|
|
PALETTE[GROUND + shades].astype(np.uint8))
|
|
self._ground_ready = key
|
|
pixels = self._ground_pixels # QImage does not copy it
|
|
height, width = pixels.shape[0], pixels.shape[1]
|
|
image = QImage(pixels.data, width, height, 3 * width, RGB888)
|
|
painter.drawImage(0, 0, image)
|
|
|
|
@staticmethod
|
|
def _stretched(levels, box, view: Projection) -> bool:
|
|
"""Whether the map in hand is being blown up to fill the window.
|
|
|
|
Measured as pixels of map per degree of world, in hand against
|
|
wanted, which is the thing that actually shows: a map fetched
|
|
for eleven hundred pixels across and drawn across nineteen
|
|
hundred is the same map with each of its pixels covering nearly
|
|
two.
|
|
|
|
Saying yes here cannot loop. The request that follows is keyed
|
|
on the window's size, so once it has been answered the key
|
|
matches and nothing more is asked -- which is what stops a
|
|
window bigger than the tile budget can cover from asking
|
|
forever. At that size the map is enlarged by design, and the
|
|
readme has always said so.
|
|
"""
|
|
if levels is None or box is None or view.width < 1:
|
|
return False
|
|
across = box[3] - box[1]
|
|
shown = view.east - view.west
|
|
if across <= 0 or shown <= 0:
|
|
return False
|
|
have = levels.shape[1] / across
|
|
want = view.width / shown
|
|
return want > have * (1.0 + GROUND_STRETCH)
|
|
|
|
@staticmethod
|
|
def _crop(levels, box, view: Projection):
|
|
"""The part of the fetched map this view is looking at.
|
|
|
|
Both are laid out the same way -- latitude down, longitude across,
|
|
evenly -- so this is arithmetic rather than another projection.
|
|
"""
|
|
south, west, north, east = box
|
|
rows, columns = levels.shape[0], levels.shape[1]
|
|
lats = np.linspace(view.north, view.south, view.height)
|
|
lons = np.linspace(view.west, view.east, view.width)
|
|
y = np.clip(((north - lats) / max(1e-9, north - south)
|
|
* (rows - 1)).round().astype(np.int64), 0, rows - 1)
|
|
x = np.clip(((lons - west) / max(1e-9, east - west)
|
|
* (columns - 1)).round().astype(np.int64),
|
|
0, columns - 1)
|
|
return np.clip(levels[y[:, None], x[None, :]], 0,
|
|
GROUND_SHADES - 1)
|
|
|
|
def _draw_graticule(self, painter, view) -> None:
|
|
pen = QPen(rgb(GRID))
|
|
pen.setStyle(DOTTED)
|
|
painter.setPen(pen)
|
|
painter.setFont(self.text_font)
|
|
step = _grid_step(view.north - view.south)
|
|
lat = math.ceil(view.south / step) * step
|
|
while lat <= view.north:
|
|
_, y = view.xy(lat, view.west)
|
|
painter.drawLine(0, y, self.width(), y)
|
|
lat += step
|
|
step = _grid_step(view.east - view.west)
|
|
lon = math.ceil(view.west / step) * step
|
|
while lon <= view.east:
|
|
x, _ = view.xy(view.south, lon)
|
|
painter.drawLine(x, 0, x, self.height())
|
|
lon += step
|
|
painter.setPen(rgb(GRID))
|
|
step = _grid_step(view.north - view.south)
|
|
lat = math.ceil(view.south / step) * step
|
|
while lat <= view.north:
|
|
_, y = view.xy(lat, view.west)
|
|
painter.drawText(4, y - 3, _degrees(lat, "lat"))
|
|
lat += step
|
|
step = _grid_step(view.east - view.west)
|
|
lon = math.ceil(view.west / step) * step
|
|
while lon <= view.east:
|
|
x, _ = view.xy(view.south, lon)
|
|
painter.drawText(x + 3, self.height() - 24,
|
|
_degrees(lon, "lon"))
|
|
lon += step
|
|
|
|
def _draw_airports(self, painter, view) -> None:
|
|
"""Every aerodrome under the view, marked and named.
|
|
|
|
A route names the two airports its aircraft are flying between,
|
|
and those are almost never the ones underneath: a receiver hears
|
|
aircraft over its own county, and the county's airports are what
|
|
say where on the map you are looking.
|
|
|
|
Drawn under the aircraft and before them, since an aeroplane is
|
|
what the window is for and an airport is where it is.
|
|
"""
|
|
if not self.sky.show_airports:
|
|
return
|
|
found = self.sky.airports_covering(view.south, view.west,
|
|
view.north, view.east)
|
|
if found is None:
|
|
# Ask for them and carry on drawing. They arrive when they
|
|
# arrive; the aircraft are the part that cannot wait.
|
|
self.sky.want_airports(self.ground_box(view))
|
|
return
|
|
if not found:
|
|
return
|
|
from .flightmap import THEME
|
|
|
|
colour = rgb(AIRPORT)
|
|
glowing = bool(THEME.glow)
|
|
painter.setFont(self.text_font)
|
|
for code, lat, lon in found:
|
|
# Skipped rather than drawn and clipped. What is fetched
|
|
# covers rather more world than is shown, so on a zoomed-in
|
|
# view most of the county's airports are outside it, and
|
|
# they are not worth a draw call each to have Qt throw away.
|
|
if not view.inside(lat, lon):
|
|
continue
|
|
x, y = view.xy(lat, lon)
|
|
# The square goes down unsmoothed. It is six pixels on a
|
|
# side and axis-aligned, so antialiasing it only spreads a
|
|
# one-pixel line across two and leaves the mark looking out
|
|
# of focus next to the crisp aircraft beside it. The name
|
|
# keeps its smoothing, which is what letters want.
|
|
def square(pen):
|
|
painter.setPen(pen)
|
|
painter.setBrush(_NO_BRUSH)
|
|
painter.drawRect(x - 3, y - 3, 6, 6)
|
|
|
|
# The halo wants smoothing and the square does not. It is
|
|
# six pixels on a side and axis-aligned, so antialiasing the
|
|
# square itself only spreads a one-pixel line across two and
|
|
# leaves the mark looking out of focus beside the crisp
|
|
# aircraft; the glow round it is all curve and needs it.
|
|
if glowing:
|
|
glow_line(painter, colour, 1.0, square, core=False)
|
|
painter.setRenderHint(ANTIALIAS, False)
|
|
square(QPen(colour, 1.0))
|
|
painter.fillRect(x - 1, y - 1, 2, 2, colour)
|
|
painter.setRenderHint(ANTIALIAS, True)
|
|
if code:
|
|
painter.drawText(x + 7, y + 4, code)
|
|
|
|
def _draw_rings(self, painter, view) -> None:
|
|
"""Filled discs at a quarter, a half and three quarters of the
|
|
radius, concentric on the receiver.
|
|
|
|
Translucent and stacked, so the ground inside the innermost is
|
|
lifted three times and the outermost once. What that gives is a
|
|
sense of how far away a thing is without measuring anything: an
|
|
aircraft two shades in is about halfway to the edge of what this
|
|
receiver hears.
|
|
"""
|
|
from .flightmap import RING_STEPS, ring_labels
|
|
|
|
home = self.sky.home
|
|
radius = self.sky.radius_nm
|
|
if not self.sky.show_rings or home is None or radius <= 0:
|
|
return
|
|
from .flightlog import move
|
|
|
|
tint = rgb(GROUND + GROUND_SHADES - 1, 22)
|
|
painter.setPen(NO_PEN)
|
|
painter.setBrush(tint)
|
|
middle = QPointF(*view.xy(home[0], home[1]))
|
|
painter.setFont(self.text_font)
|
|
for part in sorted(RING_STEPS, reverse=True):
|
|
nm = radius * part
|
|
north = view.xy(*move(home[0], home[1], 0.0, nm))
|
|
east = view.xy(*move(home[0], home[1], 90.0, nm))
|
|
across = abs(east[0] - middle.x())
|
|
down = abs(north[1] - middle.y())
|
|
if across < 2 or down < 2:
|
|
continue
|
|
painter.setPen(NO_PEN)
|
|
painter.setBrush(tint)
|
|
painter.drawEllipse(middle, across, down)
|
|
for nm, text in ring_labels(radius, self.sky.unit):
|
|
north = view.xy(*move(home[0], home[1], 0.0, nm))
|
|
if not (0 <= north[0] < self.width()
|
|
and 0 <= north[1] < self.height()):
|
|
continue
|
|
wide = QtGui.QFontMetrics(self.text_font).horizontalAdvance(text)
|
|
painter.setPen(rgb(DIM))
|
|
painter.drawText(int(north[0] - wide / 2),
|
|
int(north[1]) + 12, text)
|
|
|
|
def _draw_home(self, painter, view) -> None:
|
|
"""A flag on the spot the receiver was told it is standing on.
|
|
|
|
Only where it was actually told. The middle of the picture is
|
|
otherwise worked out from whatever flew past, which is not a
|
|
place anybody is standing, and a flag on it would say somebody
|
|
is.
|
|
|
|
The foot of the pole is the position and the pennant flies up
|
|
and to the right of it, so that nothing the flag is made of
|
|
covers the place it points at.
|
|
"""
|
|
from .flightmap import HOME_DROP, HOME_FLY, HOME_POLE
|
|
|
|
home = self.sky.home
|
|
if home is None or not view.inside(home[0], home[1]):
|
|
return
|
|
x, y = view.xy(home[0], home[1])
|
|
colour = rgb(HOME)
|
|
top = y - HOME_POLE
|
|
|
|
def pole(pen):
|
|
painter.setPen(pen)
|
|
painter.drawLine(x, y, x, top)
|
|
|
|
glow_line(painter, colour, 2.0, pole)
|
|
pennant = QPolygonF([QPointF(x + 1, top),
|
|
QPointF(x + 1 + HOME_FLY, top),
|
|
QPointF(x + 1, top + HOME_DROP)])
|
|
|
|
def outline(pen):
|
|
painter.setPen(pen)
|
|
painter.setBrush(_NO_BRUSH)
|
|
painter.drawPolygon(pennant)
|
|
|
|
glow_line(painter, colour, 0.1, outline, core=False)
|
|
painter.setPen(NO_PEN)
|
|
painter.setBrush(colour)
|
|
painter.drawPolygon(pennant)
|
|
|
|
def _draw_trail(self, painter, view, blip: Blip,
|
|
strength: float = 1.0) -> None:
|
|
points = self.sky.trail(blip.icao)
|
|
if len(points) < 2:
|
|
return
|
|
path = QPolygonF([QPointF(*view.xy(lat, lon))
|
|
for lat, lon, _ in points])
|
|
|
|
def stroke(pen):
|
|
painter.setPen(pen)
|
|
painter.drawPolyline(path)
|
|
|
|
glow_line(painter, craft_colour(blip.altitude_ft,
|
|
int(90 * strength)), 1.4, stroke)
|
|
|
|
def _lay_out(self, blip: Blip, x, y, taken, strength: float = 1.0):
|
|
"""Where this aircraft's box goes, and what is in it.
|
|
|
|
Kept apart from the painting so that every box's place is
|
|
decided before any of them is drawn, which is what lets the
|
|
ones in motion go down last.
|
|
"""
|
|
# A box at a tenth of its colour is not information, it is
|
|
# something in the way of the aircraft still flying.
|
|
if self.detail <= 0 or strength < LABEL_WHILE:
|
|
return None
|
|
lines = self._wrapped(self._box_lines(blip))
|
|
box = self._box_size(lines)
|
|
bx, by = self._box_spot(blip.icao, x, y, box, taken)
|
|
# The settled place is what is spoken for, not the place the box
|
|
# happens to have reached: laying out against a box in mid-swing
|
|
# would move every box near it as well, and they would move
|
|
# again when it arrived. A glide crosses its neighbours for a
|
|
# moment; a whole screen rearranging itself twice does not
|
|
# settle at all.
|
|
taken.append((bx, by, box[0], box[1]))
|
|
dx, dy = self._box_drawn(blip.icao, x, y, (bx, by))
|
|
return ((dx, dy) != (bx, by), blip, x, y, dx, dy, box, lines,
|
|
strength)
|
|
|
|
def _paint_label(self, painter, laid) -> None:
|
|
_moving, blip, x, y, dx, dy, box, lines, strength = laid
|
|
colour = craft_colour(blip.altitude_ft, _alpha(strength))
|
|
# To the near edge of the box rather than its middle: a leader
|
|
# drawn to the centre crosses the box and strikes out a line of
|
|
# what it was drawn to point at.
|
|
to_x = int(max(dx, min(x, dx + box[0])))
|
|
to_y = int(max(dy, min(y, dy + box[1])))
|
|
|
|
def leader(pen):
|
|
painter.setPen(pen)
|
|
painter.drawLine(x, y, to_x, to_y)
|
|
|
|
# Its own colour, and dashed: neither of which it used to be.
|
|
# Drawn in the aircraft's own colour it came out the same colour
|
|
# as that aircraft's trail, and a straight solid line running
|
|
# out of an aeroplane in the colour of the path behind the
|
|
# aeroplane reads as more path -- a heading nobody flew.
|
|
glow_line(painter, rgb(LEADER, _alpha(strength)), 1.0, leader,
|
|
dash=LEADER_DASH)
|
|
title = f"{blip.callsign} {blip.icao}" if blip.callsign \
|
|
else blip.icao
|
|
self._draw_box(painter, dx, dy, box, lines, colour, title)
|
|
|
|
def _box_spot(self, icao: str, x: int, y: int, box, taken):
|
|
"""Where this aircraft's box belongs, once everything settles.
|
|
|
|
The spot it already had is kept for as long as it still works,
|
|
which is what stops a box hopping about because the aeroplane
|
|
two along moved a pixel. It is remembered as an offset, so an
|
|
aircraft crossing the window carries its box with it and only a
|
|
genuine clash asks for a new place.
|
|
"""
|
|
bounds = (2, self._header_height() + 2,
|
|
self.width() - 2, self.height() - 26)
|
|
left, top, right, bottom = bounds
|
|
want = self._box_want.get(icao)
|
|
if want is not None:
|
|
bx = max(left, min(int(x + want[0]), right - box[0]))
|
|
by = max(top, min(int(y + want[1]), bottom - box[1]))
|
|
if _clear(bx, by, box[0], box[1], taken):
|
|
self._box_want[icao] = (bx - x, by - y)
|
|
return bx, by
|
|
bx, by = place_box(x, y, box[0], box[1], taken, bounds)
|
|
self._box_want[icao] = (bx - x, by - y)
|
|
return bx, by
|
|
|
|
def _box_drawn(self, icao: str, x: int, y: int, want):
|
|
"""Where to draw the box this frame, on its way to `want`."""
|
|
self._box_seen.add(icao)
|
|
target = (want[0] - x, want[1] - y)
|
|
here = self._box_at.get(icao)
|
|
if here is None: # first sight: no swing to make
|
|
self._box_at[icao] = (float(target[0]), float(target[1]))
|
|
return want
|
|
here = glide(here, target, self._glide_step)
|
|
self._box_at[icao] = here
|
|
if here != (float(target[0]), float(target[1])):
|
|
self._box_moving = True
|
|
return int(round(x + here[0])), int(round(y + here[1]))
|
|
|
|
def _draw_echo(self, painter, x, y, colour, icao: str) -> None:
|
|
"""One ring travelling outward from an aircraft, dimming as it
|
|
grows. What a radar repeater does, and what the eye reads as
|
|
"this thing is transmitting" -- which is what an aeroplane on
|
|
this picture is doing, twice a second."""
|
|
from .flightmap import echo_age, phase_of
|
|
|
|
every = self.sky.echo
|
|
reach = self.sky.echo_reach
|
|
if every <= 0 or reach <= 0:
|
|
return
|
|
age = echo_age(time.time() - self.sky.started, every,
|
|
phase_of(icao))
|
|
part = age / max(1e-9, every)
|
|
radius = reach * part
|
|
if radius < 2:
|
|
return
|
|
ring = QColor(colour)
|
|
# Dimmer the further out it has got, and gone by the time it
|
|
# arrives: a ring that vanished at full strength would read as
|
|
# something switching off rather than something spending itself.
|
|
ring.setAlpha(int(colour.alpha() * (1.0 - part) ** 1.6 * 0.75))
|
|
painter.setPen(QPen(ring, 1.2))
|
|
painter.setBrush(_NO_BRUSH)
|
|
painter.drawEllipse(QPointF(x, y), radius, radius)
|
|
|
|
def _pulse_level(self, icao: str):
|
|
"""How far up its pulse this aircraft is, or None for no pulse.
|
|
|
|
Each aeroplane is offset by its own address, so a sky full of
|
|
them swells and fades separately rather than beating as one --
|
|
which reads as a display flashing rather than as a lot of
|
|
separate things transmitting.
|
|
"""
|
|
from .flightmap import phase_of, pulse_at
|
|
|
|
if self.sky.pulse <= 0:
|
|
return None
|
|
return pulse_at(time.time() - self.sky.started, self.sky.pulse,
|
|
phase_of(icao))
|
|
|
|
def _draw_symbol(self, painter, x, y, heading, colour,
|
|
strength: float = 1.0, icao: str = "",
|
|
shape: str = "aircraft") -> None:
|
|
angle = math.radians(heading % 360.0)
|
|
sin, cos = math.sin(angle), math.cos(angle)
|
|
|
|
def point(ahead, side):
|
|
return QPointF(x + side * cos + ahead * sin,
|
|
y + side * sin - ahead * cos)
|
|
|
|
level = self._pulse_level(icao) if strength >= 1.0 else None
|
|
if level is not None:
|
|
# A painter can blend, so the swell here is continuous
|
|
# rather than the handful of steps an indexed picture is
|
|
# held to: the colour walks from dim towards white and the
|
|
# halo widens with it, which is a beam sitting in one place
|
|
# a little too long.
|
|
colour = _lifted(colour, level)
|
|
if shape == "aircraft":
|
|
outline_of = QPolygonF([point(9, 0), point(-6, 5),
|
|
point(-3, 0), point(-6, -5)])
|
|
elif shape == "vehicle":
|
|
# A thing going somewhere that is not an aeroplane: a body
|
|
# with a stalk, so the direction reads without the mark
|
|
# claiming to be flying.
|
|
outline_of = QPolygonF([point(8, 0), point(1, 4),
|
|
point(-5, 3), point(-5, -3),
|
|
point(1, -4)])
|
|
else:
|
|
# Somewhere rather than something: a diamond, which is the
|
|
# one shape on this picture that has no front.
|
|
outline_of = QPolygonF([point(0, 6), point(6, 0),
|
|
point(0, -6), point(-6, 0)])
|
|
# The halo is stroked round the outline rather than filled, so
|
|
# that it spreads outwards from the symbol instead of merely
|
|
# making it bigger.
|
|
from .flightmap import THEME
|
|
|
|
burn = 0.0 if level is None else max(0.0, level - 0.25) * 5.0
|
|
if THEME.glow or burn > 0:
|
|
def outline(pen):
|
|
painter.setPen(pen)
|
|
painter.setBrush(_NO_BRUSH)
|
|
painter.drawPolygon(outline_of)
|
|
|
|
if burn > 0:
|
|
# The raster burn: the shape itself, laid down wide and
|
|
# faint under the aeroplane rather than a circle drawn
|
|
# round it, so the glow has the shape of the thing
|
|
# casting it.
|
|
for ring in (2.0, 1.0):
|
|
halo = QColor(colour)
|
|
halo.setAlpha(int(min(150, 60 * burn) / ring))
|
|
pen = QPen(halo, burn * 2.2 * ring)
|
|
pen.setJoinStyle(ROUND_JOIN)
|
|
pen.setCapStyle(ROUND_CAP)
|
|
outline(pen)
|
|
if THEME.glow:
|
|
glow_line(painter, colour, 0.1, outline, core=False)
|
|
painter.setPen(NO_PEN)
|
|
painter.setBrush(colour)
|
|
painter.drawPolygon(outline_of)
|
|
painter.setBrush(QColor(255, 255, 255, int(200 * strength)))
|
|
painter.drawEllipse(QPointF(x, y), 1.6, 1.6)
|
|
|
|
def _box_lines(self, blip: Blip) -> list[tuple[str, str]]:
|
|
if self.detail >= 2:
|
|
return blip.lines(self.sky.unit, self.sky.centre())
|
|
out = []
|
|
if blip.altitude_ft:
|
|
out.append(("alt", f"{blip.altitude_ft:,} ft", ""))
|
|
if blip.ground_speed_kt:
|
|
out.append(("gs", f"{in_speed(blip.ground_speed_kt, self.sky.unit):.0f}"
|
|
f" {speed_label(self.sky.unit)}", ""))
|
|
return out
|
|
|
|
@staticmethod
|
|
def _wrapped(lines) -> list[tuple[str, str, str]]:
|
|
"""The box's rows, with the long ones folded.
|
|
|
|
A folded row carries neither the label nor the flag: both belong
|
|
to the value as a whole, and repeating them down the side of a
|
|
wrapped airport name would read as several different facts.
|
|
"""
|
|
out: list[tuple[str, str, str]] = []
|
|
for row in lines:
|
|
label, value, country = (row if len(row) == 3
|
|
else (row[0], row[1], ""))
|
|
for i, piece in enumerate(wrap_value(value)):
|
|
out.append((label if i == 0 else "", piece,
|
|
country if i == 0 else ""))
|
|
return out
|
|
|
|
def _box_size(self, lines) -> tuple[int, int]:
|
|
from .flags import FLAG_W
|
|
|
|
metrics = QtGui.QFontMetrics(self.text_font)
|
|
head = QtGui.QFontMetrics(self.head_font)
|
|
widest = head.horizontalAdvance("XXXXXXXX XXXXXX")
|
|
flagged = any(country for _, _, country in lines)
|
|
for _label, value, _country in lines:
|
|
widest = max(widest, metrics.horizontalAdvance(value))
|
|
gutter = metrics.horizontalAdvance("XXXXX ")
|
|
room = gutter + widest + (FLAG_W + 4 if flagged else 0)
|
|
row = metrics.height()
|
|
return room + 14, head.height() + row * len(lines) + 12
|
|
|
|
def _draw_box(self, painter, bx, by, box, lines, colour,
|
|
title: str) -> None:
|
|
width, height = box
|
|
shape = QRectF(bx, by, width, height)
|
|
# The panel colour, from the theme, so a box on a phosphor
|
|
# screen is the black of the tube rather than a blue-grey card.
|
|
# As solid as the setting asks for, and no more solid than the
|
|
# label it is behind: a card at full strength under a label that
|
|
# is fading out would be the brightest thing left of it.
|
|
back = rgb(PANEL, int(255 * self.sky.box_opacity
|
|
* (colour.alpha() / 255)))
|
|
painter.setBrush(back)
|
|
painter.setPen(QPen(colour, 1.2))
|
|
painter.drawRoundedRect(shape, 3.0, 3.0)
|
|
|
|
def outline(pen):
|
|
painter.setPen(pen)
|
|
painter.setBrush(_NO_BRUSH)
|
|
painter.drawRoundedRect(shape, 3.0, 3.0)
|
|
|
|
glow_line(painter, colour, 1.2, outline)
|
|
painter.setFont(self.head_font)
|
|
faded = colour.alpha()
|
|
painter.setPen(colour.lighter(135))
|
|
head = QtGui.QFontMetrics(self.head_font)
|
|
painter.drawText(bx + 7, by + head.ascent() + 4, title)
|
|
painter.setFont(self.text_font)
|
|
metrics = QtGui.QFontMetrics(self.text_font)
|
|
gutter = metrics.horizontalAdvance("XXXXX ")
|
|
flagged = any(country for _, _, country in lines)
|
|
y = by + head.height() + 6 + metrics.ascent()
|
|
for label, value, country in lines:
|
|
if label:
|
|
painter.setPen(rgb(GRID, faded))
|
|
painter.drawText(bx + 7, y, f"{label:>5s}")
|
|
left = bx + 7 + gutter
|
|
if flagged:
|
|
if country:
|
|
self._draw_flag(painter, left, y - metrics.ascent() + 2,
|
|
country)
|
|
left += FLAG_PIXELS + 4
|
|
painter.setPen(rgb(INK, faded))
|
|
painter.drawText(left, y, value)
|
|
y += metrics.height()
|
|
|
|
def _draw_flag(self, painter, x: int, y: int, country: str) -> None:
|
|
"""A flag beside a place name, or its letters where there is none.
|
|
|
|
A country with no flag here is named rather than approximated: two
|
|
letters are never wrong, and a flag that is nearly another
|
|
country's is worse than no flag at all.
|
|
"""
|
|
from .flags import FLAG_H, FLAG_W, pixels_for
|
|
|
|
picture = pixels_for(country)
|
|
if picture is None:
|
|
painter.setPen(rgb(GRID))
|
|
painter.drawText(x, y + FLAG_H, country[:2].upper())
|
|
return
|
|
pixels = np.ascontiguousarray(picture)
|
|
self._flag_pixels = pixels # QImage does not copy it
|
|
image = QImage(pixels.data, FLAG_W, FLAG_H, 3 * FLAG_W, RGB888)
|
|
painter.drawImage(x, y, image)
|
|
|
|
def _draw_scale(self, painter, view) -> None:
|
|
from .basemap import ATTRIBUTION
|
|
|
|
painter.setFont(self.text_font)
|
|
metrics = QtGui.QFontMetrics(self.text_font)
|
|
across = in_distance(view.width_nm, self.sky.unit)
|
|
per = self.width() / max(1e-9, across)
|
|
for miles in (200, 100, 50, 20, 10, 5, 2, 1):
|
|
pixels = int(miles * per)
|
|
if pixels <= self.width() * 0.28:
|
|
break
|
|
else:
|
|
return
|
|
y = self.height() - 10
|
|
painter.setPen(QPen(rgb(INK), 1.0))
|
|
painter.drawLine(12, y, 12 + pixels, y)
|
|
painter.drawLine(12, y - 4, 12, y + 4)
|
|
painter.drawLine(12 + pixels, y - 4, 12 + pixels, y + 4)
|
|
painter.drawText(18 + pixels, y + 4,
|
|
f"{miles} {distance_label(self.sky.unit)}")
|
|
if self.show_ground and self.sky.ground_covering(
|
|
view.south, view.west, view.north, view.east)[0] is not None:
|
|
painter.setPen(rgb(GRID))
|
|
painter.drawText(self.width() - 8
|
|
- metrics.horizontalAdvance(ATTRIBUTION),
|
|
y + 4, ATTRIBUTION)
|
|
|
|
def _header_height(self) -> int:
|
|
return QtGui.QFontMetrics(self.head_font).height() + 8
|
|
|
|
def _draw_header(self, painter, flying: int) -> None:
|
|
metrics = QtGui.QFontMetrics(self.head_font)
|
|
height = self._header_height()
|
|
painter.setPen(NO_PEN)
|
|
painter.setBrush(QColor(10, 12, 18, 205))
|
|
painter.drawRect(0, 0, self.width(), height)
|
|
elapsed = max(0.001, time.time() - self.sky.started)
|
|
told = (f"{self.sky.channel} {flying} {self.sky.subject} "
|
|
f"{self.sky.aircraft_seen} seen "
|
|
f"{self.sky.frames:,} {self.sky.counted} "
|
|
f"{self.sky.frames / elapsed:.0f}/s "
|
|
f"{_clock(elapsed)}")
|
|
if self.sky.log_name:
|
|
told += f" {self.sky.log_name}"
|
|
if self.sky.note:
|
|
told += f" {self.sky.note}"
|
|
painter.setFont(self.head_font)
|
|
painter.setPen(rgb(INK))
|
|
painter.drawText(10, metrics.ascent() + 4, told)
|
|
keys = ("d detail t trails g map f full [ ] bright "
|
|
"+/- range q quit")
|
|
painter.setPen(rgb(GRID))
|
|
painter.drawText(self.width() - 8
|
|
- metrics.horizontalAdvance(keys),
|
|
metrics.ascent() + 4, keys)
|
|
|
|
class Window(QtWidgets.QMainWindow):
|
|
"""The window itself: a map, a clock and a few keys."""
|
|
|
|
def __init__(self, sky: Sky, title: str = "bandsaunter — aircraft"):
|
|
super().__init__()
|
|
self.sky = sky
|
|
self.view = SkyView(sky, self)
|
|
self.setCentralWidget(self.view)
|
|
self.setWindowTitle(title)
|
|
# The size to come back to when the window is un-maximised, set
|
|
# before maximising so that there is one.
|
|
self.resize(1100, 800)
|
|
# Maximised rather than a fixed size: this is a map, and the
|
|
# thing somebody wants more of is map. Maximised rather than
|
|
# true full screen, because the title bar is where the band and
|
|
# the frequency are written, and a window with no frame is one
|
|
# somebody has to know a key to get out of -- f is that key,
|
|
# for anybody who wants the last few rows as well.
|
|
self.showMaximized()
|
|
self._timer = QTimer(self)
|
|
self._timer.timeout.connect(self._tick)
|
|
self._timer.start(REDRAW_MS)
|
|
|
|
def _tick(self) -> None:
|
|
if self.sky.finished:
|
|
self.close()
|
|
return
|
|
self.view.update()
|
|
|
|
def keyPressEvent(self, event) -> None:
|
|
key = event.key()
|
|
text = event.text().lower()
|
|
if key in (KEY_Q, KEY_ESCAPE) or text == "q":
|
|
self.close()
|
|
elif text == "d":
|
|
self.view.detail = (self.view.detail + 2) % 3
|
|
elif text == "t":
|
|
self.view.trails = not self.view.trails
|
|
elif text == "g":
|
|
self.view.show_ground = not self.view.show_ground
|
|
elif text == "f":
|
|
# Back to maximised rather than to the small size it was
|
|
# built at: leaving full screen should not shrink the map to
|
|
# a quarter of the screen.
|
|
if self.isFullScreen():
|
|
self.showMaximized()
|
|
else:
|
|
self.showFullScreen()
|
|
elif text in ("+", "="):
|
|
self.sky.radius_nm = max(5.0, self.sky.radius_nm / 1.5)
|
|
elif text == "-":
|
|
self.sky.radius_nm = min(3000.0, self.sky.radius_nm * 1.5)
|
|
elif text == "[":
|
|
self.sky.brightness = max(0.1, self.sky.brightness - 0.1)
|
|
elif text == "]":
|
|
self.sky.brightness = min(1.0, self.sky.brightness + 0.1)
|
|
self.view.update()
|
|
|
|
def closeEvent(self, event) -> None:
|
|
self.sky.stopping = True
|
|
self._timer.stop()
|
|
event.accept()
|
|
|
|
_build._made = {"SkyView": SkyView, "Window": Window}
|
|
return _build._made
|
|
|
|
|
|
def _clock(seconds: float) -> str:
|
|
seconds = int(seconds)
|
|
hours, rest = divmod(seconds, 3600)
|
|
minutes, secs = divmod(rest, 60)
|
|
return f"{hours}:{minutes:02d}:{secs:02d}" if hours else f"{minutes}:{secs:02d}"
|
|
|
|
|
|
def __getattr__(name):
|
|
"""Build the window classes on first use, so importing costs nothing."""
|
|
if name in ("SkyView", "Window"):
|
|
made = _build()
|
|
if made is None:
|
|
raise RuntimeError(MISSING_QT)
|
|
return made[name]
|
|
raise AttributeError(name)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Running it
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def fetch_ground(sky: Sky, url: str = "", fetch=None) -> None:
|
|
"""Fetch whatever map the window is asking for, until it stops asking.
|
|
|
|
Runs on its own thread: the tiles come off a network the first time an
|
|
area is drawn, and a window that stopped repainting while that happened
|
|
would look broken every time it was resized.
|
|
"""
|
|
from . import basemap
|
|
|
|
while not sky.stopping:
|
|
# The aerodromes first, and on their own account. They used to be
|
|
# fetched only in the same pass as a piece of map, which meant they
|
|
# waited behind a hundred and twenty tiles coming off a network --
|
|
# and once the map was in hand there were no more passes, so they
|
|
# were never fetched again. They are one small question and they
|
|
# have nothing to do with the tiles.
|
|
_airports(sky)
|
|
wanted = sky.wanted_ground()
|
|
if wanted is None:
|
|
time.sleep(0.2)
|
|
continue
|
|
key, box, (width, height) = wanted
|
|
south, west, north, east = box
|
|
try:
|
|
extra = {"fetch": fetch} if fetch is not None else {}
|
|
if url:
|
|
extra["url"] = url
|
|
# The size asked for is the box's own, not the window's, so the
|
|
# piece of it the window shows comes out pixel for pixel with
|
|
# the screen. Rendering the wider box into the window's pixels
|
|
# and stretching it back was a whole-map upscale of a fifth,
|
|
# which is what a sharp map looks like when it looks blurred.
|
|
levels, settled = basemap.ground_under(
|
|
south, west, north, east, width, height,
|
|
shades=_ground_shades(), **extra)
|
|
except Exception:
|
|
levels, settled = None, True
|
|
# Remembered either way: a map that could not be fetched must not be
|
|
# asked for again every fifth of a second for the rest of the night.
|
|
# A map that came back with squares missing is remembered too -- it
|
|
# is most of a map and it gets drawn -- but not as the last word,
|
|
# so the window can ask for the rest of it in a moment.
|
|
sky.set_ground(levels, key, box if levels is not None else None,
|
|
settled=settled)
|
|
|
|
|
|
def _airports(sky: Sky) -> None:
|
|
"""Fetch the aerodromes the window is asking for, if it is asking.
|
|
|
|
On the fetching thread, for the same reason the tiles are: it is a
|
|
question to a network the first time an area is drawn, and the window
|
|
must not stop repainting while it is asked. Cached on disk for a month
|
|
afterwards, since a runway does not move.
|
|
"""
|
|
from . import basemap
|
|
|
|
box = sky.wanted_airports()
|
|
if box is None or not sky.show_airports:
|
|
return
|
|
try:
|
|
found = [(a["code"], a["latitude"], a["longitude"])
|
|
for a in basemap.airports_in(*box)]
|
|
except Exception:
|
|
# Kept as nothing rather than left unanswered: an area that could
|
|
# not be asked about must not be asked about again every fifth of a
|
|
# second for the rest of the night.
|
|
found = []
|
|
sky.set_airports(found, box)
|
|
|
|
|
|
def _ground_shades() -> int:
|
|
from .flightmap import GROUND_SHADES
|
|
|
|
return GROUND_SHADES
|
|
|
|
|
|
def show(sky: Sky, title: str = "bandsaunter — aircraft") -> None:
|
|
"""Open the window and stay in it until it is closed."""
|
|
made = _build()
|
|
if made is None:
|
|
raise RuntimeError(MISSING_QT)
|
|
_name, _core, _gui, widgets, _signal = _qt()
|
|
app = widgets.QApplication.instance() or widgets.QApplication([])
|
|
window = made["Window"](sky, title)
|
|
window.show()
|
|
runner = getattr(app, "exec", None) or app.exec_
|
|
runner()
|
|
sky.stopping = True
|