Repository navigation
Expand file tree
/
Copy pathui.py
More file actions
573 lines (467 loc) · 19.7 KB
/
Copy pathui.py
File metadata and controls
573 lines (467 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import math
import sys
import pygame
# Colors as RGB tuples (converted from CircuitPython 0xRRGGBB)
BACKGROUND = ( 7, 19, 31)
SKY_BAND = ( 14, 34, 49)
CARD = ( 16, 39, 57)
CARD_ALT = ( 12, 30, 45)
ACCENT = ( 45, 181, 163)
ACCENT_DIM = ( 29, 109, 103)
TEXT = (240, 247, 249)
TEXT_MUTED = (149, 169, 181)
WARN = (243, 190, 78)
ERROR = (227, 101, 91)
ALT_LOW = (243, 156, 90)
ALT_MID = (45, 181, 163)
ALT_HIGH = (183, 227, 245)
RADAR_WIDTH = 98
RADAR_HEIGHT = 70
RADAR_CENTER_X = 49
RADAR_CENTER_Y = 35
RADAR_RADIUS = 31
BADGE_STATUS_X = 126
BADGE_TREND_X = 160
BADGE_Y = 46
BADGE_WIDTH = 28
BADGE_HEIGHT = 12
BADGE_TEXT_CY = 52 # vertical center of badge
def _truncate(text, limit):
text = text or ""
if len(text) <= limit:
return text
return text[: limit - 1] + "..."
def _wrap_text(text, width, max_lines):
text = str(text or "")
if not text:
return ""
words = text.split()
if not words:
return ""
lines = []
current = words[0]
for word in words[1:]:
proposal = current + " " + word
if len(proposal) <= width:
current = proposal
continue
lines.append(current)
current = word
if len(lines) >= max_lines - 1:
break
if len(lines) < max_lines:
lines.append(current)
if len(lines) > max_lines:
lines = lines[:max_lines]
if len(lines) == max_lines and len(" ".join(words)) > len(" ".join(lines)):
lines[-1] = _truncate(lines[-1], max(4, width - 1))
return "\n".join(lines)
def _distance_label(distance_miles):
return "{:.1f}MI".format(distance_miles)
def _altitude_label(altitude_ft):
if altitude_ft is None:
return "--KFT"
return "{}KFT".format(max(0, int(round(altitude_ft / 1000.0))))
def _speed_label(speed_kts):
if speed_kts is None:
return "--KT"
return "{}KT".format(speed_kts)
def _heading_label(heading):
return "HDG{:03d}".format(int(heading) % 360)
def _vertical_label(vertical_rate_fpm):
if vertical_rate_fpm is None:
return "VS --"
return "VS {:+d}".format(int(vertical_rate_fpm))
def _trend_label(vertical_rate_fpm):
if vertical_rate_fpm is None:
return "LVL"
if vertical_rate_fpm > 250:
return "CLB"
if vertical_rate_fpm < -250:
return "DSC"
return "LVL"
def _altitude_color(altitude_ft):
if altitude_ft is None:
return TEXT_MUTED
if altitude_ft < 12000:
return ALT_LOW
if altitude_ft < 28000:
return ALT_MID
return ALT_HIGH
def _bearing_to_xy(bearing_degrees, distance_miles, radius_miles):
if radius_miles <= 0:
radius_fraction = 0
else:
radius_fraction = min(1.0, max(0.0, distance_miles / radius_miles))
angle = bearing_degrees * math.pi / 180.0
x_offset = int(round(math.sin(angle) * RADAR_RADIUS * radius_fraction))
y_offset = int(round(math.cos(angle) * RADAR_RADIUS * radius_fraction))
return RADAR_CENTER_X + x_offset, RADAR_CENTER_Y - y_offset
def _heading_endpoint(x_pos, y_pos, heading_degrees, length=8):
angle = heading_degrees * math.pi / 180.0
x_offset = int(round(math.sin(angle) * length))
y_offset = int(round(math.cos(angle) * length))
return x_pos + x_offset, y_pos - y_offset
def _radar_color(altitude_ft):
if altitude_ft is None:
return TEXT_MUTED
if altitude_ft < 12000:
return ALT_LOW
if altitude_ft < 28000:
return ALT_MID
return ALT_HIGH
def _draw_radar_pixel(surf, x, y, color):
if 0 <= x < RADAR_WIDTH and 0 <= y < RADAR_HEIGHT:
surf.set_at((x, y), color)
def _draw_radar_square(surf, cx, cy, radius, color):
for x in range(cx - radius, cx + radius + 1):
for y in range(cy - radius, cy + radius + 1):
_draw_radar_pixel(surf, x, y, color)
def _draw_radar_line(surf, x0, y0, x1, y1, color):
dx = abs(x1 - x0)
sx = 1 if x0 < x1 else -1
dy = -abs(y1 - y0)
sy = 1 if y0 < y1 else -1
err = dx + dy
while True:
_draw_radar_pixel(surf, x0, y0, color)
if x0 == x1 and y0 == y1:
return
e2 = err * 2
if e2 >= dy:
err += dy
x0 += sx
if e2 <= dx:
err += dx
y0 += sy
def _build_radar_surface(snapshot, radius_miles):
surf = pygame.Surface((RADAR_WIDTH, RADAR_HEIGHT))
surf.fill(SKY_BAND)
# Range rings
for ring_r in (10, 20, 30):
lo_sq = (ring_r - 1) ** 2
hi_sq = (ring_r + 1) ** 2
for x in range(RADAR_WIDTH):
for y in range(RADAR_HEIGHT):
d_sq = (x - RADAR_CENTER_X) ** 2 + (y - RADAR_CENTER_Y) ** 2
if lo_sq <= d_sq <= hi_sq:
surf.set_at((x, y), ACCENT_DIM)
# Crosshairs
_draw_radar_line(surf, RADAR_CENTER_X - RADAR_RADIUS, RADAR_CENTER_Y,
RADAR_CENTER_X + RADAR_RADIUS, RADAR_CENTER_Y, ACCENT_DIM)
_draw_radar_line(surf, RADAR_CENTER_X, RADAR_CENTER_Y - RADAR_RADIUS,
RADAR_CENTER_X, RADAR_CENTER_Y + RADAR_RADIUS, ACCENT_DIM)
_draw_radar_square(surf, RADAR_CENTER_X, RADAR_CENTER_Y, 1, TEXT_MUTED)
# North indicator
_draw_radar_line(surf, RADAR_CENTER_X, 2, RADAR_CENTER_X, 6, TEXT)
_draw_radar_line(surf, RADAR_CENTER_X - 2, 4, RADAR_CENTER_X + 2, 4, TEXT)
records = snapshot.get("records") or []
for record in records[1:]:
x, y = _bearing_to_xy(record["bearing"], record["distance_miles"], radius_miles)
color = TEXT_MUTED if not record.get("is_live") else _radar_color(record.get("altitude_ft"))
_draw_radar_square(surf, x, y, 1, color)
featured = snapshot.get("featured")
if featured:
x, y = _bearing_to_xy(featured["bearing"], featured["distance_miles"], radius_miles)
ex, ey = _heading_endpoint(x, y, featured["heading"])
_draw_radar_line(surf, x, y, ex, ey, TEXT)
_draw_radar_square(surf, x, y, 2, TEXT)
_draw_radar_square(surf, x, y, 1, _radar_color(featured.get("altitude_ft")))
return surf
def _build_plane_glyph_surface():
surf = pygame.Surface((RADAR_WIDTH, RADAR_HEIGHT))
surf.fill(SKY_BAND)
# Wings
pygame.draw.rect(surf, WARN, pygame.Rect(32, 34, 34, 4))
# Fuselage
pygame.draw.rect(surf, WARN, pygame.Rect(45, 21, 8, 28))
# Horizontal stabilizers
pygame.draw.rect(surf, WARN, pygame.Rect(39, 17, 20, 4))
pygame.draw.rect(surf, WARN, pygame.Rect(39, 49, 20, 4))
# Vertical stabilizer base
pygame.draw.rect(surf, WARN, pygame.Rect(44, 57, 10, 4))
return surf
class PlanePortalUI:
FONT_SIZE = 11
_NATIVE_W = 320
_NATIVE_H = 240
_NATIVE_LINE_H = 12 # approximate line height in native coords for layout math
def __init__(self, config):
self._config = config
pygame.init()
# Detect monitor resolution before creating the window.
info = pygame.display.Info()
display_w = info.current_w if info.current_w > 0 else self._NATIVE_W
display_h = info.current_h if info.current_h > 0 else self._NATIVE_H
flags = pygame.FULLSCREEN if config.fullscreen else 0
self._screen = pygame.display.set_mode((display_w, display_h), flags)
pygame.display.set_caption("Plane Portal")
pygame.mouse.set_visible(False)
# Scale factor: how many screen pixels per native pixel.
sw, sh = self._screen.get_size()
self._scale = min(sw / self._NATIVE_W, sh / self._NATIVE_H)
# Offsets to center the scaled content on the screen.
self._ox = (sw - int(self._NATIVE_W * self._scale)) // 2
self._oy = (sh - int(self._NATIVE_H * self._scale)) // 2
# Fonts sized to match the scale factor.
font_size = max(8, int(self.FONT_SIZE * self._scale))
self._font = pygame.font.SysFont("monospace", font_size)
self._font_large = pygame.font.SysFont("monospace", font_size * 2)
self._fh = self._font.get_height()
self._fh_large = self._font_large.get_height()
self.show_message(
"Plane Portal",
"Booting display",
"Edit settings.toml, then restart",
)
# -------------------------------------------------------------------------
# Internal drawing helpers
# -------------------------------------------------------------------------
def _pump(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
if event.type == pygame.KEYDOWN and event.key in (pygame.K_q, pygame.K_ESCAPE):
pygame.quit()
sys.exit(0)
def _flip(self):
pygame.display.flip()
def _r(self, x, y, w, h):
"""Convert native-coord rect to a scaled screen Rect."""
s = self._scale
return pygame.Rect(
self._ox + int(x * s),
self._oy + int(y * s),
max(1, int(w * s)),
max(1, int(h * s)),
)
def _fill_rect(self, x, y, w, h, color):
pygame.draw.rect(self._screen, color, self._r(x, y, w, h))
def _txt(self, text, color, x, cy, large=False):
"""Render text; x and cy are native coords, cy is the vertical center."""
font = self._font_large if large else self._font
fh = self._fh_large if large else self._fh
surf = font.render(str(text), True, color)
px = self._ox + int(x * self._scale)
py = self._oy + int(cy * self._scale) - fh // 2
self._screen.blit(surf, (px, py))
def _txt_multiline(self, text, color, x, cy, line_spacing=1.1):
"""Render multi-line text; x, cy are native coords."""
if not text:
return
lines = text.split("\n")
# Step in native coordinate space so _txt's scaling stays consistent.
step = int(self._NATIVE_LINE_H * line_spacing)
y = cy
for line in lines:
self._txt(line, color, x, y)
y += step
def _draw_base(self):
self._fill_rect(0, 0, 320, 240, BACKGROUND)
self._fill_rect(0, 0, 320, 80, SKY_BAND)
self._fill_rect(0, 0, 320, 28, CARD_ALT)
self._fill_rect(10, 38, 192, 154, CARD)
self._fill_rect(212, 38, 98, 154, CARD_ALT)
self._fill_rect(10, 198, 300, 32, CARD_ALT)
self._fill_rect(18, 52, 98, 70, SKY_BAND)
self._fill_rect(18, 120, 98, 2, ACCENT)
self._fill_rect(10, 194, 300, 2, ACCENT_DIM)
def _draw_badge(self, x, color, text):
pygame.draw.rect(self._screen, color, self._r(x, BADGE_Y, BADGE_WIDTH, BADGE_HEIGHT))
label = _truncate(str(text), 4)
surf = self._font.render(label, True, CARD_ALT)
fw = surf.get_width()
scaled_badge_w = max(1, int(BADGE_WIDTH * self._scale))
px = self._ox + int(x * self._scale) + max(1, (scaled_badge_w - fw) // 2)
py = self._oy + int(BADGE_TEXT_CY * self._scale) - self._fh // 2
self._screen.blit(surf, (px, py))
def _blit_image(self, surf):
target_w = max(1, int(RADAR_WIDTH * self._scale))
target_h = max(1, int(RADAR_HEIGHT * self._scale))
scaled = pygame.transform.smoothscale(surf, (target_w, target_h))
self._screen.blit(scaled, (self._ox + int(18 * self._scale),
self._oy + int(52 * self._scale)))
# -------------------------------------------------------------------------
# Public API
# -------------------------------------------------------------------------
def show_message(self, title, body, footer, side_text=None, use_radar=False):
self._pump()
self._draw_base()
if use_radar:
self._blit_image(_build_radar_surface({"records": [], "featured": None},
self._config.radius_miles))
else:
self._blit_image(_build_plane_glyph_surface())
self._txt(_truncate(title.upper(), 22), TEXT, 12, 17)
self._txt(_truncate(body, 24), TEXT_MUTED, 158, 17)
self._txt("STANDBY", WARN, 18, 48)
self._draw_badge(BADGE_STATUS_X, WARN, "WAIT")
self._draw_badge(BADGE_TREND_X, CARD_ALT, "IDLE")
self._txt(_wrap_text(body, 22, 2), TEXT, 126, 74)
self._txt(_wrap_text(footer, 22, 2), TEXT_MUTED, 126, 96)
self._txt(_wrap_text(body, 22, 2), TEXT, 18, 146)
self._txt_multiline(_wrap_text(footer, 22, 2), TEXT_MUTED, 18, 166)
self._txt("STATUS", TEXT, 222, 56)
side = side_text or "Waiting for first\nnearby aircraft"
self._txt_multiline(_wrap_text(side, 13, 5), TEXT_MUTED, 222, 76)
self._txt(_truncate(footer, 46), TEXT_MUTED, 18, 216)
self._flip()
def show_refreshing(self, detail, source_label):
self._pump()
self._draw_base()
self._blit_image(_build_plane_glyph_surface())
self._txt("PLANE PORTAL", TEXT, 12, 17)
self._txt(_truncate(source_label, 24), TEXT_MUTED, 158, 17)
self._txt("REFRESH", WARN, 18, 48)
self._draw_badge(BADGE_STATUS_X, WARN, "SCAN")
self._draw_badge(BADGE_TREND_X, ACCENT_DIM, "LIVE")
self._txt("STATUS", TEXT, 222, 56)
self._txt_multiline(_wrap_text(detail, 13, 5), TEXT_MUTED, 222, 76)
self._txt(_truncate(detail, 46), WARN, 18, 216)
self._flip()
def render_snapshot(self, snapshot, ip_address, source_label, stale=False, detail=None):
self._pump()
featured = snapshot["featured"]
if featured is None:
if snapshot.get("has_seen_aircraft"):
self.show_message(
"Quiet Sky",
"No aircraft now",
"Watching {} miles around watch point".format(self._config.radius_miles),
side_text="No aircraft in recent window",
use_radar=True,
)
else:
self.show_message(
"Quiet Sky",
"No planes logged",
"Watching {} miles around watch point".format(self._config.radius_miles),
side_text="Waiting for first nearby aircraft",
use_radar=False,
)
return
self._draw_base()
# Header
self._txt("PLANE PORTAL", TEXT, 12, 17)
self._txt(_truncate("{} {}".format(source_label, ip_address), 24), TEXT_MUTED, 158, 17)
# Radar
self._blit_image(_build_radar_surface(snapshot, self._config.radius_miles))
# Status line above radar
status_color = WARN if stale else ACCENT
self._txt(featured["status_text"], status_color, 18, 48)
# Badges
trend = _trend_label(featured["vertical_rate_fpm"])
self._draw_badge(BADGE_STATUS_X, status_color, featured["status_text"])
self._draw_badge(BADGE_TREND_X, self._trend_color(featured["vertical_rate_fpm"]), trend)
# Featured aircraft details (right of radar)
self._txt(_truncate(featured["callsign"], 6), TEXT, 126, 74, large=True)
self._txt(_truncate(self._aircraft_line(featured), 14),
_altitude_color(featured.get("altitude_ft")), 126, 96)
self._txt(_truncate(self._route_badge(featured), 16), TEXT, 126, 114)
# Image badge (ICAO/registration in radar area)
self._txt(_truncate(self._image_badge_text(featured), 12), TEXT_MUTED, 18, 132)
# Metrics below radar
self._txt(_truncate(self._metric_line(featured), 26), TEXT, 18, 146)
self._txt(_truncate(self._metric_line_secondary(featured), 26), TEXT_MUTED, 18, 166)
self._txt(_truncate(self._owner_badge(featured), 26), TEXT_MUTED, 18, 184)
# Side panel
self._txt("RECENT SKY", TEXT, 222, 56)
self._txt_multiline(self._side_list_text(snapshot["others"]), TEXT_MUTED, 222, 76)
# Footer
footer_text = detail or "{} live, {} recent inside {} mi".format(
snapshot["live_count"],
snapshot["recent_count"],
int(self._config.radius_miles),
)
self._txt(_truncate(footer_text, 46), WARN if stale else TEXT_MUTED, 18, 216)
self._flip()
# -------------------------------------------------------------------------
# Data formatting helpers
# -------------------------------------------------------------------------
def _aircraft_line(self, record):
enrichment = record.get("enrichment") or {}
aircraft = enrichment.get("aircraft") or {}
registration = aircraft.get("registration")
aircraft_type = aircraft.get("type") or aircraft.get("icao_type")
if registration and aircraft_type:
return "{} {}".format(registration, aircraft_type)
if registration:
return registration
if aircraft_type:
return aircraft_type
return record["category_name"]
def _route_line(self, record):
enrichment = record.get("enrichment") or {}
flightroute = enrichment.get("flightroute") or {}
origin = flightroute.get("origin") or {}
destination = flightroute.get("destination") or {}
origin_code = origin.get("iata_code") or origin.get("icao_code")
destination_code = destination.get("iata_code") or destination.get("icao_code")
if origin_code and destination_code:
return "{} -> {}".format(origin_code, destination_code)
return None
def _metric_line(self, record):
return "{} {} {}".format(
_distance_label(record["distance_miles"]),
_altitude_label(record["altitude_ft"]),
_speed_label(record["speed_kts"]),
)
def _metric_line_secondary(self, record):
return "BRG{:03d} {} {}".format(
record["bearing"],
_heading_label(record["heading"]),
_vertical_label(record["vertical_rate_fpm"]),
)
def _route_badge(self, record):
route = self._route_line(record)
if not route:
return "NO ROUTE"
return route.replace(" -> ", ">")
def _owner_badge(self, record):
owner = self._owner_line(record)
if not owner:
return record.get("category_name") or "Aircraft"
return _truncate(owner, 20)
def _trend_color(self, vertical_rate_fpm):
if vertical_rate_fpm is None:
return CARD_ALT
if vertical_rate_fpm > 250:
return ALT_HIGH
if vertical_rate_fpm < -250:
return ALT_LOW
return TEXT_MUTED
def _owner_line(self, record):
enrichment = record.get("enrichment") or {}
aircraft = enrichment.get("aircraft") or {}
flightroute = enrichment.get("flightroute") or {}
airline = flightroute.get("airline") or {}
if airline.get("name"):
return airline.get("name")
if aircraft.get("registered_owner"):
return aircraft.get("registered_owner")
if aircraft.get("manufacturer"):
return aircraft.get("manufacturer")
return None
def _image_badge_text(self, record):
enrichment = record.get("enrichment") or {}
aircraft = enrichment.get("aircraft") or {}
if aircraft.get("registration"):
return aircraft.get("registration")
return record["icao24"].upper()
def _side_list_text(self, records):
if not records:
return "No other nearby\naircraft in the\nrecent window"
lines = []
for record in records:
route = self._route_badge(record)
lines.append(
"{} {}\n{} {}\n{}".format(
record["status_text"][0],
_distance_label(record["distance_miles"]),
_truncate(record["callsign"], 6),
_altitude_label(record["altitude_ft"]),
_truncate(route, 12),
)
)
return "\n".join(lines)