feat: add FS25_FarmHUD mod and FarmHUD desktop companion app

Initial commit: the FS25 Lua mod (live.json data export), the
FS25-WebDashboard project (Node/web dashboard + PySide6 desktop
variant), and FarmHUD (standalone PySide6 companion app with
Discord Rich Presence, settings, and installer).
This commit is contained in:
2026-09-27 15:25:07 +02:00
commit e5754cca18
63 changed files with 7196 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
.venv/
__pycache__/
*.pyc
+67
View File
@@ -0,0 +1,67 @@
# FS25 Desktop Dashboard (Python)
Native Desktop-App (PySide6/Qt) als Ersatz für den alten Node.js-Server +
Browser-Dashboard. Zeigt dieselben Live-Daten wie die Web-Version, aber als
eigenständiges Fenster – kein Browser, kein Node.js, kein separater Server
nötig. Die App liest `live.json` direkt ein.
```
FS25 (Mod) --schreibt--> live.json --liest--> Python-Desktop-App
```
## Installation & Start
1. [Python 3.10+](https://python.org) installieren, falls noch nicht vorhanden
(Haken bei "Add python.exe to PATH" beim Installer setzen).
2. Einmalig `setup.bat` in diesem Ordner ausführen (installiert PySide6 in
eine lokale `.venv`).
3. Danach im Hauptordner `Dashboard-Desktop-starten.bat` doppelklicken
(oder `FS25-und-Dashboard-Desktop-starten.bat`, um Spiel + Dashboard
zusammen zu starten).
Manuell ohne die .bat-Dateien:
```bash
cd desktop-app
python -m venv .venv
.venv\Scripts\pip install -r requirements.txt
.venv\Scripts\python main.py
```
Der Mod (`mod/FS25_FarmHUD`) wird weiterhin wie in der
[Haupt-README](../README.md) beschrieben installiert – daran ändert sich
nichts.
## Was die App zeigt
Identisch zur Web-Version: ausgewähltes Fahrzeug (Tacho, Drehzahlmesser,
Tempomat, Motor, Tank/Schaden/Verschmutzung, angekoppelte Geräte,
60-Sekunden-Geschwindigkeitsverlauf), Zeit, Wetter (+ Vorschau), Betrieb,
Lager/Tierhaltung/Produktion, sowie eine Tabelle aller Fahrzeuge (anklickbar
zur manuellen Auswahl, "📍 Mein Fahrzeug" um wieder automatisch dem
gesteuerten Fahrzeug zu folgen). Hell/Dunkel-Umschalter und Vollbildmodus
oben rechts, Panels lassen sich einzeln einklappen (Zustand wird gemerkt).
## Projektstruktur
```
desktop-app/
├── main.py ← Einstiegspunkt
├── main_window.py ← Fenster-Aufbau, Live-Poll-Timer, Panel-Verdrahtung
├── live_data.py ← findet & liest live.json (ersetzt server.js)
├── state.py ← Auswahl-/Verlaufs-Logik (ersetzt `state` in app.js)
├── formatting.py ← Zahlen-/Text-Formatierung, Wetter-/Status-Labels
├── theme.py ← Hell/Dunkel-Farbschema + Stylesheet
├── widgets/ ← ein Modul pro Panel (Fahrzeug, Zeit, Wetter,
│ Betrieb, Lager, Tabelle) + Gauge/Sparkline
├── requirements.txt
└── setup.bat
```
## Hinweis: Web-Version bleibt erhalten
Die alte `server/` + `web/`-Lösung bleibt im Repo bestehen – sie hat einen
Vorteil, den die Desktop-App nicht hat: sie lässt sich im selben WLAN auch
von einem Handy/Tablet aus öffnen (z. B. als zweites Cockpit-Display). Für
die normale Nutzung am Spiel-PC ist die Desktop-App aber die einfachere Wahl
(kein Node.js, kein Browser-Tab, kein Server-Fenster).
+103
View File
@@ -0,0 +1,103 @@
"""Shared formatting helpers and lookup tables.
Mirrors the formatting logic in ``web/app.js`` 1:1 so the desktop app shows
exactly the same numbers/labels as the browser dashboard did.
"""
from __future__ import annotations
from typing import Any, Optional
WEATHER_ICONS = {
"SUN": "☀️",
"PARTIALLY_CLOUDY": "🌤️",
"CLOUDY": "☁️",
"RAIN": "🌧️",
"SNOW": "❄️",
"HAIL": "🧊",
"TWISTER": "🌪️",
"THUNDER": "⛈️",
}
WEATHER_LABELS_DE = {
"SUN": "Sonnig",
"PARTIALLY_CLOUDY": "Teils bewölkt",
"CLOUDY": "Bewölkt",
"RAIN": "Regen",
"SNOW": "Schnee",
"HAIL": "Hagel",
"TWISTER": "Tornado",
"THUNDER": "Gewitter",
}
# Best-effort translation - the real ProductionPoint.PROD_STATUS enum wasn't
# fully enumerable from the shipped source (only MISSING_INPUTS was confirmed
# via an actual usage), so unrecognized status names just show as-is.
PRODUCTION_STATUS_LABELS = {
"RUNNING": "läuft",
"ACTIVE": "läuft",
"STOPPED": "gestoppt",
"DISABLED": "deaktiviert",
"PAUSED": "pausiert",
"MISSING_INPUTS": "Rohstoffe fehlen",
"MISSING_OUTPUT_CAPACITY": "Lager voll",
"NO_INPUT_CAPACITY": "Lager voll",
}
def production_status_ok(name: Optional[str]) -> Optional[bool]:
"""True = ok/green, False = warn/orange, None = neutral (no status)."""
if name in ("RUNNING", "ACTIVE"):
return True
if not name:
return None
return False
def is_number(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool)
def format_number(n: Any, digits: int = 0) -> str:
if not is_number(n):
return "–"
return f"{n:.{digits}f}"
def format_euro(n: Any) -> str:
if not is_number(n):
return "–"
# de-DE grouping uses '.' as thousands separator - build it manually
# since Python's locale module would require the OS locale to be set.
text = f"{round(n):,}".replace(",", ".")
return f"{text} €"
def format_liters(n: Any) -> str:
if not is_number(n):
return "0"
text = f"{round(n):,}".replace(",", ".")
return text
# A plain implement (trailer, plow, seed drill, ...) has neither an engine
# (Motorized) nor its own steering/cruise control (Drivable) - its "speed" is
# just whatever's towing it, so showing a km/h number for it is noise rather
# than information.
def is_drivable(vehicle: dict) -> bool:
return isinstance(vehicle.get("motorStarted"), bool) or isinstance(
vehicle.get("cruiseControlActive"), bool
)
def format_fuel(vehicle: dict) -> str:
level = vehicle.get("fuelLevel")
capacity = vehicle.get("fuelCapacity")
if not is_number(level) or not is_number(capacity) or capacity <= 0:
return "–"
return f"{round((level / capacity) * 100)}%"
def farm_suffix(owner_farm_id: Any, show: bool) -> str:
if show and owner_farm_id is not None:
return f" (Betrieb #{owner_farm_id})"
return ""
@@ -0,0 +1,86 @@
"""Locates and reads the FS25 WebDashboard mod's live.json file.
Replaces the file-locating part of ``server/server.js`` - same candidate
paths (including the OneDrive-redirected-Documents cases), same
``FS25_LIVE_JSON`` environment variable override, same "keep re-resolving
until the file actually appears" behaviour (the game may not have written it
yet on first launch).
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any, Optional
def candidate_live_data_paths() -> list[Path]:
home = Path.home()
candidates: list[Path] = []
env_path = os.environ.get("FS25_LIVE_JSON")
if env_path:
candidates.append(Path(env_path))
# OneDrive can redirect "Documents" - check both the plain and OneDrive path.
tail = Path("My Games") / "FarmingSimulator2025" / "modSettings" / "FS25_FarmHUD" / "live.json"
candidates.append(home / "Documents" / tail)
candidates.append(home / "OneDrive" / "Documents" / tail)
candidates.append(home / "OneDrive" / "Dokumente" / tail)
return candidates
class LiveDataSource:
"""Resolves live.json's path once, then keeps re-checking it exists.
Mirrors ``resolveLiveDataPath`` / ``serveLiveData`` from server.js:
picks the first candidate that exists, falls back to the first guess
otherwise, and re-resolves on every read if the current path stops
existing (e.g. the server/app was started before the game wrote it).
"""
def __init__(self) -> None:
self.path: Optional[Path] = self._resolve()
def _resolve(self) -> Optional[Path]:
candidates = candidate_live_data_paths()
for candidate in candidates:
if candidate.exists():
return candidate
return candidates[0] if candidates else None
def read(self) -> dict[str, Any]:
"""Returns the parsed live.json, or a `connected: false` stand-in."""
if self.path is None or not self.path.exists():
resolved = self._resolve()
if resolved is not None:
self.path = resolved
if self.path is None or not self.path.exists():
return {
"connected": False,
"error": (
"live.json not found yet - start Farming Simulator 25 "
"with the WebDashboard mod active and load a savegame."
),
"expectedPath": str(self.path) if self.path else None,
}
try:
text = self.path.read_text(encoding="utf-8")
data = json.loads(text)
except (OSError, json.JSONDecodeError):
# The mod writes this file 4x/second - reading it mid-write can
# occasionally race into a truncated file. Treat that the same
# as "not connected yet" rather than crashing the poll loop;
# the next tick reads it fine.
return {
"connected": False,
"error": "live.json is being written, retrying…",
"expectedPath": str(self.path),
}
if isinstance(data, dict):
data.setdefault("connected", True)
return data
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""FS25 Web Dashboard - native desktop app.
Reads the mod's live.json directly (no Node.js server / browser needed
anymore) and renders the same information the old web dashboard did as a
native PySide6 window.
Run:
pip install -r requirements.txt
python main.py
"""
from __future__ import annotations
import sys
from PySide6.QtWidgets import QApplication
from main_window import MainWindow
def main() -> int:
app = QApplication(sys.argv)
app.setApplicationName("FS25 Live Dashboard")
window = MainWindow()
window.show()
return app.exec()
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,197 @@
"""Main window: assembles all panels into a scrollable grid, polls
live.json on a timer (replaces the browser's `fetch('/api/live')` polling
and the Node.js server it used to hit), and wires selection/theme/
fullscreen the same way app.js did."""
from __future__ import annotations
from typing import Any
from PySide6.QtCore import QSettings, QTimer
from PySide6.QtWidgets import (
QGridLayout,
QMainWindow,
QScrollArea,
QVBoxLayout,
QWidget,
)
from live_data import LiveDataSource
from state import AppState
from theme import (
SETTINGS_APP,
SETTINGS_ORG,
build_stylesheet,
colors_for,
load_theme_name,
save_theme_name,
)
from widgets.farm_panel import FarmPanel
from widgets.storage_panel import StoragePanel
from widgets.time_panel import TimePanel
from widgets.top_bar import TopBar
from widgets.vehicle_panel import VehiclePanel
from widgets.vehicle_table import VehicleTablePanel
from widgets.weather_panel import WeatherPanel
POLL_INTERVAL_MS = 500
COLLAPSE_SETTINGS_PREFIX = "collapsed/"
class MainWindow(QMainWindow):
def __init__(self) -> None:
super().__init__()
self.setWindowTitle("FS25 Live Dashboard")
self.resize(1200, 860)
self.state = AppState()
self.live_data = LiveDataSource()
self.settings = QSettings(SETTINGS_ORG, SETTINGS_APP)
central = QWidget()
self.setCentralWidget(central)
outer = QVBoxLayout(central)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
self.top_bar = TopBar()
self.top_bar.theme_toggle_requested.connect(self._toggle_theme)
self.top_bar.fullscreen_toggle_requested.connect(self._toggle_fullscreen)
outer.addWidget(self.top_bar)
scroll = QScrollArea()
scroll.setWidgetResizable(True)
outer.addWidget(scroll)
content = QWidget()
scroll.setWidget(content)
grid = QGridLayout(content)
grid.setContentsMargins(14, 14, 14, 14)
grid.setSpacing(14)
grid.setColumnStretch(0, 3)
grid.setColumnStretch(1, 2)
self.vehicle_panel = VehiclePanel()
self.vehicle_panel.follow_requested.connect(self._on_follow_requested)
grid.addWidget(self.vehicle_panel, 0, 0, 3, 1)
self.time_panel = TimePanel()
grid.addWidget(self.time_panel, 0, 1)
self.weather_panel = WeatherPanel()
grid.addWidget(self.weather_panel, 1, 1)
self.farm_panel = FarmPanel()
grid.addWidget(self.farm_panel, 2, 1)
self.storage_panel = StoragePanel()
grid.addWidget(self.storage_panel, 3, 0, 1, 2)
self.vehicle_table = VehicleTablePanel()
self.vehicle_table.vehicle_clicked.connect(self._on_vehicle_row_clicked)
grid.addWidget(self.vehicle_table, 4, 0, 1, 2)
grid.setRowStretch(5, 1)
self._panels = [
self.vehicle_panel,
self.time_panel,
self.weather_panel,
self.farm_panel,
self.storage_panel,
self.vehicle_table,
]
self._restore_panel_collapse_state()
self._apply_theme(load_theme_name())
self.timer = QTimer(self)
self.timer.timeout.connect(self._poll_once)
self.timer.start(POLL_INTERVAL_MS)
self._poll_once()
# ------------------------------------------------------------------
# Panel collapse persistence (mirrors the `fs25dash.collapsed.<id>`
# localStorage keys in app.js)
# ------------------------------------------------------------------
def _restore_panel_collapse_state(self) -> None:
for panel in self._panels:
key = COLLAPSE_SETTINGS_PREFIX + panel.panel_id
collapsed = self.settings.value(key, False, type=bool)
panel.set_collapsed(collapsed)
panel.collapsed_changed.connect(
lambda is_collapsed, p=panel: self.settings.setValue(
COLLAPSE_SETTINGS_PREFIX + p.panel_id, is_collapsed
)
)
# ------------------------------------------------------------------
# Theme + fullscreen
# ------------------------------------------------------------------
def _apply_theme(self, name: str) -> None:
self._theme_name = name
from PySide6.QtWidgets import QApplication
QApplication.instance().setStyleSheet(build_stylesheet(name))
# The gauge/sparkline widgets paint themselves with QPainter (not
# QSS), so their colors need pushing through explicitly on every
# theme change - otherwise they'd keep the dark-theme hardcoded
# defaults and become unreadable in light mode.
c = colors_for(name)
self.vehicle_panel.speed_gauge.set_colors(c["track"], c["text"], c["text-dim"])
self.vehicle_panel.rpm_gauge.set_colors(c["track"], c["text"], c["text-dim"])
self.vehicle_panel.speed_history_widget.set_accent(c["accent"])
def _toggle_theme(self) -> None:
next_name = "light" if self._theme_name != "light" else "dark"
save_theme_name(next_name)
self._apply_theme(next_name)
def _toggle_fullscreen(self) -> None:
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
# ------------------------------------------------------------------
# Selection
# ------------------------------------------------------------------
def _on_follow_requested(self) -> None:
self.state.follow_my_vehicle_now()
if self.state.last_data:
self._render(self.state.last_data)
def _on_vehicle_row_clicked(self, vehicle_id: Any) -> None:
self.state.select_vehicle(vehicle_id, manual=True)
if self.state.last_data:
self._render(self.state.last_data)
# ------------------------------------------------------------------
# Polling + render dispatch (mirrors `pollOnce` / `onData` in app.js)
# ------------------------------------------------------------------
def _poll_once(self) -> None:
data = self.live_data.read()
self.state.last_data = data
self._render(data)
connected = data.get("connected") is not False
waiting = bool(data.get("error"))
self.top_bar.set_status(connected, waiting)
def _render(self, data: dict) -> None:
vehicles = data.get("vehicles") or []
self.top_bar.set_map_id((data.get("mission") or {}).get("mapId") or "")
self.state.ensure_selection(vehicles, data.get("controlledVehicleId"))
self.vehicle_table.render_table(vehicles, self.state.selected_vehicle_id)
selected = next((v for v in vehicles if v.get("id") == self.state.selected_vehicle_id), None)
self.vehicle_panel.render_selected(selected, vehicles, self.state)
self.time_panel.render_time(data.get("time"))
self.weather_panel.render_weather(data.get("weather"), data.get("time"))
self.farm_panel.render_farm(data.get("mission"), data.get("farmlands"), data.get("farms"))
self.farm_panel.render_player_status(data.get("player"))
self.storage_panel.render_storage(
data.get("silos"), data.get("husbandries"), data.get("productions"), data.get("farms")
)
@@ -0,0 +1 @@
PySide6>=6.10
+21
View File
@@ -0,0 +1,21 @@
@echo off
title FS25 Dashboard - Setup
cd /d "%~dp0"
echo Erstelle Python-Umgebung (.venv) fuer das Dashboard...
python -m venv .venv
if errorlevel 1 (
echo.
echo Python wurde nicht gefunden. Installiere Python 3.10+ von https://python.org
echo und starte dieses Skript danach erneut.
pause
exit /b 1
)
echo Installiere Abhaengigkeiten (PySide6)...
".venv\Scripts\python.exe" -m pip install --upgrade pip >nul
".venv\Scripts\python.exe" -m pip install -r requirements.txt
echo.
echo Fertig! Start ueber "Dashboard-Desktop-starten.bat" im Hauptordner.
pause
+61
View File
@@ -0,0 +1,61 @@
"""App-wide selection/history state - mirrors `state` in web/app.js."""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Any, Optional
SPEED_HISTORY_WINDOW_S = 60.0
@dataclass
class AppState:
selected_vehicle_id: Any = None
# True = the vehicle panel always shows whatever you're currently
# driving; False = it's pinned to a manually clicked vehicle.
follow_my_vehicle: bool = True
speed_history: list[tuple[float, float]] = field(default_factory=list)
last_data: Optional[dict] = None
def select_vehicle(self, vehicle_id: Any, manual: bool = False) -> None:
if self.selected_vehicle_id != vehicle_id:
self.speed_history = []
self.selected_vehicle_id = vehicle_id
if manual:
self.follow_my_vehicle = False
def follow_my_vehicle_now(self) -> None:
self.follow_my_vehicle = True
def ensure_selection(self, vehicles: list[dict], controlled_vehicle_id: Any) -> None:
vehicle_ids = {v.get("id") for v in vehicles}
# "Follow me" (default): always show whatever you're currently
# sitting in, even if something else was clicked earlier - as long
# as you ARE in a vehicle. Getting out doesn't cancel follow mode,
# it just has nothing to jump to yet (falls through below) until
# you get back in.
if (
self.follow_my_vehicle
and controlled_vehicle_id is not None
and controlled_vehicle_id in vehicle_ids
):
self.select_vehicle(controlled_vehicle_id, manual=False)
return
if self.selected_vehicle_id is not None and self.selected_vehicle_id in vehicle_ids:
return
if controlled_vehicle_id is not None and controlled_vehicle_id in vehicle_ids:
self.select_vehicle(controlled_vehicle_id, manual=False)
return
if vehicles:
self.select_vehicle(vehicles[0].get("id"), manual=False)
else:
self.selected_vehicle_id = None
def push_speed_history(self, speed: float) -> None:
now = time.monotonic()
self.speed_history.append((now, speed))
cutoff = now - SPEED_HISTORY_WINDOW_S
while self.speed_history and self.speed_history[0][0] < cutoff:
self.speed_history.pop(0)
+159
View File
@@ -0,0 +1,159 @@
"""Light/dark theme colors + Qt stylesheet, persisted like the web version's
`localStorage` theme key (via QSettings this time).
"""
from __future__ import annotations
from PySide6.QtCore import QSettings
SETTINGS_ORG = "FS25WebDashboard"
SETTINGS_APP = "DesktopDashboard"
THEME_KEY = "theme"
DARK = {
"bg": "#12161c",
"panel": "#1b212b",
"panel-header": "#222a36",
"border": "#2b3442",
"text": "#e7ecf3",
"text-dim": "#8b97a8",
"accent": "#4da3ff",
"accent-rpm": "#ff9f4d",
"danger": "#ff5d5d",
"ok": "#3ecf7a",
"warn": "#e8b93f",
"track": "#2b3442",
}
LIGHT = {
"bg": "#f2f4f7",
"panel": "#ffffff",
"panel-header": "#eef1f5",
"border": "#dbe1e8",
"text": "#1a2230",
"text-dim": "#5c6a7d",
"accent": "#1c6fe0",
"accent-rpm": "#e07a1c",
"danger": "#d3392f",
"ok": "#1f9d55",
"warn": "#b8860b",
"track": "#e2e7ed",
}
def load_theme_name() -> str:
settings = QSettings(SETTINGS_ORG, SETTINGS_APP)
return settings.value(THEME_KEY, "dark")
def save_theme_name(name: str) -> None:
settings = QSettings(SETTINGS_ORG, SETTINGS_APP)
settings.setValue(THEME_KEY, name)
def colors_for(name: str) -> dict:
return DARK if name != "light" else LIGHT
def build_stylesheet(name: str) -> str:
c = colors_for(name)
return f"""
QWidget {{
background: {c['bg']};
color: {c['text']};
font-size: 13px;
}}
QMainWindow, QScrollArea, QScrollArea > QWidget > QWidget {{
background: {c['bg']};
}}
QGroupBox {{
background: {c['panel']};
border: 1px solid {c['border']};
border-radius: 8px;
margin-top: 0px;
padding: 0px;
}}
QFrame[role="panel"] {{
background: {c['panel']};
border: 1px solid {c['border']};
border-radius: 8px;
}}
QLabel {{
background: transparent;
}}
QLabel[role="panel-title"] {{
font-size: 14px;
font-weight: 600;
background: transparent;
}}
QLabel[role="panel-sub"], QLabel[role="stat-label"] {{
color: {c['text-dim']};
font-size: 11px;
}}
QLabel[role="stat-value"] {{
font-size: 14px;
font-weight: 600;
}}
QFrame[role="panel-header"] {{
background: {c['panel-header']};
border-top-left-radius: 8px;
border-top-right-radius: 8px;
border-bottom: 1px solid {c['border']};
}}
QFrame[role="stat-chip"] {{
background: {c['panel-header']};
border: 1px solid {c['border']};
border-radius: 6px;
}}
QPushButton {{
background: {c['panel-header']};
border: 1px solid {c['border']};
border-radius: 6px;
padding: 4px 10px;
color: {c['text']};
}}
QPushButton:hover {{
border-color: {c['accent']};
}}
QPushButton[active="true"] {{
border-color: {c['accent']};
color: {c['accent']};
}}
QPushButton[flat="true"] {{
background: transparent;
border: none;
color: {c['text-dim']};
}}
QProgressBar {{
background: {c['track']};
border: none;
border-radius: 4px;
text-align: center;
color: {c['text']};
height: 10px;
}}
QProgressBar::chunk {{
border-radius: 4px;
}}
QTableWidget {{
background: {c['panel']};
gridline-color: {c['border']};
border: none;
selection-background-color: {c['accent']};
}}
QHeaderView::section {{
background: {c['panel-header']};
color: {c['text-dim']};
border: none;
border-bottom: 1px solid {c['border']};
padding: 4px;
}}
QScrollBar:vertical {{
background: {c['bg']};
width: 12px;
}}
QScrollBar::handle:vertical {{
background: {c['border']};
border-radius: 6px;
min-height: 24px;
}}
"""
@@ -0,0 +1,188 @@
"""Small reusable building blocks used across every panel."""
from __future__ import annotations
from PySide6.QtCore import Signal
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QProgressBar,
QPushButton,
QSizePolicy,
QVBoxLayout,
QWidget,
)
def style_role(widget: QWidget, role: str) -> QWidget:
"""Sets the `role` dynamic property the app.qss selectors key off of."""
widget.setProperty("role", role)
return widget
def clear_layout(layout) -> None:
"""Empties a layout so it can be rebuilt from scratch on the next poll
tick.
Removing a widget from a layout with ``takeAt()`` does NOT hide it -
it keeps painting at its last geometry until ``deleteLater()``'s
deferred deletion actually runs on a later event-loop pass. Since every
dynamic list in this app (fill units, implements, storage cards, farm
rows, forecast days, ...) gets cleared and rebuilt on every ~500ms poll
tick, that lag would show up as visible flicker/ghosting. Hiding the
widget immediately (synchronous, cheap) avoids that; deleteLater()
still runs afterwards to actually free it.
"""
while layout.count():
item = layout.takeAt(0)
w = item.widget()
if w is not None:
w.hide()
w.deleteLater()
class StatChip(QFrame):
"""One "stat-chip": small label on top, bold value below."""
def __init__(self, label: str, parent=None) -> None:
super().__init__(parent)
style_role(self, "stat-chip")
layout = QVBoxLayout(self)
layout.setContentsMargins(8, 5, 8, 5)
layout.setSpacing(1)
self.label = QLabel(label)
style_role(self.label, "stat-label")
layout.addWidget(self.label)
self.value = QLabel("–")
style_role(self.value, "stat-value")
self.value.setWordWrap(True)
layout.addWidget(self.value)
def set_value(self, text: str) -> None:
self.value.setText(text)
class LabeledBar(QWidget):
"""Label row (name + value text) + a colored progress bar underneath."""
def __init__(self, label: str, color: str, parent=None) -> None:
super().__init__(parent)
self._color = color
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(3)
row = QHBoxLayout()
row.setContentsMargins(0, 0, 0, 0)
self.name_label = QLabel(label)
style_role(self.name_label, "stat-label")
row.addWidget(self.name_label)
row.addStretch(1)
self.value_label = QLabel("–")
style_role(self.value_label, "stat-label")
row.addWidget(self.value_label)
layout.addLayout(row)
self.bar = QProgressBar()
self.bar.setRange(0, 1000)
self.bar.setValue(0)
self.bar.setTextVisible(False)
self.bar.setFixedHeight(10)
layout.addWidget(self.bar)
self._apply_color(color)
def _apply_color(self, color: str) -> None:
self.bar.setStyleSheet(f"QProgressBar::chunk {{ background: {color}; }}")
def set_label(self, label: str) -> None:
self.name_label.setText(label)
def set_value(self, text: str, pct: float, color: str | None = None) -> None:
self.value_label.setText(text)
self.bar.setValue(int(max(0.0, min(100.0, pct)) * 10))
if color and color != self._color:
self._color = color
self._apply_color(color)
class PanelHeader(QFrame):
"""Header bar of a collapsible panel: title, optional subtitle/extra
widgets, a collapse toggle."""
toggled = Signal(bool)
def __init__(self, title: str, parent=None) -> None:
super().__init__(parent)
style_role(self, "panel-header")
self.layout = QHBoxLayout(self)
self.layout.setContentsMargins(10, 6, 8, 6)
self.layout.setSpacing(8)
self.title_label = QLabel(title)
style_role(self.title_label, "panel-title")
self.layout.addWidget(self.title_label)
self.sub_label = QLabel("")
style_role(self.sub_label, "panel-sub")
self.layout.addWidget(self.sub_label)
self.layout.addStretch(1)
self._collapsed = False
self.toggle_btn = QPushButton("▾")
self.toggle_btn.setProperty("flat", "true")
self.toggle_btn.setFixedWidth(24)
self.toggle_btn.clicked.connect(self._on_toggle_clicked)
self.layout.addWidget(self.toggle_btn)
def insert_extra(self, widget: QWidget) -> None:
# inserted just before the stretch/toggle so it sits next to the title
self.layout.insertWidget(self.layout.count() - 2, widget)
def _on_toggle_clicked(self) -> None:
self.set_collapsed(not self._collapsed)
self.toggled.emit(self._collapsed)
def set_collapsed(self, collapsed: bool) -> None:
self._collapsed = collapsed
self.toggle_btn.setText("▸" if collapsed else "▾")
class CollapsiblePanel(QFrame):
"""A QGroupBox-like panel with a header (title + collapse toggle) and a
body widget, matching the `.panel[data-panel-id]` behaviour in the web
version (collapsed state persisted via QSettings by the caller)."""
collapsed_changed = Signal(bool)
def __init__(self, panel_id: str, title: str, parent=None) -> None:
super().__init__(parent)
self.panel_id = panel_id
style_role(self, "panel")
self.setObjectName("panel_" + panel_id)
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
self.header = PanelHeader(title, self)
self.header.toggled.connect(self._on_header_toggled)
outer.addWidget(self.header)
self.body = QWidget(self)
self.body_layout = QVBoxLayout(self.body)
self.body_layout.setContentsMargins(12, 10, 12, 12)
self.body_layout.setSpacing(8)
outer.addWidget(self.body)
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum)
def set_collapsed(self, collapsed: bool) -> None:
self.header.set_collapsed(collapsed)
self.body.setVisible(not collapsed)
def _on_header_toggled(self, collapsed: bool) -> None:
self.body.setVisible(not collapsed)
self.collapsed_changed.emit(collapsed)
@@ -0,0 +1,131 @@
"""Farm panel: name/money/farmland stats, other farms, own farmland list.
Mirrors `renderFarm` + `renderPlayerStatus`."""
from __future__ import annotations
from typing import Optional
from PySide6.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout, QWidget
from formatting import format_euro, is_number
from widgets.common import CollapsiblePanel, StatChip, clear_layout, style_role
class FarmPanel(CollapsiblePanel):
def __init__(self, parent=None) -> None:
super().__init__("farm", "Betrieb", parent)
chip_row = QHBoxLayout()
self.name_chip = StatChip("Betrieb")
self.money_chip = StatChip("Kontostand")
self.farmland_count_chip = StatChip("Eigene Grundstücke")
self.farmland_value_chip = StatChip("Grundstückswert")
self.player_status_chip = StatChip("Spielerstatus")
for chip in (
self.name_chip,
self.money_chip,
self.farmland_count_chip,
self.farmland_value_chip,
self.player_status_chip,
):
chip_row.addWidget(chip)
self.body_layout.addLayout(chip_row)
self.other_farms_head = QLabel("Andere Betriebe")
style_role(self.other_farms_head, "stat-label")
self.other_farms_head.hide()
self.body_layout.addWidget(self.other_farms_head)
self.other_farms_list = QVBoxLayout()
self.body_layout.addLayout(self.other_farms_list)
farmland_head = QLabel("Eigene Grundstücke")
style_role(farmland_head, "stat-label")
self.body_layout.addWidget(farmland_head)
self.farmland_list = QVBoxLayout()
self.body_layout.addLayout(self.farmland_list)
@staticmethod
def _row(name: str, value: str) -> QWidget:
# Wrapped in a QWidget (not a bare QHBoxLayout) so a single
# addWidget()/clear_layout() pair in render_farm() can add and later
# remove it as one unit - a layout added via addLayout() can't be
# torn back down that way (clear_layout only knows how to hide
# *widgets* it finds via item.widget()), which would otherwise leave
# every farmland/other-farm row from every past render's data
# stacked on screen forever.
row = QWidget()
row_layout = QHBoxLayout(row)
row_layout.setContentsMargins(0, 0, 0, 0)
name_lbl = QLabel(name)
value_lbl = QLabel(value)
row_layout.addWidget(name_lbl)
row_layout.addStretch(1)
row_layout.addWidget(value_lbl)
return row
def render_player_status(self, player: Optional[dict]) -> None:
if not player:
self.player_status_chip.set_value("–")
return
if player.get("isControllingVehicle"):
self.player_status_chip.set_value("im Fahrzeug")
elif is_number(player.get("x")) and is_number(player.get("z")):
self.player_status_chip.set_value(f"zu Fuß ({round(player['x'])}, {round(player['z'])})")
else:
self.player_status_chip.set_value("zu Fuß")
def render_farm(self, mission: Optional[dict], farmlands: Optional[list], farms: Optional[list]) -> None:
clear_layout(self.other_farms_list)
clear_layout(self.farmland_list)
if not mission:
self.name_chip.set_value("–")
self.money_chip.set_value("–")
self.farmland_count_chip.set_value("–")
self.farmland_value_chip.set_value("–")
self.other_farms_head.hide()
self.farmland_list.addWidget(self._muted("– keine –"))
return
farm_arr = farms or []
name = mission.get("farmName") or f"Betrieb #{mission.get('farmId', '–')}"
if len(farm_arr) > 1:
name += f" (von {len(farm_arr)} Betrieben)"
self.name_chip.set_value(name)
self.money_chip.set_value(format_euro(mission.get("money")))
owned = [
f for f in (farmlands or [])
if f.get("isOwned") and f.get("farmId") == mission.get("farmId")
]
self.farmland_count_chip.set_value(str(len(owned)) if owned else "–")
total_value = sum(f.get("price") or 0 for f in owned)
self.farmland_value_chip.set_value(format_euro(total_value) if owned else "–")
others = [f for f in farm_arr if f.get("id") != mission.get("farmId")]
self.other_farms_head.setVisible(bool(others))
for f in others:
self.other_farms_list.addWidget(
self._row(
f.get("name") or f"Betrieb #{f.get('id')}",
format_euro(f.get("money")) if is_number(f.get("money")) else "–",
)
)
if not owned:
self.farmland_list.addWidget(self._muted("– keine –"))
else:
for f in owned:
self.farmland_list.addWidget(
self._row(
f.get("name") or f"Grundstück #{f.get('id')}",
format_euro(f.get("price")) if is_number(f.get("price")) else "–",
)
)
@staticmethod
def _muted(text: str) -> QLabel:
lbl = QLabel(text)
style_role(lbl, "stat-label")
return lbl
@@ -0,0 +1,86 @@
"""Half-circle arc gauge - native repaint of the SVG gauge in index.html
(`<path d="M20,100 A80,80 0 0 1 180,100" .../>`, a 180° arc)."""
from __future__ import annotations
from PySide6.QtCore import QRectF, Qt
from PySide6.QtGui import QColor, QFont, QPainter, QPen
from PySide6.QtWidgets import QSizePolicy, QWidget
class GaugeWidget(QWidget):
def __init__(self, unit: str, caption: str, accent: str, parent=None) -> None:
super().__init__(parent)
self._unit = unit
self._caption = caption
self._accent = QColor(accent)
self._track_color = QColor("#3a4453")
self._text_color = QColor("#e7ecf3")
self._dim_color = QColor("#8b97a8")
self._fraction = 0.0
self._value_text = "0"
self.setMinimumSize(150, 130)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
def set_colors(self, track: str, text: str, dim: str) -> None:
self._track_color = QColor(track)
self._text_color = QColor(text)
self._dim_color = QColor(dim)
self.update()
def set_value(self, fraction: float, value_text: str) -> None:
self._fraction = max(0.0, min(1.0, fraction))
self._value_text = value_text
self.update()
def sizeHint(self):
return self.minimumSize()
def paintEvent(self, event) -> None: # noqa: N802 (Qt override)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
w = self.width()
h = self.height()
# Gauge art-board is 200x155 in the original SVG - scale to fit width,
# keep it centered horizontally, anchored to the top.
scale = min(w / 200.0, (h - 22) / 155.0) if h > 22 else w / 200.0
scale = max(scale, 0.1)
painter.translate((w - 200 * scale) / 2.0, 0)
painter.scale(scale, scale)
rect = QRectF(20, 20, 160, 160) # bounding box of the r=80 circle at (100,100)
pen_width = 14
track_pen = QPen(self._track_color, pen_width, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap)
painter.setPen(track_pen)
# Qt angles: 0 = 3 o'clock, positive = counter-clockwise, in 1/16th deg.
# The arc goes from 180° (9 o'clock) to 0° (3 o'clock) along the top.
painter.drawArc(rect, 180 * 16, -180 * 16)
if self._fraction > 0.01:
fill_pen = QPen(self._accent, pen_width, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap)
painter.setPen(fill_pen)
span = -180 * self._fraction
painter.drawArc(rect, 180 * 16, int(span * 16))
painter.setPen(self._text_color)
value_font = QFont()
value_font.setPointSizeF(22)
value_font.setWeight(QFont.Weight.DemiBold)
painter.setFont(value_font)
painter.drawText(QRectF(0, 95, 200, 34), Qt.AlignmentFlag.AlignCenter, self._value_text)
painter.setPen(self._dim_color)
unit_font = QFont()
unit_font.setPointSizeF(11)
painter.setFont(unit_font)
painter.drawText(QRectF(0, 128, 200, 20), Qt.AlignmentFlag.AlignCenter, self._unit)
painter.resetTransform()
painter.setPen(self._dim_color)
cap_font = QFont()
cap_font.setPointSizeF(11)
painter.setFont(cap_font)
painter.drawText(
0, int(h - 6), w, 18, Qt.AlignmentFlag.AlignHCenter, self._caption
)
@@ -0,0 +1,51 @@
"""60-second speed sparkline - native repaint of the `#speedHistory` canvas."""
from __future__ import annotations
import time
from PySide6.QtGui import QColor, QPainter, QPen
from PySide6.QtWidgets import QWidget
WINDOW_S = 60.0
class SpeedHistoryWidget(QWidget):
def __init__(self, accent: str, parent=None) -> None:
super().__init__(parent)
self._accent = QColor(accent)
self._points: list[tuple[float, float]] = []
self.setMinimumHeight(48)
def set_accent(self, accent: str) -> None:
self._accent = QColor(accent)
self.update()
def set_points(self, points: list[tuple[float, float]]) -> None:
self._points = points
self.update()
def paintEvent(self, event) -> None: # noqa: N802
if len(self._points) < 2:
return
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
w = self.width()
h = self.height()
now = time.monotonic()
max_v = max(20.0, max(p[1] for p in self._points))
pen = QPen(self._accent, 2)
painter.setPen(pen)
path_points = []
for t, v in self._points:
fx = 1 - (now - t) / WINDOW_S
x = fx * w
y = h - (v / max_v) * (h - 4) - 2
path_points.append((x, y))
for i in range(1, len(path_points)):
x0, y0 = path_points[i - 1]
x1, y1 = path_points[i]
painter.drawLine(int(x0), int(y0), int(x1), int(y1))
@@ -0,0 +1,153 @@
"""Storage panel: silos, husbandries, productions. Mirrors `renderStorage`."""
from __future__ import annotations
from typing import Optional
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QVBoxLayout
from formatting import (
PRODUCTION_STATUS_LABELS,
farm_suffix,
format_liters,
is_number,
production_status_ok,
)
from widgets.common import CollapsiblePanel, clear_layout, style_role
class StoragePanel(CollapsiblePanel):
def __init__(self, parent=None) -> None:
super().__init__("storage", "Lager, Tierhaltung & Produktion", parent)
self.body_layout.addWidget(self._head("Silos"))
self.silo_list = QVBoxLayout()
self.silo_list.setSpacing(6)
self.body_layout.addLayout(self.silo_list)
self.body_layout.addWidget(self._head("Ställe"))
self.husbandry_list = QVBoxLayout()
self.husbandry_list.setSpacing(6)
self.body_layout.addLayout(self.husbandry_list)
self.body_layout.addWidget(self._head("Produktionen"))
self.production_list = QVBoxLayout()
self.production_list.setSpacing(6)
self.body_layout.addLayout(self.production_list)
@staticmethod
def _head(text: str) -> QLabel:
lbl = QLabel(text)
lbl.setStyleSheet("font-weight: 600; margin-top: 4px;")
return lbl
@staticmethod
def _muted(text: str) -> QLabel:
lbl = QLabel(text)
style_role(lbl, "stat-label")
return lbl
@staticmethod
def _card() -> tuple[QFrame, QVBoxLayout]:
card = QFrame()
style_role(card, "stat-chip")
layout = QVBoxLayout(card)
layout.setContentsMargins(10, 8, 10, 8)
layout.setSpacing(3)
return card, layout
@staticmethod
def _fill_row(name: str, value: str):
row = QHBoxLayout()
row.addWidget(QLabel(name))
row.addStretch(1)
row.addWidget(QLabel(value))
return row
def render_storage(
self,
silos: Optional[list],
husbandries: Optional[list],
productions: Optional[list],
farms: Optional[list],
) -> None:
show_farm_badge = bool(farms) and len(farms) > 1
clear_layout(self.silo_list)
filled_silos = [s for s in (silos or []) if s.get("fillTypes")]
if not filled_silos:
self.silo_list.addWidget(self._muted("– keine befüllten Silos –"))
else:
for silo in filled_silos:
card, layout = self._card()
name_lbl = QLabel((silo.get("name") or "Unbenannt") + farm_suffix(silo.get("ownerFarmId"), show_farm_badge))
name_lbl.setStyleSheet("font-weight: 600;")
layout.addWidget(name_lbl)
for ft in silo.get("fillTypes") or []:
level = ft.get("fillLevel") if is_number(ft.get("fillLevel")) else 0
layout.addLayout(self._fill_row(ft.get("fillTypeName") or "Unbekannt", f"{format_liters(level)} l"))
self.silo_list.addWidget(card)
clear_layout(self.husbandry_list)
husbandry_arr = husbandries or []
if not husbandry_arr:
self.husbandry_list.addWidget(self._muted("– keine –"))
else:
for h in husbandry_arr:
card, layout = self._card()
name_lbl = QLabel((h.get("name") or "Unbenannt") + farm_suffix(h.get("ownerFarmId"), show_farm_badge))
name_lbl.setStyleSheet("font-weight: 600;")
layout.addWidget(name_lbl)
count = h.get("numAnimals") if is_number(h.get("numAnimals")) else "–"
max_n = f" / {h.get('maxNumAnimals')}" if is_number(h.get("maxNumAnimals")) else ""
count_lbl = QLabel(f"{count}{max_n}")
count_lbl.setStyleSheet("font-size: 18px; font-weight: 700;")
layout.addWidget(count_lbl)
layout.addWidget(self._muted("Tiere"))
self.husbandry_list.addWidget(card)
clear_layout(self.production_list)
production_arr = productions or []
if not production_arr:
self.production_list.addWidget(self._muted("– keine –"))
else:
for p in production_arr:
card, layout = self._card()
name_lbl = QLabel((p.get("name") or "Unbenannt") + farm_suffix(p.get("ownerFarmId"), show_farm_badge))
name_lbl.setStyleSheet("font-weight: 600;")
layout.addWidget(name_lbl)
for r in p.get("recipes") or []:
head_row = QHBoxLayout()
head_row.addWidget(QLabel(r.get("name") or "Rezept"))
head_row.addStretch(1)
status_name = r.get("statusName")
status_label = PRODUCTION_STATUS_LABELS.get(status_name, status_name or "")
if status_label:
status_lbl = QLabel(status_label)
ok = production_status_ok(status_name)
if ok is True:
status_lbl.setStyleSheet("color: #3ecf7a; font-weight: 600;")
elif ok is False:
status_lbl.setStyleSheet("color: #e8b93f; font-weight: 600;")
head_row.addWidget(status_lbl)
layout.addLayout(head_row)
inputs_text = " + ".join(
(i.get("fillTypeName") or "?") + (f" ({i.get('amount')})" if is_number(i.get("amount")) else "")
for i in (r.get("inputs") or [])
) or "–"
outputs_text = " + ".join(
(o.get("fillTypeName") or "?") + (f" ({o.get('amount')})" if is_number(o.get("amount")) else "")
for o in (r.get("outputs") or [])
) or "–"
flow_lbl = self._muted(f"{inputs_text} → {outputs_text}")
layout.addWidget(flow_lbl)
contents = p.get("contents") or []
if contents:
layout.addWidget(self._head("Lagerbestand"))
for c in contents:
level = c.get("fillLevel") if is_number(c.get("fillLevel")) else 0
layout.addLayout(self._fill_row(c.get("fillTypeName") or "Unbekannt", f"{format_liters(level)} l"))
self.production_list.addWidget(card)
@@ -0,0 +1,66 @@
"""Time panel: clock, day, season, timescale. Mirrors `renderTime`."""
from __future__ import annotations
from typing import Optional
from PySide6.QtWidgets import QHBoxLayout, QLabel
from formatting import is_number
from widgets.common import CollapsiblePanel, style_role
class TimePanel(CollapsiblePanel):
def __init__(self, parent=None) -> None:
super().__init__("time", "Zeit", parent)
self.clock_label = QLabel("--:--")
self.clock_label.setStyleSheet("font-size: 34px; font-weight: 700;")
self.body_layout.addWidget(self.clock_label)
sub_row = QHBoxLayout()
self.day_label = QLabel("Tag –")
self.season_label = QLabel("")
self.period_label = QLabel("")
self.scale_label = QLabel("")
for lbl in (self.day_label, self.season_label, self.period_label, self.scale_label):
style_role(lbl, "stat-label")
sub_row.addWidget(lbl)
sub_row.addStretch(1)
self.body_layout.addLayout(sub_row)
def render_time(self, time_data: Optional[dict]) -> None:
if not time_data:
self.clock_label.setText("--:--")
self.day_label.setText("Tag –")
self.season_label.setText("")
self.period_label.setText("")
self.scale_label.setText("")
return
minutes = None
day_time_minutes = time_data.get("dayTimeMinutes")
current_hour = time_data.get("currentHour")
if is_number(day_time_minutes):
minutes = day_time_minutes / 60000 if day_time_minutes > 1440 else day_time_minutes
elif is_number(current_hour):
minutes = current_hour * 60
if minutes is not None:
minutes = ((minutes % 1440) + 1440) % 1440
hh = int(minutes // 60)
mm = int(minutes % 60)
self.clock_label.setText(f"{hh:02d}:{mm:02d}")
else:
self.clock_label.setText("--:--")
current_day = time_data.get("currentDay")
self.day_label.setText(f"Tag {current_day}" if is_number(current_day) else "Tag –")
season = time_data.get("currentSeason")
self.season_label.setText(f"Saison {season}" if season is not None else "")
days_per_period = time_data.get("daysPerPeriod")
self.period_label.setText(f"({days_per_period} Tage/Saison)" if is_number(days_per_period) else "")
time_scale = time_data.get("timeScale")
self.scale_label.setText(f"{time_scale}× Zeitraffer" if is_number(time_scale) else "")
@@ -0,0 +1,65 @@
"""Top bar: brand, connection status, map id, theme + fullscreen toggles."""
from __future__ import annotations
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton
from widgets.common import style_role
class TopBar(QFrame):
theme_toggle_requested = Signal()
fullscreen_toggle_requested = Signal()
def __init__(self, parent=None) -> None:
super().__init__(parent)
style_role(self, "panel-header")
layout = QHBoxLayout(self)
layout.setContentsMargins(14, 8, 14, 8)
layout.setSpacing(10)
brand = QLabel("FS25")
brand.setStyleSheet("font-weight: 800; font-size: 15px;")
layout.addWidget(brand)
title = QLabel("Live Dashboard")
style_role(title, "panel-title")
layout.addWidget(title)
self.map_id_label = QLabel("")
style_role(self.map_id_label, "panel-sub")
layout.addWidget(self.map_id_label)
layout.addStretch(1)
self.status_dot = QLabel("●")
self.status_dot.setStyleSheet("color: #ff5d5d; font-size: 14px;")
layout.addWidget(self.status_dot)
self.status_label = QLabel("Verbinde…")
style_role(self.status_label, "panel-sub")
layout.addWidget(self.status_label)
self.theme_btn = QPushButton("🌓")
self.theme_btn.setToolTip("Hell/Dunkel umschalten")
self.theme_btn.clicked.connect(self.theme_toggle_requested.emit)
layout.addWidget(self.theme_btn)
self.fullscreen_btn = QPushButton("⛶")
self.fullscreen_btn.setToolTip("Vollbild")
self.fullscreen_btn.clicked.connect(self.fullscreen_toggle_requested.emit)
layout.addWidget(self.fullscreen_btn)
def set_status(self, live: bool, waiting: bool) -> None:
if live:
self.status_dot.setStyleSheet("color: #3ecf7a; font-size: 14px;")
self.status_label.setText("Live")
elif waiting:
self.status_dot.setStyleSheet("color: #e8b93f; font-size: 14px;")
self.status_label.setText("Warte auf Spiel…")
else:
self.status_dot.setStyleSheet("color: #ff5d5d; font-size: 14px;")
self.status_label.setText("Keine Verbindung")
def set_map_id(self, map_id: str) -> None:
self.map_id_label.setText(f"· {map_id}" if map_id else "")
@@ -0,0 +1,301 @@
"""Selected-vehicle panel: gauges, cruise/motor/load, hours/price, fuel/
damage/dirt bars, own fill units, attached implements (recursive chain),
60s speed sparkline. Mirrors `renderSelectedVehicle` + friends in app.js."""
from __future__ import annotations
from typing import Any, Optional
from PySide6.QtCore import Signal
from PySide6.QtWidgets import (
QHBoxLayout,
QLabel,
QPushButton,
QVBoxLayout,
QWidget,
)
from formatting import format_euro, format_number, is_drivable, is_number
from state import AppState
from widgets.common import CollapsiblePanel, LabeledBar, StatChip, clear_layout, style_role
from widgets.gauge import GaugeWidget
from widgets.speed_history import SpeedHistoryWidget
class FillUnitRow(LabeledBar):
pass
class ImplementCard(QWidget):
def __init__(self, name: str, depth: int, parent=None) -> None:
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(depth * 16, 4, 0, 4)
layout.setSpacing(4)
prefix = "↳ " if depth > 0 else ""
name_label = QLabel(prefix + name)
name_label.setStyleSheet("font-weight: 600;")
layout.addWidget(name_label)
self.body_layout = layout
def add_no_tank(self) -> None:
lbl = QLabel("kein Tank")
style_role(lbl, "stat-label")
self.body_layout.addWidget(lbl)
def add_fill_bar(self, name: str, level: float, capacity: float, accent: str) -> None:
pct = min(100.0, max(0.0, (level / capacity) * 100)) if capacity else 0.0
bar = LabeledBar(name, accent)
bar.set_value(f"{round(level)} / {round(capacity)} l ({round(pct)}%)", pct)
self.body_layout.addWidget(bar)
class VehiclePanel(CollapsiblePanel):
vehicle_selected = Signal(object) # emitted for the "follow my vehicle" button
follow_requested = Signal()
ACCENT_SPEED = "#4da3ff"
ACCENT_RPM = "#ff9f4d"
FUEL_COLOR = "#4da3ff"
DAMAGE_COLOR = "#ff5d5d"
DIRT_COLOR = "#9a7b4f"
def __init__(self, parent=None) -> None:
super().__init__("vehicle", "Kein Fahrzeug ausgewählt", parent)
self.header.sub_label.setText("")
self.follow_btn = QPushButton("📍 Mein Fahrzeug")
self.follow_btn.setProperty("flat", "true")
self.follow_btn.clicked.connect(self.follow_requested.emit)
self.header.insert_extra(self.follow_btn)
self.manual_hint = QLabel(
"🔒 manuell ausgewählt – klicke „Mein Fahrzeug“ um wieder automatisch zu folgen"
)
style_role(self.manual_hint, "stat-label")
self.manual_hint.setWordWrap(True)
self.manual_hint.hide()
self.body_layout.addWidget(self.manual_hint)
gauge_row = QHBoxLayout()
self.speed_gauge = GaugeWidget("km/h", "Geschwindigkeit", self.ACCENT_SPEED)
self.rpm_gauge = GaugeWidget("U/min", "Drehzahl", self.ACCENT_RPM)
gauge_row.addWidget(self.speed_gauge)
gauge_row.addWidget(self.rpm_gauge)
self.body_layout.addLayout(gauge_row)
stat_row_1 = QHBoxLayout()
self.cruise_chip = StatChip("Tempomat")
self.motor_chip = StatChip("Motor")
self.load_chip = StatChip("Last")
for chip in (self.cruise_chip, self.motor_chip, self.load_chip):
stat_row_1.addWidget(chip)
self.body_layout.addLayout(stat_row_1)
stat_row_2 = QHBoxLayout()
self.hours_chip = StatChip("Betriebsstunden")
self.price_chip = StatChip("Neuwert")
self.sell_price_chip = StatChip("Verkaufswert")
for chip in (self.hours_chip, self.price_chip, self.sell_price_chip):
stat_row_2.addWidget(chip)
self.body_layout.addLayout(stat_row_2)
stat_row_3 = QHBoxLayout()
self.position_chip = StatChip("Position")
self.heading_chip = StatChip("Ausrichtung")
for chip in (self.position_chip, self.heading_chip):
stat_row_3.addWidget(chip)
self.body_layout.addLayout(stat_row_3)
bar_row = QHBoxLayout()
self.fuel_bar = LabeledBar("Tank", self.FUEL_COLOR)
self.damage_bar = LabeledBar("Schaden", self.DAMAGE_COLOR)
self.dirt_bar = LabeledBar("Verschmutzung", self.DIRT_COLOR)
for bar in (self.fuel_bar, self.damage_bar, self.dirt_bar):
bar_row.addWidget(bar)
self.body_layout.addLayout(bar_row)
self.body_layout.addWidget(self._section_label("Eigene Ladung / Behälter"))
self.own_fill_container = QVBoxLayout()
self.own_fill_container.setSpacing(6)
self.body_layout.addLayout(self.own_fill_container)
self.body_layout.addWidget(self._section_label("Angekoppelte Geräte"))
self.implements_container = QVBoxLayout()
self.implements_container.setSpacing(6)
self.body_layout.addLayout(self.implements_container)
self.body_layout.addWidget(self._section_label("Geschwindigkeit (letzte 60s)"))
self.speed_history_widget = SpeedHistoryWidget(self.ACCENT_SPEED)
self.body_layout.addWidget(self.speed_history_widget)
self.render_selected(None, [], AppState())
@staticmethod
def _section_label(text: str) -> QLabel:
lbl = QLabel(text)
style_role(lbl, "stat-label")
return lbl
def render_selected(self, vehicle: Optional[dict], vehicles: list[dict], app_state: AppState) -> None:
self.manual_hint.setVisible(not app_state.follow_my_vehicle)
self.follow_btn.setProperty("active", "true" if app_state.follow_my_vehicle else "false")
self.follow_btn.style().unpolish(self.follow_btn)
self.follow_btn.style().polish(self.follow_btn)
if vehicle is None:
self.header.title_label.setText("Kein Fahrzeug ausgewählt")
self.header.sub_label.setText("")
self.speed_gauge.set_value(0, "0")
self.rpm_gauge.set_value(0, "0")
self.cruise_chip.set_value("aus")
self.motor_chip.set_value("–")
self.load_chip.set_value("–")
self.hours_chip.set_value("–")
self.price_chip.set_value("–")
self.sell_price_chip.set_value("–")
self.position_chip.set_value("–")
self.heading_chip.set_value("–")
self.fuel_bar.set_value("–", 0)
self.damage_bar.set_value("–", 0)
self.dirt_bar.set_value("–", 0)
self._render_own_fill_units(None)
self._render_implements(None, vehicles)
self.speed_history_widget.set_points([])
return
self.header.title_label.setText(vehicle.get("name") or "Unbenannt")
self.header.sub_label.setText(vehicle.get("typeName") or "")
vehicle_is_drivable = is_drivable(vehicle)
speed = max(0.0, vehicle.get("speedKmh") or 0.0) if vehicle_is_drivable and is_number(vehicle.get("speedKmh")) else 0.0
speed_max = max(60.0, ((int(speed) // 20) + 1) * 20)
self.speed_gauge.set_value(speed / speed_max if speed_max else 0, format_number(speed, 0) if vehicle_is_drivable else "–")
rpm_fraction = (vehicle.get("rpmPercent") or 0) / 100 if is_number(vehicle.get("rpmPercent")) else 0
self.rpm_gauge.set_value(rpm_fraction, format_number(vehicle.get("rpm"), 0))
if vehicle.get("cruiseControlActive"):
max_text = ""
if is_number(vehicle.get("cruiseControlMaxSpeed")):
max_text = f" (max {format_number(vehicle.get('cruiseControlMaxSpeed'), 0)})"
self.cruise_chip.set_value(
f"an · {format_number(vehicle.get('cruiseControlSpeed'), 0)} km/h{max_text}"
)
else:
self.cruise_chip.set_value("aus")
motor_started = vehicle.get("motorStarted")
if isinstance(motor_started, bool):
self.motor_chip.set_value("läuft" if motor_started else "aus")
else:
self.motor_chip.set_value("–")
load = vehicle.get("motorLoadPercent")
self.load_chip.set_value(f"{round(load)}%" if is_number(load) else "–")
fuel_level = vehicle.get("fuelLevel")
fuel_capacity = vehicle.get("fuelCapacity")
if is_number(fuel_level) and is_number(fuel_capacity) and fuel_capacity > 0:
pct = (fuel_level / fuel_capacity) * 100
fuel_units = vehicle.get("fillUnits") or []
fuel_unit = next((fu for fu in fuel_units if fu.get("fillTypeId") == vehicle.get("fuelType")), None)
fuel_name = f"{fuel_unit.get('fillTypeName')}: " if fuel_unit and fuel_unit.get("fillTypeName") else ""
self.fuel_bar.set_value(
f"{fuel_name}{round(fuel_level)} / {round(fuel_capacity)} l ({round(pct)}%)", pct
)
else:
self.fuel_bar.set_value("–", 0)
damage = vehicle.get("damagePercent")
if is_number(damage):
pct = min(100.0, max(0.0, damage))
self.damage_bar.set_value(f"{round(pct)}%", pct)
else:
self.damage_bar.set_value("–", 0)
dirt = vehicle.get("dirtPercent")
if is_number(dirt):
pct = min(100.0, max(0.0, dirt))
self.dirt_bar.set_value(f"{round(pct)}%", pct)
else:
self.dirt_bar.set_value("–", 0)
hours = vehicle.get("operatingHours")
self.hours_chip.set_value(f"{format_number(hours, 1)} h" if is_number(hours) else "–")
self.price_chip.set_value(format_euro(vehicle.get("price")))
self.sell_price_chip.set_value(format_euro(vehicle.get("sellPrice")))
x, z = vehicle.get("x"), vehicle.get("z")
self.position_chip.set_value(f"{round(x)}, {round(z)}" if is_number(x) and is_number(z) else "–")
heading = vehicle.get("headingRad")
if is_number(heading):
import math
deg = ((heading * 180 / math.pi) % 360 + 360) % 360
self.heading_chip.set_value(f"{round(deg)}°")
else:
self.heading_chip.set_value("–")
self._render_own_fill_units(vehicle)
self._render_implements(vehicle, vehicles)
app_state.push_speed_history(speed)
self.speed_history_widget.set_points(list(app_state.speed_history))
def _render_own_fill_units(self, vehicle: Optional[dict]) -> None:
clear_layout(self.own_fill_container)
fill_units = (vehicle.get("fillUnits") if vehicle else None) or []
fuel_type = vehicle.get("fuelType") if vehicle else None
relevant = [
fu
for fu in fill_units
if is_number(fu.get("capacity")) and fu.get("capacity") > 0
and not (fuel_type is not None and fu.get("fillTypeId") == fuel_type)
]
if not relevant:
lbl = self._section_label("– keine –")
self.own_fill_container.addWidget(lbl)
return
for fu in relevant:
level = fu.get("fillLevel") if is_number(fu.get("fillLevel")) else 0
capacity = fu.get("capacity")
pct = min(100.0, max(0.0, (level / capacity) * 100)) if capacity else 0.0
bar = LabeledBar(fu.get("fillTypeName") or "Unbekannt", self.ACCENT_SPEED)
bar.set_value(f"{round(level)} / {round(capacity)} l ({round(pct)}%)", pct)
self.own_fill_container.addWidget(bar)
def _render_implements(self, vehicle: Optional[dict], vehicles: list[dict]) -> None:
clear_layout(self.implements_container)
root_ids = (vehicle.get("attachedImplementIds") if vehicle else None) or []
if not root_ids:
self.implements_container.addWidget(self._section_label("– keine –"))
return
by_id = {v.get("id"): v for v in vehicles}
visited = {vehicle.get("id")} if vehicle else set()
def append_chain(implement_id: Any, depth: int) -> None:
if implement_id in visited:
return
visited.add(implement_id)
implement = by_id.get(implement_id)
card = ImplementCard(implement.get("name") if implement and implement.get("name") else "Unbekanntes Gerät", depth)
fill_units = (implement.get("fillUnits") if implement else None) or []
relevant = [fu for fu in fill_units if is_number(fu.get("capacity")) and fu.get("capacity") > 0]
if not relevant:
card.add_no_tank()
else:
for fu in relevant:
level = fu.get("fillLevel") if is_number(fu.get("fillLevel")) else 0
card.add_fill_bar(fu.get("fillTypeName") or "Unbekannt", level, fu.get("capacity"), self.ACCENT_SPEED)
self.implements_container.addWidget(card)
child_ids = (implement.get("attachedImplementIds") if implement else None) or []
for child_id in child_ids:
append_chain(child_id, depth + 1)
for root_id in root_ids:
append_chain(root_id, 0)
@@ -0,0 +1,79 @@
"""Vehicle table: all vehicles, sortable by name, click to select, damage
highlighted. Mirrors `renderVehicleTable`."""
from __future__ import annotations
from typing import Any
from PySide6.QtCore import Signal
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QAbstractItemView, QHeaderView, QTableWidget, QTableWidgetItem
from formatting import format_fuel, format_number, is_drivable, is_number
from widgets.common import CollapsiblePanel
COLUMNS = ["Name", "km/h", "U/min", "Tempomat", "Tank", "Schaden"]
class VehicleTablePanel(CollapsiblePanel):
vehicle_clicked = Signal(object)
def __init__(self, parent=None) -> None:
super().__init__("table", "Alle Fahrzeuge", parent)
self.header.sub_label.setText("0 Fahrzeuge")
self.table = QTableWidget(0, len(COLUMNS))
self.table.setHorizontalHeaderLabels(COLUMNS)
self.table.verticalHeader().setVisible(False)
self.table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
self.table.setMinimumHeight(220)
self.table.cellClicked.connect(self._on_cell_clicked)
self.body_layout.addWidget(self.table)
self._row_ids: list[Any] = []
def _on_cell_clicked(self, row: int, _col: int) -> None:
if 0 <= row < len(self._row_ids):
self.vehicle_clicked.emit(self._row_ids[row])
def render_table(self, vehicles: list[dict], selected_id: Any) -> None:
count = len(vehicles)
self.header.sub_label.setText(f"{count} Fahrzeug" if count == 1 else f"{count} Fahrzeuge")
sorted_vehicles = sorted(vehicles, key=lambda v: (v.get("name") or "").lower())
self._row_ids = [v.get("id") for v in sorted_vehicles]
self.table.setRowCount(max(1, len(sorted_vehicles)))
if not sorted_vehicles:
self.table.setSpan(0, 0, 1, len(COLUMNS))
item = QTableWidgetItem(
"Keine Fahrzeuge geladen – starte das Spiel mit dem WebDashboard-Mod und lade einen Spielstand."
)
self.table.setItem(0, 0, item)
return
self.table.setSpan(0, 0, 1, 1)
for row, v in enumerate(sorted_vehicles):
values = [
v.get("name") or "Unbenannt",
format_number(v.get("speedKmh"), 0) if is_drivable(v) else "–",
format_number(v.get("rpm"), 0),
(
f"an ({format_number(v.get('cruiseControlSpeed'), 0)})"
if v.get("cruiseControlActive")
else "–"
),
format_fuel(v),
f"{round(max(0, v.get('damagePercent')))}%" if is_number(v.get("damagePercent")) else "–",
]
for col, text in enumerate(values):
item = QTableWidgetItem(text)
if col == 5 and is_number(v.get("damagePercent")) and v.get("damagePercent") >= 50:
item.setForeground(QColor("#ff5d5d"))
self.table.setItem(row, col, item)
if v.get("id") == selected_id:
for col in range(len(COLUMNS)):
self.table.item(row, col).setSelected(True)
@@ -0,0 +1,118 @@
"""Weather panel: current weather, badges, forecast strip. Mirrors
`renderWeather`."""
from __future__ import annotations
from typing import Optional
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QVBoxLayout
from formatting import WEATHER_ICONS, WEATHER_LABELS_DE, is_number
from widgets.common import CollapsiblePanel, clear_layout, style_role
class WeatherPanel(CollapsiblePanel):
def __init__(self, parent=None) -> None:
super().__init__("weather", "Wetter", parent)
now_row = QHBoxLayout()
self.icon_label = QLabel("❓")
self.icon_label.setStyleSheet("font-size: 30px;")
now_row.addWidget(self.icon_label)
text_col = QVBoxLayout()
self.type_label = QLabel("Unbekannt")
self.type_label.setStyleSheet("font-weight: 600;")
text_col.addWidget(self.type_label)
self.temp_label = QLabel("")
style_role(self.temp_label, "stat-label")
text_col.addWidget(self.temp_label)
now_row.addLayout(text_col)
now_row.addStretch(1)
self.badges_row = QHBoxLayout()
now_row.addLayout(self.badges_row)
self.body_layout.addLayout(now_row)
self.extra_row = QHBoxLayout()
self.body_layout.addLayout(self.extra_row)
self.forecast_row = QHBoxLayout()
self.forecast_row.setSpacing(8)
self.body_layout.addLayout(self.forecast_row)
def render_weather(self, weather: Optional[dict], time_data: Optional[dict]) -> None:
clear_layout(self.badges_row)
clear_layout(self.extra_row)
clear_layout(self.forecast_row)
if not weather:
self.icon_label.setText("❓")
self.type_label.setText("Unbekannt")
self.temp_label.setText("")
self.forecast_row.addWidget(self._muted("Keine Wetterdaten vom Spiel verfügbar."))
return
name = weather.get("currentTypeName")
self.icon_label.setText(WEATHER_ICONS.get(name, "❓"))
self.type_label.setText(WEATHER_LABELS_DE.get(name, "Unbekannt"))
temp = weather.get("temperatureCelsius")
self.temp_label.setText(f"{round(temp)} °C" if is_number(temp) else "")
badges = []
if weather.get("isRaining"):
badges.append("🌧️ Regen")
if weather.get("isSnowing"):
badges.append("❄️ Schnee")
if time_data and time_data.get("isNight"):
badges.append("🌙 Nacht")
for text in badges:
badge = QFrame()
style_role(badge, "stat-chip")
layout = QHBoxLayout(badge)
layout.setContentsMargins(8, 3, 8, 3)
lbl = QLabel(text)
layout.addWidget(lbl)
self.badges_row.addWidget(badge)
rain_scale = weather.get("rainFallScale")
if weather.get("isRaining") and is_number(rain_scale):
self.extra_row.addWidget(self._muted(f"Regenintensität: {round(rain_scale * 100)}%"))
snow_height = weather.get("snowHeight")
if is_number(snow_height) and snow_height > 0.001:
self.extra_row.addWidget(self._muted(f"Schneehöhe: {snow_height:.2f} m"))
self.extra_row.addStretch(1)
forecast = weather.get("forecast") or []
if not forecast:
self.forecast_row.addWidget(self._muted("Keine Vorhersagedaten vom Spiel verfügbar."))
return
for f in forecast:
day = QFrame()
style_role(day, "stat-chip")
col = QVBoxLayout(day)
col.setContentsMargins(8, 6, 8, 6)
col.setSpacing(2)
label = QLabel(f"+{f.get('dayOffset')} Tag")
style_role(label, "stat-label")
col.addWidget(label)
icon = QLabel(WEATHER_ICONS.get(f.get("typeName"), "❓"))
icon.setStyleSheet("font-size: 20px;")
col.addWidget(icon)
min_t = f.get("minTemperatureCelsius")
max_t = f.get("maxTemperatureCelsius")
temp_text = f"{round(min_t)}° / {round(max_t)}°" if is_number(min_t) and is_number(max_t) else ""
temp_lbl = QLabel(temp_text)
col.addWidget(temp_lbl)
self.forecast_row.addWidget(day)
self.forecast_row.addStretch(1)
@staticmethod
def _muted(text: str) -> QLabel:
lbl = QLabel(text)
style_role(lbl, "stat-label")
return lbl