177 lines
6.1 KiB
Python
177 lines
6.1 KiB
Python
"""Тексты и разметка для окна и значка в трее (без зависимостей от Qt — удобно тестировать)."""
|
||
from __future__ import annotations
|
||
|
||
import html
|
||
import time
|
||
from dataclasses import dataclass
|
||
from typing import List, Optional
|
||
|
||
from .config import Config
|
||
from .model import Forecast, Observation, Period, Snapshot
|
||
|
||
ARROWS = ["↓", "↙", "←", "↖", "↑", "↗", "→", "↘"]
|
||
DIM = "#b4bac0"
|
||
ERR = "#ff8a80"
|
||
|
||
|
||
def num(d: float) -> str:
|
||
return str(int(d)) if d == int(d) else f"{d:.1f}"
|
||
|
||
|
||
def signed(d: float) -> str:
|
||
return ("+" if d > 0 else "") + num(d)
|
||
|
||
|
||
def icon(o: Optional[Observation]) -> str:
|
||
if o is None or o.cloud_score is None:
|
||
return "·"
|
||
if o.cloud_score <= 2:
|
||
return "☀"
|
||
if o.cloud_score <= 7:
|
||
return "⛅"
|
||
return "☁"
|
||
|
||
|
||
def title(o: Optional[Observation]) -> str:
|
||
return o.station if o is not None and o.station else "Погода"
|
||
|
||
|
||
def temp(o: Observation) -> str:
|
||
return f"{o.temperature:.1f} °C"
|
||
|
||
|
||
def wind(o: Observation) -> str:
|
||
# стрелка показывает, куда дует ветер (откуда + 180°)
|
||
arrow = ARROWS[(o.wind_from_deg // 45) % 8] + " " if o.wind_from_deg is not None else ""
|
||
speed = f"{num(o.wind_speed)} м/с" if o.wind_speed is not None else "—"
|
||
return arrow + speed + (f", {o.wind_dir_text}" if o.wind_dir_text else "")
|
||
|
||
|
||
def humidity(o: Observation) -> str:
|
||
return f"{num(o.humidity)} %" if o.humidity is not None else "—"
|
||
|
||
|
||
def pressure(o: Observation, fc: Optional[Forecast]) -> str:
|
||
s = f"{num(o.pressure)} мм рт. ст." if o.pressure is not None else "—"
|
||
if fc is not None and fc.trend is not None:
|
||
t = fc.trend
|
||
s += f" {t.arrow} {t.word} (по прогнозу {signed(t.delta)} мм за {t.hours} ч)"
|
||
return s
|
||
|
||
|
||
def precip(o: Observation, fc: Optional[Forecast]) -> str:
|
||
if o.precipitation:
|
||
return o.precipitation
|
||
return "в наблюдениях нет, см. прогноз ниже" if fc is not None else "нет данных"
|
||
|
||
|
||
def prob(p: Period) -> str:
|
||
if p.prob is None:
|
||
return "—"
|
||
return f"{num(p.prob)} %" + (" ☔" if p.prob >= 50 else "")
|
||
|
||
|
||
def wind_short(p: Period) -> str:
|
||
return f"{num(p.wind)} м/с" if p.wind is not None else ""
|
||
|
||
|
||
def temp_short(p: Period) -> str:
|
||
return f"{round(p.temp)}°" if p.temp is not None else ""
|
||
|
||
|
||
def clock(ts: float) -> str:
|
||
return time.strftime("%H:%M", time.localtime(ts))
|
||
|
||
|
||
def footer(o: Observation, snap: Optional[Snapshot]) -> str:
|
||
s = f"Наблюдение: {o.time} (местн.)"
|
||
if snap is not None and snap.fetched_at > 0:
|
||
s += f" · проверено {clock(snap.fetched_at)}"
|
||
return s
|
||
|
||
|
||
def errors(snap: Optional[Snapshot]) -> List[str]:
|
||
out: List[str] = []
|
||
if snap is not None:
|
||
if snap.obs_error:
|
||
out.append(snap.obs_error)
|
||
if snap.forecast_error:
|
||
out.append("Прогноз: " + snap.forecast_error)
|
||
return out
|
||
|
||
|
||
@dataclass
|
||
class View:
|
||
html: str
|
||
tooltip: str
|
||
tray_text: str
|
||
tray_cold: bool
|
||
|
||
|
||
def build_view(snap: Optional[Snapshot], cfg: Config) -> View:
|
||
e = html.escape
|
||
fs, col = cfg.font_size, cfg.text_color
|
||
o = snap.obs if snap else None
|
||
fc = snap.forecast if snap else None
|
||
parts: List[str] = []
|
||
|
||
parts.append(f'<div style="font-size:{fs + 3}pt; font-weight:600; color:{col};">{e(title(o))}</div>')
|
||
|
||
if o is not None:
|
||
parts.append(f'<div style="font-size:{round(fs * 2.4)}pt; color:{col};">{icon(o)} {e(temp(o))}</div>')
|
||
rows = [
|
||
("Ветер", wind(o)),
|
||
("Влажность", humidity(o)),
|
||
("Давление", pressure(o, fc)),
|
||
("Осадки", precip(o, fc)),
|
||
]
|
||
parts.append('<table cellspacing="0" cellpadding="1" style="margin-top:6px;">')
|
||
for label, value in rows:
|
||
parts.append(
|
||
f'<tr><td style="color:{DIM}; padding-right:16px;">{label}</td>'
|
||
f'<td style="color:{col};">{e(value)}</td></tr>'
|
||
)
|
||
parts.append("</table>")
|
||
elif snap is None:
|
||
parts.append(f'<div style="color:{DIM};">Загрузка…</div>')
|
||
|
||
periods = (fc.periods if fc else [])[: max(0, cfg.forecast_rows)]
|
||
if periods:
|
||
parts.append(f'<div style="color:{DIM}; margin-top:8px;">Прогноз</div>')
|
||
parts.append('<table cellspacing="0" cellpadding="1">')
|
||
for p in periods:
|
||
parts.append(
|
||
f'<tr><td style="color:{col}; padding-right:12px;">{e(p.label)}</td>'
|
||
f'<td align="right" style="color:{col}; padding-right:10px;">{e(prob(p))}</td>'
|
||
f'<td align="right" style="color:{col}; padding-right:10px;">{e(temp_short(p))}</td>'
|
||
f'<td align="right" style="color:{DIM}; padding-right:12px;">{e(wind_short(p))}</td>'
|
||
f'<td style="color:{DIM};">{e(p.cond)}</td></tr>'
|
||
)
|
||
parts.append("</table>")
|
||
if fc and fc.updated:
|
||
parts.append(
|
||
f'<div style="font-size:{max(7, fs - 3)}pt; color:{DIM};">'
|
||
f'Прогноз Гидрометцентра, обновлён {e(fc.updated)}</div>'
|
||
)
|
||
|
||
small = max(7, fs - 2)
|
||
if o is not None:
|
||
parts.append(f'<div style="font-size:{small}pt; color:{DIM}; margin-top:6px;">{e(footer(o, snap))}</div>')
|
||
for err in errors(snap):
|
||
parts.append(f'<div style="font-size:{small}pt; color:{ERR};">{e(err)}</div>')
|
||
|
||
if o is not None:
|
||
tooltip = "\n".join([
|
||
f"{title(o)}: {temp(o)}",
|
||
f"Ветер: {wind(o)}",
|
||
f"Влажность: {humidity(o)}",
|
||
f"Давление: {num(o.pressure) + ' мм рт. ст.' if o.pressure is not None else '—'}",
|
||
])
|
||
tray_text = f"{round(o.temperature)} °C" # без « °C» цифры получаются ещё крупнее
|
||
cold = o.temperature <= 0
|
||
else:
|
||
tooltip = "Погода Гидрометцентра\n" + ("\n".join(errors(snap)) or "Загрузка…")
|
||
tray_text = "?"
|
||
cold = False
|
||
return View("".join(parts), tooltip, tray_text, cold)
|