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
+16
View File
@@ -0,0 +1,16 @@
# Unrelated project in this working directory, not part of this repo
FS25-YoutubeRadio/
# Python virtual envs and caches
.venv/
__pycache__/
*.pyc
# Build/packaging output
build/
dist/
Output/
*.spec
# Personal desktop shortcuts (machine-specific, hardcoded local paths)
*.lnk
+133
View File
@@ -0,0 +1,133 @@
# FarmHUD
Eine schlanke, eigenständige Companion-App für **Farming Simulator 25** –
komplett anderes Design als [FS25-WebDashboard](../FS25-WebDashboard/README.md),
aber dieselbe Datenquelle (denselben Mod). Zeigt praktisch alles, was der
Mod liefert, als scrollbare Kachel-Spalte, **von oben nach unten nach
Nützlichkeit sortiert**:
1. **Direkt sichtbar, am wichtigsten:** aktuelles Fahrzeug, Kontostand,
Hofwert, Ingame-Zeit, rotierendes Easter Egg.
2. **Direkt sichtbar, oft gebraucht:** Fahrzeug-Details (Tempomat, Motor,
Tank, Schaden, Verschmutzung), angehängtes Gerät + Füllstand, Kredit,
Wetter + Vorschau, aktive Aufträge.
3. **Direkt sichtbar, gelegentlich gebraucht:** Verkaufspreise, Lager,
Tierhaltung, Mitspieler (nur bei Mehrspieler sichtbar).
4. **Eingeklappt unter "mehr anzeigen"** (technisch/selten gebraucht):
Sitzungseinstellungen, Spielstand-Metadaten, Fahrzeug-Technik
(Eigentümer, Ein/Aus, Lichter, …), Produktionsstatus, Feldübersicht.
Discord Rich Presence bleibt bewusst schlanker und zeigt nur eine
konfigurierbare Auswahl (Kontostand/Hofwert/Ingame-Zeit/Easter Egg im
Wechsel) – niemand braucht eine Kredit-Zeile im Discord-Profil.
```
FS25 (Mod: FS25_FarmHUD) --schreibt--> live.json --liest--> FarmHUD --Rich Presence--> Discord
```
FarmHUD braucht **denselben Mod** wie FS25-WebDashboard
(`FS25_FarmHUD`, siehe [dessen README](../FS25-WebDashboard/README.md)
für die Installation) – es ist keine zweite Mod-Installation nötig, nur
eine zweite Art, dieselben Live-Daten anzuzeigen.
## Design
Ein Trecker-Armaturenbrett, kein SaaS-Dashboard: warme Kohle-/Oliv-Töne statt
kühlem Grau, ein einziger Erntegold-Akzent (`#e2a63c`, aus dem App-Icon),
"Bahnschrift SemiBold" für Wortmarke/Überschriften und "Cascadia Mono" mit
Tabellen-Ziffern für alle Live-Messwerte (Geld, Zeit, Prozente) – wie eine
echte Digitalanzeige, nicht nur eingefärbter Fließtext. Beide Schriften
gehören seit Windows 10 zum System, keine zusätzliche Installation nötig.
Layout: eine breite "Cockpit"-Kachel für das aktuelle Fahrzeug oben, darunter
Kontostand/Hofwert/Ingame-Zeit als drei kleinere Gauge-Kacheln nebeneinander
– nutzt die Fensterbreite wie ein echtes Armaturenbrett statt vier gleiche
Balken übereinander zu stapeln. Fenster ist frei größenveränderbar und
maximierbar; der Inhalt bleibt dabei auf eine angenehme Lesebreite begrenzt
und zentriert. Eigenes App-Icon (grüne Ähren auf grünem Badge, unter
`app/assets/icon.ico`) – zeigt jetzt auch korrekt in der Windows-Taskleiste
(nicht mehr das generische Python-Symbol).
## Starten (aus dem Quellcode)
```bash
cd app
setup.bat # einmalig: Python-Umgebung + Abhängigkeiten
run.bat # danach jedes Mal
```
## Discord Rich Presence
In den Einstellungen (⚙-Button unten rechts im Fenster):
1. Haken bei "Discord-Status anzeigen" setzen.
2. Client ID ist bereits vorausgefüllt (`1548716147740778556` – deine
Discord-App aus dem [Developer Portal](https://discord.com/developers/applications)).
Falls du eine andere App nutzen willst, hier die ID eintragen.
3. Auswählen, welche Werte in der Rotation gezeigt werden sollen
(Kontostand / Hofwert / Ingame-Zeit / Easter Egg) und wie oft gewechselt
wird.
FarmHUD zeigt dann z. B. `🚜 Fendt 942` als erste Zeile und wechselt in der
zweiten Zeile alle 15 Sekunden (einstellbar) durch die ausgewählten Werte.
Erfordert einen laufenden Discord-Client auf demselben PC – ohne Discord
bleibt der Status einfach "nicht verbunden", nichts bricht.
> Optional: Für ein eigenes Vorschaubild in der Presence-Karte kannst du im
> Developer Portal unter "Rich Presence → Art Assets" ein Bild mit dem
> Schlüssel `farmhud` hochladen (z. B. `app/assets/icon.png`) – FarmHUD
> referenziert diesen Key bereits.
## Updates
Auf der Einstellungsseite kannst du jederzeit manuell "Auf Updates prüfen"
klicken. Das braucht eine **Update-Quelle**: eine URL, die eine kleine
JSON-Datei im Format von [`fhud-version.example.json`](fhud-version.example.json)
liefert. Wo du diese Datei hostest (GitHub, eigene Website, …) ist dir
überlassen – trag die URL einfach in das Feld "Update-Quelle" ein. Ist eine
neuere Version verfügbar, zeigt FarmHUD einen Hinweis mit Download-Link.
Es gibt **keinen automatischen Update-Check beim Start** – das ist bewusst
so, du prüfst manuell wann du willst.
## Installer bauen (wie ein fertiges Windows-Setup)
1. **Einmalig:** [Inno Setup 6](https://jrsoftware.org/isdl.php) installieren
(kostenlos, ca. 5 MB).
2. `cd app && setup.bat` (falls noch nicht geschehen).
3. `cd app && build.bat` – baut mit PyInstaller `app/dist/FarmHUD/FarmHUD.exe`
(Nutzer brauchen dafür kein Python).
4. `installer/farmhud.iss` in Inno Setup öffnen und auf **Compile** klicken
(oder per Kommandozeile: `ISCC.exe installer\farmhud.iss`).
5. Ergebnis: `installer/Output/FarmHUD-Setup-1.0.0.exe` – ein normaler
Windows-Setup-Assistent mit Lizenz-/Pfadauswahl, Start-Menü- und
optionaler Desktop-Verknüpfung, sauberem Uninstaller.
Bei einer neuen Version: `app/version.py` (`APP_VERSION`) und
`installer/farmhud.iss` (`MyAppVersion`) beide auf dieselbe Nummer setzen,
dann Schritt 3–4 wiederholen.
## Projektstruktur
```
FS25-FarmCompanion/
├── app/
│ ├── main.py ← Einstiegspunkt
│ ├── main_window.py ← HUD-Fenster, Timer, Discord-Rotation
│ ├── discord_rpc.py ← pypresence-Wrapper (fehlertolerant)
│ ├── update_checker.py ← manueller Update-Check gegen JSON-URL
│ ├── settings_store.py ← QSettings (Discord/Update-Konfiguration)
│ ├── easter_egg.py ← rotierende Spr��che
│ ├── live_data.py ← findet & liest live.json (wie FS25-WebDashboard)
│ ├── formatting.py
│ ├── theme.py ← dunkles HUD-Stylesheet
│ ├── widgets/
│ │ ├── stat_tile.py
│ │ └── settings_dialog.py
│ ├── assets/icon.ico + icon.png
│ ├── requirements.txt
│ ├── setup.bat / run.bat / build.bat
├── installer/
│ └── farmhud.iss ← Inno Setup Skript
└── fhud-version.example.json ← Format für die Update-Quelle
```
+6
View File
@@ -0,0 +1,6 @@
.venv/
__pycache__/
*.pyc
build/
dist/
*.spec
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+25
View File
@@ -0,0 +1,25 @@
@echo off
title FarmHUD - Build
cd /d "%~dp0"
if not exist ".venv\Scripts\python.exe" (
echo Keine .venv gefunden - fuehre zuerst setup.bat aus.
pause
exit /b 1
)
echo Installiere PyInstaller (falls noch nicht vorhanden)...
".venv\Scripts\python.exe" -m pip install --quiet pyinstaller
echo Baue FarmHUD.exe...
".venv\Scripts\python.exe" -m PyInstaller ^
--noconfirm --windowed --onedir ^
--name FarmHUD ^
--icon assets\icon.ico ^
--add-data "assets;assets" ^
main.py
echo.
echo Fertig! Ergebnis liegt in dist\FarmHUD\FarmHUD.exe
echo Naechster Schritt: installer\farmhud.iss mit Inno Setup kompilieren.
pause
+70
View File
@@ -0,0 +1,70 @@
"""Thin, defensive wrapper around pypresence.Presence.
Discord Rich Presence talks to the local Discord client over a named pipe -
it's simply not there if Discord isn't running, the user hasn't enabled it,
or the client id is wrong. Every call here is wrapped so a missing/closed
pipe just flips `connected` back to False instead of raising into the
caller - the UI polls `connected` and retries on a timer.
"""
from __future__ import annotations
import time
from typing import Optional
try:
from pypresence import Presence
from pypresence.exceptions import PyPresenceException
except ImportError: # pragma: no cover - handled by requirements.txt
Presence = None
PyPresenceException = Exception
class DiscordRPC:
def __init__(self) -> None:
self._presence: Optional["Presence"] = None
self._client_id: Optional[str] = None
self.connected = False
self.start_ts: Optional[int] = None
def connect(self, client_id: str) -> bool:
if Presence is None:
return False
if self.connected and self._client_id == client_id:
return True
self.disconnect()
if not client_id or not client_id.isdigit():
return False
try:
self._presence = Presence(client_id)
self._presence.connect()
except Exception:
self._presence = None
self.connected = False
return False
self._client_id = client_id
self.connected = True
self.start_ts = int(time.time())
return True
def disconnect(self) -> None:
if self._presence is not None:
try:
self._presence.close()
except Exception:
pass
self._presence = None
self.connected = False
def update(self, details: str, state: str, large_image: Optional[str] = None) -> bool:
if not self.connected or self._presence is None:
return False
try:
kwargs = {"details": details, "state": state, "start": self.start_ts}
if large_image:
kwargs["large_image"] = large_image
self._presence.update(**kwargs)
return True
except Exception:
self.connected = False
self._presence = None
return False
+43
View File
@@ -0,0 +1,43 @@
"""The 'Easter Egg' stat slot: a rotating fun line, mostly playful
commentary on your current money/time, occasionally a pure surprise line.
Deterministic-ish per poll (re-picked only when explicitly rolled) so it
doesn't flicker on every 500ms data refresh.
"""
from __future__ import annotations
import random
from typing import Optional
RARE_LINES = [
"🐄 Irgendwo hat gerade eine Kuh gemuht.",
"🛰️ Dieses Feld wird seit 1998 nicht mehr gedüngt.",
"🦆 Eine Ente hat deinen Trecker für ein Boot gehalten.",
"🌾 Der Weizen träumt von der Ernte.",
"🚜 Achtung: Traktor-Philosoph erkannt.",
"🥔 Die Kartoffel des Tages grüßt dich.",
]
MONEY_LINES = [
(1_000_000, "🤑 Krösus vom Dienst - über 1 Million auf dem Konto!"),
(100_000, "💰 Solide gewirtschaftet - sechsstellig im Plus."),
(0, "🌱 Jeder große Hof fängt mal klein an."),
]
NIGHT_HOURS = set(range(22, 24)) | set(range(0, 5))
def pick_easter_egg(money: Optional[float], hour: Optional[int], rng: Optional[random.Random] = None) -> str:
rng = rng or random
# ~1 in 6 rolls is a pure surprise line, independent of game state.
if rng.random() < (1 / 6):
return rng.choice(RARE_LINES)
if hour is not None and hour in NIGHT_HOURS:
return "🌙 Nachtschicht auf dem Hof - Kaffee nicht vergessen."
if money is not None:
for threshold, line in MONEY_LINES:
if money >= threshold:
return line
return "🚜 FarmHUD hält dich auf dem Laufenden."
+165
View File
@@ -0,0 +1,165 @@
"""Formatting helpers for the small set of stats FarmHUD shows."""
from __future__ import annotations
from typing import Any
def is_number(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool)
def format_euro(n: Any) -> str:
if not is_number(n):
return "–"
text = f"{round(n):,}".replace(",", ".")
return f"{text} €"
def format_speed(vehicle: dict) -> str:
if not vehicle:
return "–"
speed = vehicle.get("speedKmh")
if is_number(speed) and (isinstance(vehicle.get("motorStarted"), bool) or isinstance(vehicle.get("cruiseControlActive"), bool)):
return f"{round(max(0.0, speed))} km/h"
return "–"
def format_game_time_parts(time_data: dict) -> tuple[str, str]:
"""(clock, day) as two separate short strings - kept apart so a tight
layout can show the clock as the headline and the day as a small
subtitle instead of squeezing both onto one line."""
if not time_data:
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
clock = "--:--"
if minutes is not None:
minutes = ((minutes % 1440) + 1440) % 1440
hh = int(minutes // 60)
mm = int(minutes % 60)
clock = f"{hh:02d}:{mm:02d}"
day = time_data.get("currentDay")
day_text = f"Tag {day}" if is_number(day) else ""
return clock, day_text
def format_game_time(time_data: dict) -> str:
clock, day_text = format_game_time_parts(time_data)
return f"{clock} · {day_text}" if day_text else clock
def farmland_total_value(mission: dict, farmlands: list) -> float:
if not mission:
return 0.0
farm_id = mission.get("farmId")
owned = [f for f in (farmlands or []) if f.get("isOwned") and f.get("farmId") == farm_id]
return sum(f.get("price") or 0 for f in owned)
def format_percent(n: Any) -> str:
if not is_number(n):
return "–"
return f"{round(n)}%"
def format_liters(n: Any) -> str:
if not is_number(n):
return "0 l"
text = f"{round(n):,}".replace(",", ".")
return f"{text} l"
def format_price_per_liter(n: Any) -> str:
if not is_number(n):
return "–"
return f"{n:.2f} €/l"
def format_fuel_percent(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 format_percent((level / capacity) * 100)
def format_cruise(vehicle: dict) -> str:
if not vehicle.get("cruiseControlActive"):
return "aus"
speed = vehicle.get("cruiseControlSpeed")
return f"an · {round(speed)} km/h" if is_number(speed) else "an"
def format_minutes_as_duration(total_minutes: Any) -> str:
if not is_number(total_minutes):
return "–"
hours = int(total_minutes // 60)
return f"{hours} h"
def yes_no(value: Any) -> str:
if value is True:
return "ja"
if value is False:
return "nein"
return "–"
# FS25's mission.type.name is an internal camelCase identifier
# ("stonePickMission", "baleWrapMission", ...), not display text - showing
# it raw (or just .capitalize()'d, which produces "Stonepickmission") reads
# as a bug, not a label. Known ones get a proper German name; anything
# unmapped still gets split into readable words instead of one mashed-together one.
MISSION_TYPE_LABELS = {
"mowmission": "Mähen",
"grassmission": "Gras mähen",
"harvestmission": "Ernten",
"cultivatemission": "Grubbern",
"plowmission": "Pflügen",
"sowmission": "Säen",
"weedmission": "Unkraut entfernen",
"herbicidemission": "Pflanzenschutz",
"fertilizemission": "Düngen",
"hoemission": "Hacken",
"rollermission": "Walzen",
"stonepickmission": "Steine sammeln",
"balewrapmission": "Ballen wickeln",
"balecollectmission": "Ballen einsammeln",
"transportmission": "Transport",
"delivermission": "Lieferung",
"treemission": "Bäume fällen",
"destructiblerockmission": "Felsen sprengen",
"levelingmission": "Planieren",
"animaldealermission": "Tierhandel",
"universalmission": "Sammelauftrag",
}
def format_mission_type(raw: Any) -> str:
if not raw:
return "Auftrag"
key = str(raw).lower()
if key in MISSION_TYPE_LABELS:
return MISSION_TYPE_LABELS[key]
# Fallback: split camelCase into words ("baleWrapMission" ->
# "bale Wrap Mission"), drop a trailing "Mission", sentence-case it.
text = str(raw)
words = []
current = text[0]
for ch in text[1:]:
if ch.isupper() and current and not current[-1].isupper():
words.append(current)
current = ch
else:
current += ch
words.append(current)
if words and words[-1].lower() == "mission":
words = words[:-1]
phrase = " ".join(w.lower() for w in words if w)
return phrase[:1].upper() + phrase[1:] if phrase else "Auftrag"
+70
View File
@@ -0,0 +1,70 @@
"""Locates and reads the FS25 WebDashboard mod's live.json file.
Identical resolution logic to the FS25-WebDashboard desktop app (same mod,
same env var override) - FarmHUD is a second, differently-designed reader
of the same data source, not a second mod.
"""
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))
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:
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]:
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):
return {
"connected": False,
"error": "live.json is being written, retrying…",
"expectedPath": str(self.path),
}
if isinstance(data, dict):
data.setdefault("connected", True)
return data
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""FarmHUD - a compact FS25 companion HUD with Discord Rich Presence.
Run:
pip install -r requirements.txt
python main.py
"""
from __future__ import annotations
import os
import sys
import tkinter
from PySide6.QtWidgets import QApplication
from main_window import MainWindow
from theme import STYLESHEET
from version import APP_NAME, APP_ORG, APP_VERSION
def resource_path(relative: str) -> str:
"""Works both run from source and from a PyInstaller onefile bundle."""
base = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base, relative)
def _fix_windows_taskbar_icon() -> None:
"""Without this, Windows groups the app under its own generic Python
icon in the taskbar (and when pinned) instead of the one set via
setWindowIcon() - the title bar icon is unaffected either way, this is
purely a taskbar/grouping quirk. Setting an explicit AppUserModelID
tells Windows this process is its own distinct app. No-op everywhere
else, and safe to skip if anything about this call ever misbehaves."""
if sys.platform != "win32":
return
try:
import ctypes
app_id = f"{APP_ORG}.{APP_NAME}.{APP_VERSION}"
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id)
except Exception:
pass
def main() -> int:
_fix_windows_taskbar_icon()
app = QApplication(sys.argv)
app.setApplicationName(APP_NAME)
app.setStyleSheet(STYLESHEET)
icon_path = resource_path(os.path.join("assets", "icon.ico"))
window = MainWindow(icon_path=icon_path if os.path.exists(icon_path) else None)
window.show()
return app.exec()
if __name__ == "__main__":
sys.exit(main())
+608
View File
@@ -0,0 +1,608 @@
"""FarmHUD main window.
Layout is deliberately ordered top-to-bottom by how often you'd actually
glance at something while playing, not by where the data happens to live
in live.json:
1. Hero tiles: current vehicle, money, farm value, ingame time (+ the
rotating easter-egg line - a signature bit of charm, not "data").
2. Useful, checked often: vehicle details (cruise/motor/fuel/damage),
attached implement fill level, loan, weather (+ forecast), active
contracts.
3. Useful, checked occasionally: sell prices, storage, animal
husbandry, other players (multiplayer only).
4. Everything else - technical/rarely-needed (session/difficulty
settings, savegame metadata, per-vehicle technical flags, production
recipe status, field overview) - collapsed by default under "mehr
anzeigen" so the HUD stays glanceable, but still one click away.
A Discord Rich Presence connection mirrors a user-configurable subset of
the hero-tile data, and a Settings dialog covers both Discord and the
manual update check. Polls live.json directly - no server involved.
"""
from __future__ import annotations
import random
from typing import Optional
from PySide6.QtCore import QTimer
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import (
QFrame,
QHBoxLayout,
QLabel,
QMainWindow,
QPushButton,
QScrollArea,
QVBoxLayout,
QWidget,
)
from discord_rpc import DiscordRPC
from easter_egg import pick_easter_egg
from formatting import (
farmland_total_value,
format_cruise,
format_euro,
format_fuel_percent,
format_game_time,
format_game_time_parts,
format_liters,
format_minutes_as_duration,
format_mission_type,
format_percent,
format_price_per_liter,
format_speed,
is_number,
yes_no,
)
from live_data import LiveDataSource
from settings_store import ROTATION_KEYS, ROTATION_LABELS, SettingsStore
from theme import RUST, SAGE
from version import APP_NAME, APP_VERSION
from widgets.collapsible_group import CollapsibleGroup
from widgets.info_card import InfoCard
from widgets.settings_dialog import SettingsDialog
from widgets.stat_tile import StatTile
POLL_INTERVAL_MS = 500
EGG_REFRESH_MS = 12_000
DISCORD_RECONNECT_MS = 10_000
MAX_MISSIONS_SHOWN = 6
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",
}
class MainWindow(QMainWindow):
def __init__(self, icon_path: Optional[str] = None) -> None:
super().__init__()
self.setWindowTitle(f"{APP_NAME} {APP_VERSION}")
# A fixed width (or full fixed size) makes Qt/Windows grey out the
# maximize button - use a minimum instead so the HUD still starts
# compact but the window stays freely resizable/maximizable. 460 is
# the narrowest the 3-across gauge row (money/farm value/time) can
# go before its own numbers start needing to wrap.
self.setMinimumWidth(460)
self.resize(500, 820)
if icon_path:
self.setWindowIcon(QIcon(icon_path))
self.settings = SettingsStore()
self.live_data = LiveDataSource()
self.discord = DiscordRPC()
self._rng = random.Random()
self._egg_text = "🚜 FarmHUD startet…"
self._rotation_index = 0
central = QWidget()
self.setCentralWidget(central)
root = QVBoxLayout(central)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
# -- Header ---------------------------------------------------------
header = QFrame()
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(16, 14, 12, 10)
title = QLabel(f"🌾 {APP_NAME}")
title.setProperty("role", "title")
header_layout.addWidget(title)
header_layout.addStretch(1)
self.status_dot = QLabel("●")
self.status_dot.setStyleSheet(f"color: {RUST}; font-size: 12px;")
header_layout.addWidget(self.status_dot)
root.addWidget(header)
header.setProperty("role", "header")
# -- Scrollable body ---------------------------------------------------
# The tile column is capped at a comfortable reading width and
# centered - otherwise maximizing the window would stretch every
# tile/card edge-to-edge with a huge empty gap between icon and
# value, which looks broken rather than "responsive".
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.Shape.NoFrame)
root.addWidget(scroll, 1)
scroll_content = QWidget()
scroll.setWidget(scroll_content)
center_layout = QHBoxLayout(scroll_content)
center_layout.setContentsMargins(0, 0, 0, 0)
center_layout.addStretch(1)
body = QWidget()
body.setMaximumWidth(640)
center_layout.addWidget(body)
center_layout.addStretch(1)
body_layout = QVBoxLayout(body)
body_layout.setContentsMargins(16, 6, 16, 12)
body_layout.setSpacing(12)
# --- Tier 1: the gauge cluster -------------------------------------------
# One wide masthead reading (what you're driving right now) with
# three compact gauges flanking it below - the shape of a real
# tractor dash, and what actually uses a wider window well instead
# of four identical stacked bars with dead space on both sides.
self.vehicle_tile = StatTile("🚜", "Aktuelles Fahrzeug", variant="hero")
body_layout.addWidget(self.vehicle_tile)
gauge_row = QHBoxLayout()
gauge_row.setSpacing(12)
self.money_tile = StatTile("💰", "Kontostand", variant="compact")
self.farm_value_tile = StatTile("🏡", "Hofwert", variant="compact")
self.time_tile = StatTile("🕒", "Ingame-Zeit", variant="compact")
for tile in (self.money_tile, self.farm_value_tile, self.time_tile):
gauge_row.addWidget(tile)
body_layout.addLayout(gauge_row)
self.egg_label = QLabel(self._egg_text)
self.egg_label.setProperty("role", "egg")
self.egg_label.setWordWrap(True)
body_layout.addWidget(self.egg_label)
# --- Tier 2: useful, checked often --------------------------------------
self.vehicle_details_card = InfoCard("🔧", "Fahrzeug-Details")
body_layout.addWidget(self.vehicle_details_card)
# Loan + attached implement are both short (1-3 rows) - pairing them
# uses the wider column without the masonry gaps a longer card
# (weather, missions) would leave next to a short one.
pair_row = QHBoxLayout()
pair_row.setSpacing(12)
self.loan_card = InfoCard("🏦", "Kredit")
self.attached_card = InfoCard("🚛", "Angehängt")
pair_row.addWidget(self.loan_card)
pair_row.addWidget(self.attached_card)
body_layout.addLayout(pair_row)
self.weather_card = InfoCard("🌦️", "Wetter")
self.missions_card = InfoCard("🧾", "Aufträge")
for card in (self.weather_card, self.missions_card):
body_layout.addWidget(card)
# --- Tier 3: useful, checked occasionally -------------------------------
self.prices_card = InfoCard("💹", "Verkaufspreise")
self.storage_card = InfoCard("🌾", "Lager")
self.husbandry_card = InfoCard("🐄", "Tierhaltung")
self.players_card = InfoCard("👥", "Mitspieler")
for card in (self.prices_card, self.storage_card, self.husbandry_card, self.players_card):
body_layout.addWidget(card)
# --- Tier 4: technical / rarely needed - collapsed by default -----------
self.technical_group = CollapsibleGroup("Weitere Daten (selten gebraucht)")
body_layout.addWidget(self.technical_group)
self.session_card = InfoCard("⚙️", "Sitzungseinstellungen")
self.savegame_card = InfoCard("💾", "Spielstand")
self.vehicle_tech_card = InfoCard("🔩", "Fahrzeug-Technik")
self.productions_card = InfoCard("🏭", "Produktionen")
self.fields_card = InfoCard("🗺️", "Felder")
for card in (
self.session_card,
self.savegame_card,
self.vehicle_tech_card,
self.productions_card,
self.fields_card,
):
self.technical_group.body_layout.addWidget(card)
body_layout.addStretch(1)
# -- Footer ------------------------------------------------------------
footer = QFrame()
footer.setProperty("role", "footer")
footer_layout = QHBoxLayout(footer)
footer_layout.setContentsMargins(14, 8, 10, 8)
self.discord_status_label = QLabel("⭘ Discord nicht verbunden")
self.discord_status_label.setProperty("role", "dim")
footer_layout.addWidget(self.discord_status_label)
footer_layout.addStretch(1)
settings_btn = QPushButton("⚙")
settings_btn.setProperty("flat", "true")
settings_btn.setToolTip("Einstellungen")
settings_btn.clicked.connect(self._open_settings)
footer_layout.addWidget(settings_btn)
root.addWidget(footer)
# -- Timers ------------------------------------------------------------
self._data_timer = QTimer(self)
self._data_timer.timeout.connect(self._poll_once)
self._data_timer.start(POLL_INTERVAL_MS)
self._egg_timer = QTimer(self)
self._egg_timer.timeout.connect(self._refresh_egg)
self._egg_timer.start(EGG_REFRESH_MS)
self._discord_reconnect_timer = QTimer(self)
self._discord_reconnect_timer.timeout.connect(self._try_discord_connect)
self._discord_reconnect_timer.start(DISCORD_RECONNECT_MS)
self._rotation_timer = QTimer(self)
self._rotation_timer.timeout.connect(self._advance_rotation)
self._apply_rotation_interval()
self._last_data: dict = {}
self._poll_once()
self._try_discord_connect()
if self.discord.connected:
self._advance_rotation()
# ------------------------------------------------------------------
def _apply_rotation_interval(self) -> None:
self._rotation_timer.start(self.settings.discord_rotation_interval_s * 1000)
def _open_settings(self) -> None:
dialog = SettingsDialog(self.settings, self)
if dialog.exec():
self._apply_rotation_interval()
self._try_discord_connect()
if self.discord.connected:
self._advance_rotation()
# ------------------------------------------------------------------
def _try_discord_connect(self) -> None:
if not self.settings.discord_enabled:
self.discord.disconnect()
self.discord_status_label.setText("⭘ Discord deaktiviert")
return
if not self.discord.connected:
self.discord.connect(self.settings.discord_client_id)
self._update_discord_status_label()
def _update_discord_status_label(self) -> None:
if self.discord.connected:
self.discord_status_label.setText("🟢 Discord verbunden")
else:
self.discord_status_label.setText("⭘ Discord nicht verbunden")
# ------------------------------------------------------------------
def _refresh_egg(self) -> None:
data = self._last_data
money = (data.get("mission") or {}).get("money")
time_data = data.get("time") or {}
hour = None
minutes = time_data.get("dayTimeMinutes")
if is_number(minutes):
hour = int((minutes / 60000 if minutes > 1440 else minutes) // 60) % 24
self._egg_text = pick_easter_egg(money if is_number(money) else None, hour, self._rng)
self.egg_label.setText(self._egg_text)
# ------------------------------------------------------------------
def _current_vehicle(self, data: dict) -> Optional[dict]:
vehicles = data.get("vehicles") or []
controlled_id = data.get("controlledVehicleId")
for v in vehicles:
if v.get("id") == controlled_id:
return v
player = data.get("player") or {}
if not player.get("isControllingVehicle") and vehicles:
return None
return vehicles[0] if vehicles else None
def _current_farm(self, data: dict) -> Optional[dict]:
mission = data.get("mission") or {}
farm_id = mission.get("farmId")
for f in data.get("farms") or []:
if f.get("id") == farm_id:
return f
return None
def _rotation_values(self, data: dict) -> dict:
mission = data.get("mission") or {}
money = mission.get("money")
farm_value = farmland_total_value(mission, data.get("farmlands") or [])
return {
"money": format_euro(money) if is_number(money) else "–",
"farm_value": format_euro(farm_value),
"time": format_game_time(data.get("time")),
"easter_egg": self._egg_text,
}
# ------------------------------------------------------------------
def _poll_once(self) -> None:
data = self.live_data.read()
self._last_data = data
connected = data.get("connected") is not False
self.status_dot.setStyleSheet(
f"color: {SAGE}; font-size: 12px;" if connected else f"color: {RUST}; font-size: 12px;"
)
vehicle = self._current_vehicle(data)
mission = data.get("mission") or {}
farm = self._current_farm(data)
self._render_hero_tiles(vehicle, mission, data)
self._render_vehicle_details(vehicle)
self._render_attached(vehicle, data.get("vehicles") or [])
self._render_loan(farm)
self._render_weather(data.get("weather"), data.get("time"))
self._render_missions(data.get("missions"))
self._render_prices(data.get("prices"))
self._render_storage(data.get("silos"))
self._render_husbandry(data.get("husbandries"))
self._render_players(data.get("players"))
self._render_session(data.get("session"))
self._render_savegame(mission)
self._render_vehicle_tech(vehicle)
self._render_productions(data.get("productions"))
self._render_fields(data.get("fields"))
def _render_hero_tiles(self, vehicle: Optional[dict], mission: dict, data: dict) -> None:
if vehicle:
name = vehicle.get("name") or "Unbenannt"
speed = format_speed(vehicle)
self.vehicle_tile.set_value(f"{name}" + (f" · {speed}" if speed != "–" else ""))
else:
self.vehicle_tile.set_value("Kein Fahrzeug ausgewählt")
money = mission.get("money")
self.money_tile.set_value(format_euro(money) if is_number(money) else "–")
farm_value = farmland_total_value(mission, data.get("farmlands") or [])
self.farm_value_tile.set_value(format_euro(farm_value) if mission else "–")
clock, day_text = format_game_time_parts(data.get("time"))
self.time_tile.set_value(clock)
self.time_tile.set_sub_value(day_text)
def _render_vehicle_details(self, vehicle: Optional[dict]) -> None:
if not vehicle:
self.vehicle_details_card.set_rows([], empty_text="Steig in ein Fahrzeug, um Details zu sehen")
return
rows: list[tuple[str, str]] = []
if isinstance(vehicle.get("cruiseControlActive"), bool):
rows.append(("Tempomat", format_cruise(vehicle)))
if isinstance(vehicle.get("motorStarted"), bool):
rows.append(("Motor", "läuft" if vehicle["motorStarted"] else "aus"))
if is_number(vehicle.get("motorLoadPercent")):
rows.append(("Last", format_percent(vehicle["motorLoadPercent"])))
if is_number(vehicle.get("fuelCapacity")):
rows.append(("Tank", format_fuel_percent(vehicle)))
if is_number(vehicle.get("damagePercent")):
rows.append(("Schaden", format_percent(vehicle["damagePercent"])))
if is_number(vehicle.get("dirtPercent")):
rows.append(("Verschmutzung", format_percent(vehicle["dirtPercent"])))
self.vehicle_details_card.set_rows(rows, empty_text="Steig in ein Fahrzeug, um Details zu sehen")
def _render_attached(self, vehicle: Optional[dict], all_vehicles: list) -> None:
if not vehicle:
self.attached_card.set_rows([], empty_text="Kein Fahrzeug ausgewählt")
return
by_id = {v.get("id"): v for v in all_vehicles}
rows: list[tuple[str, str]] = []
for implement_id in vehicle.get("attachedImplementIds") or []:
implement = by_id.get(implement_id)
if implement is None:
continue
name = implement.get("name") or "Unbenanntes Gerät"
fill_units = [fu for fu in (implement.get("fillUnits") or []) if is_number(fu.get("capacity")) and fu["capacity"] > 0]
if fill_units:
fu = fill_units[0]
pct = (fu.get("fillLevel") or 0) / fu["capacity"] * 100
rows.append((name, f"{fu.get('fillTypeName') or ''} {format_percent(pct)}".strip()))
else:
rows.append((name, "kein Tank"))
self.attached_card.set_rows(rows, empty_text="Nichts angehängt")
def _render_loan(self, farm: Optional[dict]) -> None:
if not farm:
self.loan_card.set_rows([], empty_text="Keine Kreditdaten verfügbar")
return
rows = []
if is_number(farm.get("loan")):
rows.append(("Kredit", format_euro(farm["loan"])))
if is_number(farm.get("loanMaximum")):
rows.append(("Kreditlimit", format_euro(farm["loanMaximum"])))
self.loan_card.set_rows(rows, empty_text="Keine Kreditdaten verfügbar")
def _render_weather(self, weather: Optional[dict], time_data: Optional[dict]) -> None:
if not weather:
self.weather_card.set_rows([], empty_text="Keine Wetterdaten vom Spiel verfügbar")
return
rows = []
name = weather.get("currentTypeName")
icon = WEATHER_ICONS.get(name, "")
label = WEATHER_LABELS_DE.get(name, name or "Unbekannt")
rows.append(("Aktuell", f"{icon} {label}".strip()))
if is_number(weather.get("temperatureCelsius")):
rows.append(("Temperatur", f"{round(weather['temperatureCelsius'])} °C"))
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")
if badges:
rows.append(("Zustand", ", ".join(badges)))
if is_number(weather.get("windSpeed")):
wind_text = f"{weather['windSpeed']:.1f} m/s"
if is_number(weather.get("windDirectionDeg")):
wind_text += f" · {round(weather['windDirectionDeg'])}°"
rows.append(("Wind", wind_text))
forecast = weather.get("forecast") or []
for f in forecast[:2]:
icon = WEATHER_ICONS.get(f.get("typeName"), "")
min_t, max_t = f.get("minTemperatureCelsius"), f.get("maxTemperatureCelsius")
temp_text = f"{round(min_t)}°/{round(max_t)}°" if is_number(min_t) and is_number(max_t) else ""
rows.append((f"+{f.get('dayOffset')} Tag", f"{icon} {temp_text}".strip()))
self.weather_card.set_rows(rows)
def _render_missions(self, missions: Optional[list]) -> None:
missions = list(missions or [])
missions.sort(key=lambda m: m.get("reward") or 0, reverse=True)
rows = [
(format_mission_type(m.get("type")), format_euro(m.get("reward")) if is_number(m.get("reward")) else "–")
for m in missions[:MAX_MISSIONS_SHOWN]
]
remaining = len(missions) - MAX_MISSIONS_SHOWN
if remaining > 0:
rows.append((f"+{remaining} weitere", ""))
self.missions_card.set_rows(rows, empty_text="Keine aktiven Aufträge")
def _render_prices(self, prices: Optional[dict]) -> None:
rows = []
for entry in (prices or {}).values():
rows.append((entry.get("fillTypeName") or "Unbekannt", format_price_per_liter(entry.get("pricePerLiter"))))
rows.sort(key=lambda r: r[0])
self.prices_card.set_rows(rows, empty_text="Keine Preisdaten verfügbar")
def _render_storage(self, silos: Optional[list]) -> None:
totals: dict[str, float] = {}
for silo in silos or []:
for ft in silo.get("fillTypes") or []:
name = ft.get("fillTypeName") or "Unbekannt"
totals[name] = totals.get(name, 0) + (ft.get("fillLevel") or 0)
rows = [(name, format_liters(level)) for name, level in sorted(totals.items())]
self.storage_card.set_rows(rows, empty_text="Keine befüllten Silos")
def _render_husbandry(self, husbandries: Optional[list]) -> None:
rows = []
for h in husbandries or []:
name = h.get("name") or "Unbenannt"
count = h.get("numAnimals")
max_count = h.get("maxNumAnimals")
count_text = f"{count if is_number(count) else '–'}" + (f" / {max_count}" if is_number(max_count) else "")
if is_number(h.get("productivityPercent")):
count_text += f" · {format_percent(h['productivityPercent'])} Produktivität"
rows.append((name, count_text))
self.husbandry_card.set_rows(rows, empty_text="Keine Tierhaltung")
def _render_players(self, players: Optional[list]) -> None:
players = players or []
if len(players) <= 1:
self.players_card.hide()
return
self.players_card.show()
rows = [(p.get("nickname") or "Spieler", f"Betrieb #{p.get('farmId')}" + (" · Admin" if p.get("isAdmin") else "")) for p in players]
self.players_card.set_rows(rows)
def _render_session(self, session: Optional[dict]) -> None:
if not session:
self.session_card.set_rows([], empty_text="Keine Sitzungsdaten verfügbar")
return
rows = [
("Wirtschafts-Schwierigkeit", str(session.get("economicDifficulty", "–"))),
("Wachstumsmodus", str(session.get("growthMode", "–"))),
("Pflugpflicht", yes_no(session.get("plowingRequiredEnabled"))),
("Steine", yes_no(session.get("stonesEnabled"))),
("Unkraut", yes_no(session.get("weedsEnabled"))),
("Verkehr", yes_no(session.get("trafficEnabled"))),
("Automatikstart Motor", yes_no(session.get("automaticMotorStartEnabled"))),
]
self.session_card.set_rows(rows)
def _render_savegame(self, mission: dict) -> None:
rows = []
if mission.get("savegameName"):
rows.append(("Spielstand", str(mission["savegameName"])))
if is_number(mission.get("playTimeHours")):
rows.append(("Spielzeit gesamt", format_minutes_as_duration(mission.get("playTimeMinutes"))))
if mission.get("isMultiplayer") is not None:
rows.append(("Multiplayer", yes_no(mission.get("isMultiplayer"))))
if mission.get("serverName"):
rows.append(("Server", str(mission["serverName"])))
self.savegame_card.set_rows(rows)
def _render_vehicle_tech(self, vehicle: Optional[dict]) -> None:
if not vehicle:
self.vehicle_tech_card.set_rows([], empty_text="Kein Fahrzeug ausgewählt")
return
rows = []
if vehicle.get("ownerFarmId") is not None:
rows.append(("Eigentümer-Farm", f"#{vehicle['ownerFarmId']}"))
if vehicle.get("isOccupiedByAnyPlayer") is not None:
rows.append(("Besetzt", yes_no(vehicle.get("isOccupiedByAnyPlayer"))))
if vehicle.get("isTurnedOn") is not None:
rows.append(("Eingeschaltet", yes_no(vehicle.get("isTurnedOn"))))
if vehicle.get("isFolded") is not None:
rows.append(("Geklappt", yes_no(vehicle.get("isFolded"))))
if vehicle.get("lightsLowBeamOn") is not None:
rows.append(("Licht (Abblendlicht)", yes_no(vehicle.get("lightsLowBeamOn"))))
self.vehicle_tech_card.set_rows(rows)
def _render_productions(self, productions: Optional[list]) -> None:
rows = []
for p in productions or []:
name = p.get("name") or "Unbenannt"
recipes = p.get("recipes") or []
statuses = [r.get("statusName") or r.get("status") for r in recipes if r.get("statusName") or r.get("status")]
rows.append((name, ", ".join(str(s) for s in statuses) or "–"))
self.productions_card.set_rows(rows)
def _render_fields(self, fields: Optional[list]) -> None:
fields = fields or []
if not fields:
self.fields_card.set_rows([], empty_text="Keine Felddaten verfügbar")
return
total_area = sum(f.get("areaHa") or 0 for f in fields)
rows = [
("Anzahl Felder", str(len(fields))),
("Gesamtfläche", f"{total_area:.1f} ha"),
]
self.fields_card.set_rows(rows)
# ------------------------------------------------------------------
# Discord's Rich Presence rate limit is a handful of updates per 20s,
# so pushing on every ~500ms poll tick would get updates silently
# dropped. Instead only the rotation timer (default every 15s) pushes -
# it always reads the freshest `_last_data` the poll timer maintains.
def _push_discord_update(self, data: dict, vehicle: Optional[dict]) -> None:
if not self.discord.connected:
return
details = f"🚜 {vehicle.get('name')}" if vehicle and vehicle.get("name") else "Auf dem Hof unterwegs"
enabled_keys = [k for k in ROTATION_KEYS if self.settings.rotation_enabled(k)]
if not enabled_keys:
state = APP_NAME
else:
values = self._rotation_values(data)
key = enabled_keys[self._rotation_index % len(enabled_keys)]
if key == "easter_egg":
# Shown as a plain saying in Discord, not labeled "Easter
# Egg" - the surprise is the point, spelling it out isn't.
state = values[key]
else:
state = f"{ROTATION_LABELS[key]}: {values[key]}"
ok = self.discord.update(details=details, state=state, large_image="farmhud")
self._update_discord_status_label()
if not ok:
self.discord_status_label.setText("⭘ Discord getrennt")
def _advance_rotation(self) -> None:
self._rotation_index += 1
vehicle = self._current_vehicle(self._last_data)
self._push_discord_update(self._last_data, vehicle)
+3
View File
@@ -0,0 +1,3 @@
PySide6>=6.10
pypresence>=4.3
requests>=2.31
+14
View File
@@ -0,0 +1,14 @@
@echo off
title FarmHUD
cd /d "%~dp0"
if exist ".venv\Scripts\python.exe" (
".venv\Scripts\python.exe" main.py
) else (
python main.py
)
if errorlevel 1 (
echo.
echo Start fehlgeschlagen. Fuehre zuerst setup.bat aus.
pause
)
+62
View File
@@ -0,0 +1,62 @@
"""Persisted user settings (QSettings-backed): Discord RPC config, which
stats rotate into it, the update-manifest URL. Everything has a sensible
default so a first run works without opening Settings at all (besides
actually wanting Discord presence turned on, which stays opt-in)."""
from __future__ import annotations
from PySide6.QtCore import QSettings
from version import APP_NAME, APP_ORG, DEFAULT_DISCORD_CLIENT_ID
ROTATION_KEYS = ["money", "farm_value", "time", "easter_egg"]
ROTATION_LABELS = {
"money": "Kontostand",
"farm_value": "Hofwert",
"time": "Ingame-Zeit",
"easter_egg": "Easter Egg",
}
class SettingsStore:
def __init__(self) -> None:
self._s = QSettings(APP_ORG, APP_NAME)
# -- Discord RPC ----------------------------------------------------
@property
def discord_enabled(self) -> bool:
return self._s.value("discord/enabled", False, type=bool)
@discord_enabled.setter
def discord_enabled(self, value: bool) -> None:
self._s.setValue("discord/enabled", bool(value))
@property
def discord_client_id(self) -> str:
return self._s.value("discord/client_id", DEFAULT_DISCORD_CLIENT_ID, type=str)
@discord_client_id.setter
def discord_client_id(self, value: str) -> None:
self._s.setValue("discord/client_id", value.strip())
@property
def discord_rotation_interval_s(self) -> int:
return self._s.value("discord/rotation_interval_s", 15, type=int)
@discord_rotation_interval_s.setter
def discord_rotation_interval_s(self, value: int) -> None:
self._s.setValue("discord/rotation_interval_s", int(value))
def rotation_enabled(self, key: str) -> bool:
return self._s.value(f"discord/rotate_{key}", True, type=bool)
def set_rotation_enabled(self, key: str, value: bool) -> None:
self._s.setValue(f"discord/rotate_{key}", bool(value))
# -- Updates ----------------------------------------------------------
@property
def update_manifest_url(self) -> str:
return self._s.value("update/manifest_url", "", type=str)
@update_manifest_url.setter
def update_manifest_url(self, value: str) -> None:
self._s.setValue("update/manifest_url", value.strip())
+20
View File
@@ -0,0 +1,20 @@
@echo off
title FarmHUD - Setup
cd /d "%~dp0"
echo Erstelle Python-Umgebung (.venv)...
python -m venv .venv
if errorlevel 1 (
echo.
echo Python wurde nicht gefunden. Installiere Python 3.10+ von https://python.org
pause
exit /b 1
)
echo Installiere Abhaengigkeiten...
".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 "run.bat" oder "python main.py".
pause
+156
View File
@@ -0,0 +1,156 @@
"""FarmHUD's visual identity: a tractor instrument-cluster, not a SaaS
dashboard. Warm soil/dusk tones instead of cool corporate slate, a single
harvest-gold accent (pulled from the wheat-sheaf icon), and two purposeful
typefaces - Bahnschrift for the wordmark/headings (a technical, signage-like
grotesk already on every Windows 10+ box) and Cascadia Mono for live
numeric readouts (tabular figures, like a real digital gauge display).
Everything else stays quiet so those two choices carry the personality.
"""
from __future__ import annotations
BG = "#14140f"
PANEL = "#1d1f16"
PANEL_BORDER = "#363a29"
PANEL_BORDER_STRONG = "#4a5138"
INK = "#f1ecdc"
MUTED = "#9a9782"
AMBER = "#e2a63c"
AMBER_SOFT = "#8a6a2c"
RUST = "#c1552f"
SAGE = "#7a9b57"
HEADING_FONT = '"Bahnschrift SemiBold", "Segoe UI Semibold", "Segoe UI", sans-serif'
MONO_FONT = '"Cascadia Mono", Consolas, "Courier New", monospace'
BODY_FONT = '"Segoe UI", sans-serif'
STYLESHEET = f"""
QWidget {{
background: {BG};
color: {INK};
font-family: {BODY_FONT};
font-size: 13px;
}}
QMainWindow, QDialog {{
background: {BG};
}}
QLabel[role="title"] {{
font-family: {HEADING_FONT};
font-size: 19px;
letter-spacing: 0.2px;
}}
QLabel[role="section-title"] {{
font-family: {HEADING_FONT};
font-size: 14px;
color: {INK};
}}
QLabel[role="tile-label"] {{
font-family: {HEADING_FONT};
color: {MUTED};
font-size: 11.5px;
letter-spacing: 0.2px;
}}
QLabel[role="tile-value"] {{
font-family: {MONO_FONT};
font-size: 21px;
font-weight: 600;
color: {AMBER};
}}
QLabel[role="tile-value-lg"] {{
font-family: {MONO_FONT};
font-size: 26px;
font-weight: 600;
color: {AMBER};
}}
QLabel[role="row-value"] {{
font-family: {MONO_FONT};
font-size: 13px;
color: {INK};
}}
QLabel[role="egg"] {{
color: {AMBER};
font-size: 12px;
font-style: italic;
}}
QLabel[role="dim"] {{
color: {MUTED};
font-size: 11.5px;
}}
QFrame[role="tile"] {{
background: {PANEL};
border: 1px solid {PANEL_BORDER};
border-radius: 4px;
}}
QFrame[role="tile-hero"] {{
background: {PANEL};
border: 1px solid {PANEL_BORDER_STRONG};
border-left: 3px solid {AMBER};
border-radius: 4px;
}}
QFrame[role="footer"] {{
background: {PANEL};
border-top: 1px solid {PANEL_BORDER};
}}
QFrame[role="header"] {{
background: {PANEL};
border-bottom: 1px solid {PANEL_BORDER};
}}
QPushButton {{
background: {PANEL};
border: 1px solid {PANEL_BORDER};
border-radius: 4px;
padding: 6px 12px;
color: {INK};
}}
QPushButton:hover {{
border-color: {AMBER_SOFT};
color: {AMBER};
}}
QPushButton[flat="true"] {{
background: transparent;
border: none;
color: {MUTED};
font-size: 16px;
}}
QPushButton[flat="true"]:hover {{
color: {AMBER};
}}
QPushButton[role="primary"] {{
background: {AMBER};
border: none;
color: #1c1204;
font-weight: 600;
}}
QPushButton[role="primary"]:hover {{
background: #edb658;
}}
QLineEdit, QSpinBox {{
background: {BG};
border: 1px solid {PANEL_BORDER};
border-radius: 4px;
padding: 5px 8px;
color: {INK};
}}
QLineEdit:focus, QSpinBox:focus {{
border-color: {AMBER_SOFT};
}}
QCheckBox {{
spacing: 8px;
}}
QScrollArea {{
border: none;
}}
QGroupBox {{
border: 1px solid {PANEL_BORDER};
border-radius: 4px;
margin-top: 10px;
padding-top: 14px;
font-family: {HEADING_FONT};
font-weight: 600;
}}
QGroupBox::title {{
subcontrol-origin: margin;
left: 10px;
padding: 0 4px;
color: {MUTED};
}}
"""
+64
View File
@@ -0,0 +1,64 @@
"""Manual "check for updates" support (Settings page button).
Expects a small JSON manifest at a URL the user configures in Settings:
{ "version": "1.2.0", "url": "https://.../FarmHUD-Setup-1.2.0.exe", "notes": "..." }
See fhud-version.example.json in the project root for the exact shape.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
import requests
from version import APP_VERSION
@dataclass
class UpdateResult:
ok: bool
message: str
update_available: bool = False
latest_version: Optional[str] = None
download_url: Optional[str] = None
notes: Optional[str] = None
def _parse_version(text: str) -> tuple:
parts = []
for chunk in text.strip().split("."):
digits = "".join(c for c in chunk if c.isdigit())
parts.append(int(digits) if digits else 0)
return tuple(parts)
def check_for_update(manifest_url: str, timeout_s: float = 6.0) -> UpdateResult:
if not manifest_url:
return UpdateResult(ok=False, message="Keine Update-Quelle konfiguriert (siehe Einstellungen).")
try:
resp = requests.get(manifest_url, timeout=timeout_s)
resp.raise_for_status()
data = resp.json()
except requests.RequestException as exc:
return UpdateResult(ok=False, message=f"Update-Prüfung fehlgeschlagen: {exc}")
except ValueError:
return UpdateResult(ok=False, message="Update-Quelle lieferte kein gültiges JSON.")
latest = data.get("version")
if not latest:
return UpdateResult(ok=False, message="Update-Quelle enthält kein 'version'-Feld.")
is_newer = _parse_version(latest) > _parse_version(APP_VERSION)
if is_newer:
return UpdateResult(
ok=True,
message=f"Neue Version verfügbar: {latest} (aktuell installiert: {APP_VERSION}).",
update_available=True,
latest_version=latest,
download_url=data.get("url"),
notes=data.get("notes"),
)
return UpdateResult(ok=True, message=f"Du bist auf dem neuesten Stand ({APP_VERSION}).", update_available=False)
+12
View File
@@ -0,0 +1,12 @@
"""Central version/identity constants - used by the window title, the
About/Settings dialog, the update checker, and the PyInstaller/Inno Setup
build scripts. Bump APP_VERSION here on every release."""
APP_NAME = "FarmHUD"
APP_CODE = "FHUD" # short code used for patch/version manifest file names
APP_VERSION = "1.0.0"
APP_ORG = "FarmHUD"
# Discord Developer Portal application id (discord.com/developers/applications).
# Pre-filled default; the user can override it in Settings.
DEFAULT_DISCORD_CLIENT_ID = "1548716147740778556"
@@ -0,0 +1,56 @@
"""A collapsed-by-default group at the very bottom of the HUD for the
low-glance-value / technical data (session settings, savegame metadata,
per-vehicle technical flags, ...) - keeps the main view focused on what's
actually useful while the app + and toggle keeps everything accessible."""
from __future__ import annotations
from PySide6.QtCore import QSettings, Signal
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton, QVBoxLayout
from version import APP_NAME, APP_ORG
from widgets.common import style_role
SETTINGS_KEY = "ui/technical_section_expanded"
class CollapsibleGroup(QFrame):
toggled = Signal(bool)
def __init__(self, title: str, parent=None) -> None:
super().__init__(parent)
self.setProperty("role", "tile")
outer = QVBoxLayout(self)
outer.setContentsMargins(14, 10, 14, 10)
outer.setSpacing(8)
header = QHBoxLayout()
title_label = QLabel(title)
style_role(title_label, "section-title")
header.addWidget(title_label)
header.addStretch(1)
self._settings = QSettings(APP_ORG, APP_NAME)
self._expanded = self._settings.value(SETTINGS_KEY, False, type=bool)
self.toggle_btn = QPushButton()
self.toggle_btn.setProperty("flat", "true")
self.toggle_btn.clicked.connect(self._on_toggle)
header.addWidget(self.toggle_btn)
outer.addLayout(header)
self.body = QFrame()
self.body_layout = QVBoxLayout(self.body)
self.body_layout.setContentsMargins(0, 0, 0, 0)
self.body_layout.setSpacing(8)
outer.addWidget(self.body)
self._apply_state()
def _on_toggle(self) -> None:
self._expanded = not self._expanded
self._settings.setValue(SETTINGS_KEY, self._expanded)
self._apply_state()
self.toggled.emit(self._expanded)
def _apply_state(self) -> None:
self.body.setVisible(self._expanded)
self.toggle_btn.setText("▾ ausblenden" if self._expanded else "▸ mehr anzeigen")
+28
View File
@@ -0,0 +1,28 @@
"""Small shared helpers used across FarmHUD's widgets."""
from __future__ import annotations
from PySide6.QtWidgets import QWidget
def style_role(widget: QWidget, role: str) -> QWidget:
widget.setProperty("role", role)
return widget
def clear_layout(layout) -> None:
"""Empties a layout so it can be rebuilt 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. Every dynamic list
here (storage, missions, players, ...) gets rebuilt on every ~500ms
poll tick, so that lag would show up as visible flicker/ghosting.
Hiding 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()
@@ -0,0 +1,53 @@
"""A tile-styled card with a title row and a dynamic list of label:value
rows underneath - the one component nearly every new "useful vs. less
useful" section is built from (weather, attached implement, missions,
storage, husbandry, prices, players, session settings, ...)."""
from __future__ import annotations
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QVBoxLayout, QWidget
from widgets.common import clear_layout, style_role
class InfoCard(QFrame):
def __init__(self, icon: str, title: str, parent=None) -> None:
super().__init__(parent)
self.setProperty("role", "tile")
outer = QVBoxLayout(self)
outer.setContentsMargins(14, 10, 14, 10)
outer.setSpacing(6)
head = QHBoxLayout()
head.setSpacing(8)
icon_label = QLabel(icon)
icon_label.setStyleSheet("font-size: 15px;")
head.addWidget(icon_label)
title_label = QLabel(title)
style_role(title_label, "section-title")
head.addWidget(title_label)
head.addStretch(1)
outer.addLayout(head)
self.rows_layout = QVBoxLayout()
self.rows_layout.setSpacing(3)
outer.addLayout(self.rows_layout)
def set_rows(self, rows: list[tuple[str, str]], empty_text: str = "Keine Daten") -> None:
clear_layout(self.rows_layout)
if not rows:
lbl = QLabel(empty_text)
style_role(lbl, "dim")
self.rows_layout.addWidget(lbl)
return
for name, value in rows:
row = QWidget()
row_layout = QHBoxLayout(row)
row_layout.setContentsMargins(0, 0, 0, 0)
name_lbl = QLabel(name)
style_role(name_lbl, "dim")
row_layout.addWidget(name_lbl)
row_layout.addStretch(1)
value_lbl = QLabel(value)
style_role(value_lbl, "row-value")
row_layout.addWidget(value_lbl)
self.rows_layout.addWidget(row)
@@ -0,0 +1,146 @@
"""Settings dialog: Discord Rich Presence config + manual update check.
Both features live here on purpose (not on the main HUD) - they're
configure-once, not something you watch continuously."""
from __future__ import annotations
from PySide6.QtWidgets import (
QCheckBox,
QDialog,
QFormLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
QSpinBox,
QVBoxLayout,
)
from settings_store import ROTATION_KEYS, ROTATION_LABELS, SettingsStore
from update_checker import check_for_update
from version import APP_VERSION
class SettingsDialog(QDialog):
def __init__(self, settings: SettingsStore, parent=None) -> None:
super().__init__(parent)
self.settings = settings
self.setWindowTitle("Einstellungen")
self.setMinimumWidth(420)
root = QVBoxLayout(self)
root.setSpacing(14)
# -- Discord RPC ---------------------------------------------------
discord_box = QGroupBox("Discord Rich Presence")
discord_layout = QVBoxLayout(discord_box)
self.discord_enabled_cb = QCheckBox("Discord-Status anzeigen")
self.discord_enabled_cb.setChecked(settings.discord_enabled)
discord_layout.addWidget(self.discord_enabled_cb)
form = QFormLayout()
self.client_id_edit = QLineEdit(settings.discord_client_id)
self.client_id_edit.setPlaceholderText("Discord Application Client ID")
form.addRow("Client ID:", self.client_id_edit)
self.interval_spin = QSpinBox()
self.interval_spin.setRange(5, 120)
self.interval_spin.setSuffix(" s")
self.interval_spin.setValue(settings.discord_rotation_interval_s)
form.addRow("Wechsel alle:", self.interval_spin)
discord_layout.addLayout(form)
hint = QLabel(
"Client ID kommt aus dem Discord Developer Portal "
"(discord.com/developers/applications → deine App → General Information)."
)
hint.setProperty("role", "dim")
hint.setWordWrap(True)
discord_layout.addWidget(hint)
discord_layout.addWidget(QLabel("In der Rotation zeigen:"))
self.rotation_checkboxes: dict[str, QCheckBox] = {}
for key in ROTATION_KEYS:
cb = QCheckBox(ROTATION_LABELS[key])
cb.setChecked(settings.rotation_enabled(key))
discord_layout.addWidget(cb)
self.rotation_checkboxes[key] = cb
root.addWidget(discord_box)
# -- Updates ---------------------------------------------------------
update_box = QGroupBox("Updates")
update_layout = QVBoxLayout(update_box)
version_label = QLabel(f"Installierte Version: {APP_VERSION}")
version_label.setProperty("role", "dim")
update_layout.addWidget(version_label)
url_form = QFormLayout()
self.manifest_url_edit = QLineEdit(settings.update_manifest_url)
self.manifest_url_edit.setPlaceholderText("https://.../fhud-version.json")
url_form.addRow("Update-Quelle:", self.manifest_url_edit)
update_layout.addLayout(url_form)
check_row = QHBoxLayout()
self.check_button = QPushButton("Auf Updates prüfen")
self.check_button.setProperty("role", "primary")
self.check_button.clicked.connect(self._on_check_updates)
check_row.addWidget(self.check_button)
check_row.addStretch(1)
update_layout.addLayout(check_row)
self.update_result_label = QLabel("")
self.update_result_label.setWordWrap(True)
self.update_result_label.setProperty("role", "dim")
update_layout.addWidget(self.update_result_label)
self.download_button = QPushButton("Download öffnen")
self.download_button.hide()
self.download_button.clicked.connect(self._open_download)
update_layout.addWidget(self.download_button)
root.addWidget(update_box)
# -- Save/Close --------------------------------------------------------
button_row = QHBoxLayout()
button_row.addStretch(1)
save_btn = QPushButton("Speichern")
save_btn.setProperty("role", "primary")
save_btn.clicked.connect(self._save_and_close)
button_row.addWidget(save_btn)
root.addLayout(button_row)
self._pending_download_url = None
def _on_check_updates(self) -> None:
self.check_button.setEnabled(False)
self.update_result_label.setText("Prüfe…")
self.download_button.hide()
from PySide6.QtWidgets import QApplication
QApplication.instance().processEvents()
result = check_for_update(self.manifest_url_edit.text().strip())
self.update_result_label.setText(result.message)
if result.ok and result.update_available and result.download_url:
self._pending_download_url = result.download_url
self.download_button.show()
self.check_button.setEnabled(True)
def _open_download(self) -> None:
if self._pending_download_url:
from PySide6.QtGui import QDesktopServices
from PySide6.QtCore import QUrl
QDesktopServices.openUrl(QUrl(self._pending_download_url))
def _save_and_close(self) -> None:
self.settings.discord_enabled = self.discord_enabled_cb.isChecked()
self.settings.discord_client_id = self.client_id_edit.text()
self.settings.discord_rotation_interval_s = self.interval_spin.value()
for key, cb in self.rotation_checkboxes.items():
self.settings.set_rotation_enabled(key, cb.isChecked())
self.settings.update_manifest_url = self.manifest_url_edit.text()
self.accept()
@@ -0,0 +1,75 @@
"""HUD tiles - the two shapes the "gauge cluster" hero section is built
from: one wide masthead reading (current vehicle) and several compact
gauges side by side (money, farm value, time), the way a tractor's dash
has one big central display flanked by smaller round gauges."""
from __future__ import annotations
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QVBoxLayout
class StatTile(QFrame):
def __init__(self, icon: str, label: str, variant: str = "hero", parent=None) -> None:
super().__init__(parent)
self.variant = variant
self.setProperty("role", "tile-hero" if variant == "hero" else "tile")
if variant == "hero":
layout = QHBoxLayout(self)
layout.setContentsMargins(16, 14, 16, 14)
layout.setSpacing(14)
icon_label = QLabel(icon)
icon_label.setStyleSheet("font-size: 30px;")
icon_label.setFixedWidth(38)
layout.addWidget(icon_label)
text_col = QVBoxLayout()
text_col.setSpacing(2)
self.label = QLabel(label)
self.label.setProperty("role", "tile-label")
text_col.addWidget(self.label)
self.value = QLabel("–")
self.value.setProperty("role", "tile-value-lg")
self.value.setWordWrap(True)
text_col.addWidget(self.value)
layout.addLayout(text_col, 1)
else:
layout = QVBoxLayout(self)
layout.setContentsMargins(10, 12, 10, 12)
layout.setSpacing(4)
layout.setAlignment(Qt.AlignmentFlag.AlignHCenter)
icon_label = QLabel(icon)
icon_label.setStyleSheet("font-size: 20px;")
icon_label.setAlignment(Qt.AlignmentFlag.AlignHCenter)
layout.addWidget(icon_label)
self.label = QLabel(label)
self.label.setProperty("role", "tile-label")
self.label.setAlignment(Qt.AlignmentFlag.AlignHCenter)
layout.addWidget(self.label)
self.value = QLabel("–")
self.value.setProperty("role", "tile-value")
self.value.setAlignment(Qt.AlignmentFlag.AlignHCenter)
self.value.setWordWrap(True)
layout.addWidget(self.value)
self.sub_value = QLabel("")
self.sub_value.setProperty("role", "dim")
self.sub_value.setAlignment(Qt.AlignmentFlag.AlignHCenter)
self.sub_value.hide()
layout.addWidget(self.sub_value)
def set_value(self, text: str) -> None:
self.value.setText(text)
def set_sub_value(self, text: str) -> None:
"""Compact tiles only: a small line under the value (e.g. the day
number under the clock) - keeps the big value short enough to
never wrap in a narrow gauge tile."""
self.sub_value.setText(text)
self.sub_value.setVisible(bool(text))
@@ -0,0 +1,5 @@
{
"version": "1.0.1",
"url": "https://example.com/downloads/FarmHUD-Setup-1.0.1.exe",
"notes": "Kurze Liste was sich geändert hat."
}
+51
View File
@@ -0,0 +1,51 @@
; FarmHUD installer script (Inno Setup 6 - https://jrsoftware.org/isinfo.php).
;
; Build order:
; 1. cd ..\app && setup.bat (once, installs Python deps)
; 2. cd ..\app && build.bat (PyInstaller -> ..\app\dist\FarmHUD\)
; 3. Open this file in Inno Setup and click Compile (or: ISCC.exe farmhud.iss)
; -> produces Output\FarmHUD-Setup-<version>.exe
;
; AppId is a fixed random GUID so Windows recognizes upgrades/uninstalls
; correctly across versions - generate your own once (Tools > Generate GUID
; in Inno Setup) if you fork this, but never change it between releases.
#define MyAppName "FarmHUD"
#define MyAppVersion "1.0.0"
#define MyAppPublisher "FarmHUD"
#define MyAppExeName "FarmHUD.exe"
#define MyAppId "6E8B2B0C-6E36-4B0A-9A3B-6E7A6E6C9F41"
[Setup]
AppId={{#MyAppId}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
AppPublisher={#MyAppPublisher}
DefaultDirName={autopf}\{#MyAppName}
DefaultGroupName={#MyAppName}
UninstallDisplayIcon={app}\{#MyAppExeName}
OutputDir=Output
OutputBaseFilename=FarmHUD-Setup-{#MyAppVersion}
Compression=lzma2
SolidCompression=yes
WizardStyle=modern
SetupIconFile=..\app\assets\icon.ico
DisableProgramGroupPage=yes
ArchitecturesInstallIn64BitMode=x64compatible
[Languages]
Name: "german"; MessagesFile: "compiler:Languages\German.isl"
Name: "english"; MessagesFile: "compiler:Default.isl"
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"
[Files]
Source: "..\app\dist\FarmHUD\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}"
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#MyAppName}}"; Flags: nowait postinstall skipifsilent
@@ -0,0 +1,18 @@
@echo off
title FS25 Desktop Dashboard
cd /d "%~dp0desktop-app"
if exist ".venv\Scripts\python.exe" (
set "PYTHON_EXE=.venv\Scripts\python.exe"
) else (
set "PYTHON_EXE=python"
)
echo Starte FS25 Desktop Dashboard...
"%PYTHON_EXE%" main.py
if errorlevel 1 (
echo.
echo Start fehlgeschlagen. Falls das die erste Ausfuehrung ist, fuehre
echo zuerst "desktop-app\setup.bat" aus, um Python-Abhaengigkeiten zu installieren.
pause
)
+11
View File
@@ -0,0 +1,11 @@
@echo off
title FS25 Web Dashboard
cd /d "%~dp0server"
echo Starte FS25 Web Dashboard Server...
start "FS25 Dashboard Server" cmd /k node server.js
timeout /t 2 /nobreak >nul
start "" http://localhost:3925
exit
@@ -0,0 +1,25 @@
@echo off
title FS25 + Desktop Dashboard starten
set "FS25_EXE=C:\Program Files (x86)\Farming Simulator 2025\FarmingSimulator2025.exe"
if exist "%~dp0desktop-app\.venv\Scripts\python.exe" (
set "PYTHON_EXE=%~dp0desktop-app\.venv\Scripts\python.exe"
) else (
set "PYTHON_EXE=python"
)
echo Starte Desktop-Dashboard...
start "FS25 Desktop Dashboard" /D "%~dp0desktop-app" "%PYTHON_EXE%" main.py
if exist "%FS25_EXE%" (
echo Starte Farming Simulator 25...
start "" "%FS25_EXE%"
) else (
echo Farming Simulator 25 wurde nicht gefunden unter:
echo %FS25_EXE%
echo Bitte manuell ueber das FS25-Symbol starten.
pause
)
exit /b
@@ -0,0 +1,29 @@
@echo off
title FS25 + Dashboard starten
set "FS25_EXE=C:\Program Files (x86)\Farming Simulator 2025\FarmingSimulator2025.exe"
echo Pruefe, ob der Dashboard-Server schon laeuft...
netstat -ano | findstr ":3925" | findstr "LISTENING" >nul
if errorlevel 1 (
echo Starte Dashboard-Server...
start "FS25 Dashboard Server" /D "%~dp0server" cmd /k node server.js
timeout /t 2 /nobreak >nul
) else (
echo Dashboard-Server laeuft bereits.
)
echo Oeffne Dashboard im Browser...
start "" http://localhost:3925
if exist "%FS25_EXE%" (
echo Starte Farming Simulator 25...
start "" "%FS25_EXE%"
) else (
echo Farming Simulator 25 wurde nicht gefunden unter:
echo %FS25_EXE%
echo Bitte manuell ueber das FS25-Symbol starten.
pause
)
exit /b
+239
View File
@@ -0,0 +1,239 @@
# FS25 Web Dashboard
Ein Mod + eine App für **Farming Simulator 25**, die dir live zeigt:
Geschwindigkeit, Drehzahl, Tempomat, Tankfüllstand, Spielzeit, Wetter
(+ Vorschau, sofern das Spiel Vorhersagedaten liefert), Betriebs-/Kontostand
u.a. Es gibt zwei gleichwertige Anzeige-Varianten, die sich denselben Mod
teilen:
- **[`desktop-app/`](desktop-app/README.md)** – native Python-Desktop-App
(PySide6). Kein Node.js, kein Browser, kein Server nötig – die App liest
`live.json` direkt. **Empfohlen** für die normale Nutzung am Spiel-PC.
- **`server/` + `web/`** – die ursprüngliche Browser-Lösung (Node.js-Server
+ HTML/CSS/JS). Bleibt erhalten, weil sie sich zusätzlich im selben WLAN
von einem Handy/Tablet aus öffnen lässt (z. B. als zweites
Cockpit-Display).
## Wie es funktioniert
Farming Simulator läuft isoliert (Sandbox) und hat keinen eingebauten
Webserver für Mods. Deshalb besteht die Lösung aus zwei Teilen:
1. **`mod/FS25_FarmHUD`** – ein normaler FS25-Mod. Er verändert nichts
am Spiel, sondern schreibt 4×/Sekunde eine kleine JSON-Datei mit allen
Live-Daten nach:
`Dokumente/My Games/FarmingSimulator2025/modSettings/FS25_FarmHUD/live.json`
2. Eine der beiden Anzeigen oben liest diese Datei und zeigt sie an – die
Desktop-App direkt, die Web-Variante über einen kleinen Node.js-Server.
```
┌─ Desktop-App (Python, liest direkt) ──────┐
FS25 (Mod) --schreibt--> live.json
└─ Node-Server --HTTP--> Browser ───────────┘
```
## Installation
### Desktop-App (empfohlen)
Siehe [`desktop-app/README.md`](desktop-app/README.md) – kurz: Python
installieren, `desktop-app/setup.bat` einmal ausführen, danach
`Dashboard-Desktop-starten.bat` im Hauptordner.
### Browser-Variante
#### 1. Mod installieren
Kopiere den Ordner `mod/FS25_FarmHUD` in deinen FS25-Mods-Ordner:
```
Dokumente\My Games\FarmingSimulator2025\mods\FS25_FarmHUD
```
(Ein entpackter Ordner reicht für den Eigenbedarf – du musst ihn nicht
zippen. Falls du ihn doch als `.zip` fürs Modhub packen willst, muss die
ZIP-Datei `FS25_FarmHUD.zip` heißen und `modDesc.xml` direkt im Root
der ZIP liegen.)
Im Spiel dann unter **Mods** aktivieren und deinen Spielstand (neu) laden.
#### 2. Node.js installieren (falls noch nicht vorhanden)
Der Dashboard-Server braucht [Node.js](https://nodejs.org/) (LTS-Version).
Kurzer Check im Terminal:
```bash
node --version
```
#### 3. Server starten
```bash
cd server
node server.js
```
Die Konsole zeigt dir die URL(s) an, z. B.:
```
http://localhost:3925
http://192.168.1.23:3925 (andere Geräte im selben Netzwerk, z. B. Handy/Tablet)
```
Einfach die `localhost`-Adresse im Browser öffnen, während FS25 läuft.
> Läuft dein Dokumente-Ordner über OneDrive um, sucht der Server automatisch
> auch dort. Falls er die Datei trotzdem nicht findet, setz den Pfad manuell:
> `FS25_LIVE_JSON="C:\Pfad\zu\live.json" node server.js`
## Was im Dashboard drin ist
- **Live-Karte**: alle Fahrzeuge als Pfeile (Richtung = Fahrtrichtung) auf dem
echten Kartenbild, zoombar (Mausrad) und verschiebbar (Ziehen), mit
"Zentrieren"-Button. Grün = dein Fahrzeug, Orange = ausgewählt, Blau =
andere, Lila = du zu Fuß.
- **Ausgewähltes Fahrzeug**: folgt automatisch dem Fahrzeug, in dem du
gerade sitzt ("📍 Mein Fahrzeug"-Button zum Zurückwechseln nach manueller
Auswahl). Tacho, Drehzahlmesser, Tempomat, Motorlast, Betriebsstunden,
Neu-/Verkaufswert, Tank/Schaden/Verschmutzung als Balken, alle angekoppelten
Geräte inkl. deren Füllstand (auch mehrgliedrige Anhänger-Ketten), sowie ein
60-Sekunden-Geschwindigkeitsverlauf.
- **Zeit**: Uhrzeit inkl. Minuten, Tag, Saison, Zeitraffer-Faktor.
- **Wetter**: aktuelles Wetter, Regen-/Schnee-/Nacht-Badges + (falls vom
Spiel geliefert) eine Mehrtages-Vorschau.
- **Betrieb**: Betriebsname, Kontostand, Anzahl & Wert eigener Grundstücke.
- **Lager & Tierhaltung**: Füllstände aller Silos nach Fruchttyp, Tierzahl
je Stall.
- **Fahrzeugtabelle**: alle Fahrzeuge auf einen Blick, sortiert nach
Geschwindigkeit, klickbar, inkl. Schaden-Spalte.
- Extras: Hell/Dunkel-Umschalter, Vollbildmodus (gut für einen zweiten
Monitor/Tablet als Cockpit-Display), Verbindungsstatus-Anzeige.
## Ehrlicher Hinweis zu Wetter/Zeit-Daten
Fahrzeugdaten (Geschwindigkeit, Drehzahl, Tempomat, Tank) kommen aus der
**offiziell dokumentierten** Scripting-API von Giants (GDN) und sind stabil.
Die Wetter-/Zeit-Daten (`g_currentMission.environment`) sind dagegen **nicht
offiziell dokumentiert** – Giants veröffentlicht dafür keine Scripting-Klasse,
die Community musste das schon immer durch Ausprobieren herausfinden. Der Mod
versucht deshalb mehrere bekannte Feldnamen automatisch (mit Absicherung
gegen Abstürze), zeigt aber ggf. „Unbekannt" an, falls sich das mit einem
Spiel-Update geändert hat.
Wenn Wetter oder Uhrzeit falsch/leer sind, gib im Spiel in der Konsole
(**~** Taste, ggf. vorher `gsDebugConsole` in `game.xml` aktivieren) ein:
```
fhudDumpEnvironment
```
Das schreibt eine `debug_environment.json` in denselben `modSettings`-Ordner
mit der **echten** Struktur deiner Spielversion – damit lässt sich der Mod
in Sekunden korrigieren.
## Mehrspieler
Der Mod läuft auf dem Client, der ihn installiert hat, und zeigt dessen
Sicht auf die Welt (inkl. aller in Reichweite synchronisierten Fahrzeuge).
Auf einem Dedicated Server bräuchte man den Mod zusätzlich dort – Kontakt
gerne melden, falls das gebraucht wird, das ist mit dieser Basis gut
erweiterbar.
## Verfügbare Live-Daten (`live.json`)
Die Mod zieht bewusst deutlich mehr aus dem Spiel, als das Dashboard aktuell
anzeigt – damit neue Anzeige-Ideen sich (fast) immer nur in `web/*.js`
umsetzen lassen, ohne die Mod anzufassen oder das Spiel neu zu laden. Rufe
`http://localhost:3925/api/live` direkt im Browser auf, um die aktuelle
Rohstruktur zu sehen. Kurzüberblick:
| Feld | Inhalt |
|---|---|
| `mission` | Karten-ID/-Größe, aktueller Betrieb (Name, Kontostand), Spielstand-Index/-Name, Spielzeit (`playTimeMinutes`/`playTimeHours`), Multiplayer-Flag + Servername |
| `session` | Schwierigkeitsgrad-/Spieloptionen aus der Spielstand-Erstellung: `economicDifficulty`, `difficulty`, `growthMode`, `plowingRequiredEnabled`, `stonesEnabled`, `weedsEnabled`, `trafficEnabled`, `fuelUsage`, `helperBuyFruitEnabled`, `automaticMotorStartEnabled` |
| `farms[]` | Jeder Betrieb, dem etwas gehört: `id`, `name`, `money`, `loan` (Kredit), `loanMaximum` (best-effort) |
| `farmlands[]` | Jede Grundstücksparzelle: `id`, `name`, `price`, `isOwned`, `farmId` |
| `silos[]` | Jedes Lager/Silo: `name`, `ownerFarmId`, `fillTypes[]` (Typ + Füllstand) |
| `husbandries[]` | Jeder Tierstall: `name`, `ownerFarmId`, `numAnimals`, `maxNumAnimals`, best-effort `productivityPercent`/`happinessPercent`/`healthPercent`, `clusters[]` (Aufschlüsselung nach Subtyp/Alter/Geschlecht, falls verfügbar) |
| `productions[]` | Produktionsketten: Rezepte (Input/Output, Status) + Lagerbestand |
| `prices` | Aktueller Verkaufspreis/Liter für jeden Fülltyp, der im Snapshot vorkommt (Silos + Fahrzeugtanks) – nicht die komplette ~100+ Fülltyp-Tabelle |
| `players[]` | Jeder verbundene Spieler: `nickname`, `farmId`, `isMasterUser`, `isAdmin` (auch im Singleplayer ein Eintrag) |
| `missions[]` | Aktive Feldaufträge/Contracts: `type`, `fieldId`, `reward`, `status`, `farmId`, `timeRemaining` (best-effort) |
| `player` | grobe Weltposition, `isControllingVehicle` |
| `time` | Tag, Uhrzeit, Zeitraffer, Saison, `dayInPeriod`/`seasonProgressPercent` |
| `weather` | aktuelles Wetter, Temperatur, Regen/Schnee, Wind (`windSpeed`/`windDirectionDeg`, best-effort), Vorschau (best-effort) |
| `vehicles[]` | siehe unten |
| `fields[]` | reale Feldgrenzen (Polygon), aktuelle Frucht + Reifegrad, `ownerFarmId`/`farmlandId` |
**Pro Fahrzeug** (`vehicles[]`): `id`, `name`, `typeName`, `x`/`y`/`z`,
`headingRad`, `speedKmh`, `isControlledByPlayer`, `isOccupiedByAnyPlayer`
(irgendein Spieler drin, nicht nur du – nützlich im Multiplayer),
`ownerFarmId`, `rpm`/`rpmPercent`, `motorStarted`, `motorLoadPercent`,
Tempomat (`cruiseControlActive`/`Speed`/`MaxSpeed`), `fuelLevel`/
`fuelCapacity`, **`fillUnits[]`** (ALLE Tanks – Erntegut, Saatgut, Dünger,
Milch, … nicht nur der Tank), `damagePercent`, `dirtPercent`,
`operatingHours`, `price`/`sellPrice`, `attachedImplementIds[]` (was gerade
angehängt ist), `attacherVehicleId` (woran DIESES Fahrzeug selbst hängt),
`isTurnedOn` (Spritzen/Sämaschinen etc. an/aus), `isFolded` (Transport-/
Arbeitsbreite), `lightsTypesMask`/`lightsLowBeamOn`/`lightsHighBeamOn`
(best-effort).
Manche Felder fehlen je nach Fahrzeugtyp (ein Anhänger hat z. B. kein `rpm`)
oder je nach Kartenmod (z. B. Wetter-Vorschau) – das ist beabsichtigt, nicht
kaputt: fehlende Werte tauchen im JSON einfach nicht auf.
Zwei Debug-Konsolenbefehle (**~**-Taste im Spiel) schreiben die *echte*
Rohstruktur unsicherer Felder in eine Datei im `modSettings`-Ordner, damit
sich Feldnamen bei Bedarf schnell korrigieren lassen:
`fhudDumpEnvironment` (Wetter/Zeit) und `fhudDumpFarmStats` (Betrieb/Kredit).
## Kartenbild
`web/assets/map.jpg` ist das echte Übersichtsbild deiner aktuellen Karte
(aus der Map-Mod-Datei extrahiert, `maps/<mapname>/overview.dds`) und wird
automatisch als Hintergrund gezeichnet, solange die Mod eine `mapSize`
liefert (das Bild deckt exakt das Quadrat von -mapSize/2 bis +mapSize/2 ab,
in dem sich alle Fahrzeugkoordinaten bewegen). Fehlt die Datei, fällt die
Karte automatisch auf ein einfaches Gitter zurück – nichts bricht.
**Bei einem Kartenwechsel** (andere Map-Mod oder Vanilla-Karte) einfach
Bescheid geben, welche Karte du spielst – dann extrahiere ich das passende
`overview.dds` aus der jeweiligen Map-Mod-Datei, wandle es um und ersetze
`web/assets/map.jpg`.
## Ideen für später
- Push-Benachrichtigungen bei niedrigem Tank o. Ä.
- Historische Aufzeichnung (z. B. Betriebsstunden, gefahrene Strecke).
## Projektstruktur
```
FS25-WebDashboard/
├── mod/FS25_FarmHUD/ ← in den FS25-Mods-Ordner kopieren
│ ├── modDesc.xml
│ ├── icon_webdashboard.dds
│ └── scripts/
│ ├── Json.lua
│ └── WebDashboard.lua
├── desktop-app/ ← Python-Desktop-App (empfohlen), siehe eigene README
│ ├── main.py
│ ├── main_window.py
│ ├── live_data.py
│ ├── state.py
│ ├── formatting.py
│ ├── theme.py
│ ├── widgets/
│ ├── requirements.txt
│ └── setup.bat
├── Dashboard-Desktop-starten.bat
├── FS25-und-Dashboard-Desktop-starten.bat
├── server/ ← node server.js hier ausführen (Browser-Variante)
│ ├── server.js
│ └── package.json
└── web/ ← wird vom Server ausgeliefert
├── index.html
├── style.css
└── app.js
```
+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
Binary file not shown.
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="utf-8" standalone="no" ?>
<modDesc descVersion="92">
<author>christianolah56</author>
<version>1.4.0.0</version>
<title>
<en>FarmHUD</en>
<de>FarmHUD</de>
</title>
<description>
<en><![CDATA[
Exports live telemetry (speed, RPM, cruise control, fuel, all vehicles on the map,
farm finances, ingame time and weather, and more) to a small JSON file so the
FarmHUD desktop app - or a browser-based dashboard on your PC/phone/tablet -
can show it in real time.
This mod does NOT change any gameplay. It only reads data and writes it to:
Documents/My Games/FarmingSimulator2025/modSettings/FS25_FarmHUD/live.json
You need the separate FarmHUD app (or the "server" + "web" dashboard) from the
same download to actually view this data - see the README.
]]></en>
<de><![CDATA[
Exportiert Live-Daten (Geschwindigkeit, Drehzahl, Tempomat, Tankfüllstand, alle
Fahrzeuge auf der Karte, Betriebsfinanzen, Spielzeit und Wetter u.v.m.) in eine
kleine JSON-Datei, damit die FarmHUD-Desktop-App - oder ein browserbasiertes
Dashboard auf deinem PC/Handy/Tablet - sie in Echtzeit anzeigen kann.
Dieser Mod verändert keinerlei Spielverhalten. Er liest nur Daten und schreibt sie nach:
Dokumente/My Games/FarmingSimulator2025/modSettings/FS25_FarmHUD/live.json
Du brauchst die separate FarmHUD-App (oder den "server" + "web" Dashboard-Teil)
aus demselben Download, um diese Daten zu sehen - siehe README.
]]></de>
</description>
<iconFilename>icon_farmhud.dds</iconFilename>
<multiplayer supported="true" />
<extraSourceFiles>
<sourceFile filename="scripts/Json.lua" />
<sourceFile filename="scripts/FarmHUD.lua" />
</extraSourceFiles>
</modDesc>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,108 @@
--[[
Json.lua - minimal, dependency-free JSON encoder for FS25_FarmHUD.
Farming Simulator's Lua sandbox does not ship a JSON library, so we bring our
own tiny encoder. Only encoding is needed (the mod never reads JSON back),
so this intentionally does not implement a decoder.
Usage:
local text = Json.encode({ foo = "bar", list = {1, 2, 3} })
]]
Json = {}
local ESCAPES = {
["\\"] = "\\\\",
["\""] = "\\\"",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t",
}
local function encodeString(s)
s = tostring(s)
s = s:gsub('[\\"\n\r\t]', ESCAPES)
-- strip any other control characters that would produce invalid JSON
s = s:gsub("[\1-\31]", "")
return '"' .. s .. '"'
end
local function isArray(t)
local count = 0
for _ in pairs(t) do
count = count + 1
end
if count == 0 then
return true -- treat empty tables as empty arrays ([]) rather than {}
end
for i = 1, count do
if t[i] == nil then
return false
end
end
return true
end
local encodeValue
local function encodeArray(t, out)
out[#out + 1] = "["
local n = #t
for i = 1, n do
if i > 1 then
out[#out + 1] = ","
end
encodeValue(t[i], out)
end
out[#out + 1] = "]"
end
local function encodeObject(t, out)
out[#out + 1] = "{"
local first = true
for k, v in pairs(t) do
if not first then
out[#out + 1] = ","
end
first = false
out[#out + 1] = encodeString(k)
out[#out + 1] = ":"
encodeValue(v, out)
end
out[#out + 1] = "}"
end
encodeValue = function(v, out)
local t = type(v)
if v == nil then
out[#out + 1] = "null"
elseif t == "string" then
out[#out + 1] = encodeString(v)
elseif t == "number" then
if v ~= v or v == math.huge or v == -math.huge then
out[#out + 1] = "null" -- NaN / Infinity are not valid JSON
else
out[#out + 1] = tostring(v)
end
elseif t == "boolean" then
out[#out + 1] = v and "true" or "false"
elseif t == "table" then
if isArray(v) then
encodeArray(v, out)
else
encodeObject(v, out)
end
else
-- functions, userdata, threads: not representable, encode as null
out[#out + 1] = "null"
end
end
---Encode a Lua value (typically a table) as a JSON string.
---@param value any
---@return string
function Json.encode(value)
local out = {}
encodeValue(value, out)
return table.concat(out)
end
+10
View File
@@ -0,0 +1,10 @@
{
"name": "fs25-web-dashboard-server",
"version": "1.0.0",
"description": "Local bridge server for the FS25 Web Dashboard mod - serves the dashboard and re-exposes the mod's live.json as an HTTP API.",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"license": "MIT"
}
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env node
/**
* FS25 Web Dashboard - local bridge server
*
* Serves the static dashboard (../web) and re-reads the mod's live.json file
* on every request to /api/live, so the browser can poll it. No dependencies
* on purpose - just `node server.js`.
*/
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const os = require('os');
const PORT = process.env.PORT ? Number(process.env.PORT) : 3925;
const WEB_DIR = path.join(__dirname, '..', 'web');
// --- Locate the mod's live.json -------------------------------------------
function candidateLiveDataPaths() {
const home = os.homedir();
const candidates = [];
if (process.env.FS25_LIVE_JSON) {
candidates.push(process.env.FS25_LIVE_JSON);
}
// OneDrive can redirect "Documents" - check both the plain and OneDrive path.
candidates.push(path.join(home, 'Documents', 'My Games', 'FarmingSimulator2025', 'modSettings', 'FS25_FarmHUD', 'live.json'));
candidates.push(path.join(home, 'OneDrive', 'Documents', 'My Games', 'FarmingSimulator2025', 'modSettings', 'FS25_FarmHUD', 'live.json'));
candidates.push(path.join(home, 'OneDrive', 'Dokumente', 'My Games', 'FarmingSimulator2025', 'modSettings', 'FS25_FarmHUD', 'live.json'));
return candidates;
}
function resolveLiveDataPath() {
for (const candidate of candidateLiveDataPaths()) {
if (candidate && fs.existsSync(candidate)) {
return candidate;
}
}
// Fall back to the first guess even if it doesn't exist yet - the file
// only appears once you load a savegame with the mod active.
return candidateLiveDataPaths()[0];
}
let liveDataPath = resolveLiveDataPath();
console.log('[web-dashboard] reading live data from: ' + liveDataPath);
// --- Static file serving ----------------------------------------------------
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.ico': 'image/x-icon',
};
function serveStatic(req, res) {
let requestPath = decodeURIComponent(req.url.split('?')[0]);
if (requestPath === '/') {
requestPath = '/index.html';
}
const fullPath = path.normalize(path.join(WEB_DIR, requestPath));
if (!fullPath.startsWith(WEB_DIR)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
fs.readFile(fullPath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found: ' + requestPath);
return;
}
const ext = path.extname(fullPath).toLowerCase();
res.writeHead(200, { 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream' });
res.end(data);
});
}
function serveLiveData(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cache-Control', 'no-store');
// re-resolve in case the game (re)creates the file after this server started
if (!fs.existsSync(liveDataPath)) {
const resolved = resolveLiveDataPath();
if (resolved) {
liveDataPath = resolved;
}
}
fs.readFile(liveDataPath, 'utf8', (err, data) => {
if (err) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
connected: false,
error: 'live.json not found yet - start Farming Simulator 25 with the WebDashboard mod active and load a savegame.',
expectedPath: liveDataPath,
}));
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(data);
});
}
const server = http.createServer((req, res) => {
if (req.url.startsWith('/api/live')) {
serveLiveData(req, res);
return;
}
serveStatic(req, res);
});
server.listen(PORT, () => {
const nets = os.networkInterfaces();
const lanAddresses = [];
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
if (net.family === 'IPv4' && !net.internal) {
lanAddresses.push(net.address);
}
}
}
console.log('');
console.log(' FS25 Web Dashboard running:');
console.log(' http://localhost:' + PORT);
for (const addr of lanAddresses) {
console.log(' http://' + addr + ':' + PORT + ' (other devices on your network, e.g. phone/tablet)');
}
console.log('');
});
+953
View File
@@ -0,0 +1,953 @@
(() => {
'use strict';
const POLL_INTERVAL_MS = 500;
const GAUGE_ARC_LENGTH = Math.PI * 80; // pi * radius(80) - matches the arc path in index.html exactly
const SPEED_HISTORY_WINDOW_MS = 60000;
const WEATHER_ICONS = {
SUN: '☀️',
PARTIALLY_CLOUDY: '🌤️',
CLOUDY: '☁️',
RAIN: '🌧️',
SNOW: '❄️',
HAIL: '🧊',
TWISTER: '🌪️',
THUNDER: '⛈️',
};
const WEATHER_LABELS_DE = {
SUN: 'Sonnig',
PARTIALLY_CLOUDY: 'Teils bewölkt',
CLOUDY: 'Bewölkt',
RAIN: 'Regen',
SNOW: 'Schnee',
HAIL: 'Hagel',
TWISTER: 'Tornado',
THUNDER: 'Gewitter',
};
/** @type {{selectedVehicleId: any, speedHistory: {t:number, v:number}[], lastData: any}} */
const state = {
selectedVehicleId: null,
followMyVehicle: true, // true = panel always shows the vehicle you're currently driving
speedHistory: [],
lastData: null,
};
// ---------------------------------------------------------------------
// DOM refs
// ---------------------------------------------------------------------
const el = (id) => document.getElementById(id);
const statusDot = el('statusDot');
const statusText = el('statusText');
const vehicleCountEl = el('vehicleCount');
const vehicleNameEl = el('vehicleName');
const vehicleTypeEl = el('vehicleType');
const followMyVehicleBtn = el('followMyVehicleBtn');
const manualSelectHintEl = el('manualSelectHint');
const speedValueEl = el('speedValue');
const speedGaugeFill = el('speedGaugeFill');
const rpmValueEl = el('rpmValue');
const rpmGaugeFill = el('rpmGaugeFill');
const cruiseValueEl = el('cruiseValue');
const cruiseChip = el('cruiseChip');
const motorValueEl = el('motorValue');
const loadValueEl = el('loadValue');
const fuelTextEl = el('fuelText');
const fuelBarEl = el('fuelBar');
const damageTextEl = el('damageText');
const damageBarEl = el('damageBar');
const dirtTextEl = el('dirtText');
const dirtBarEl = el('dirtBar');
const ownFillUnitsListEl = el('ownFillUnitsList');
const implementsListEl = el('implementsList');
const hoursValueEl = el('hoursValue');
const priceValueEl = el('priceValue');
const sellPriceValueEl = el('sellPriceValue');
const positionValueEl = el('positionValue');
const headingValueEl = el('headingValue');
const mapIdTextEl = el('mapIdText');
const speedHistoryCanvas = el('speedHistory');
const speedHistoryCtx = speedHistoryCanvas.getContext('2d');
const clockText = el('clockText');
const dayText = el('dayText');
const seasonText = el('seasonText');
const periodTextEl = el('periodText');
const scaleText = el('scaleText');
const weatherIcon = el('weatherIcon');
const weatherType = el('weatherType');
const weatherTemp = el('weatherTemp');
const weatherBadgesEl = el('weatherBadges');
const weatherExtraEl = el('weatherExtra');
const forecastStrip = el('forecastStrip');
const farmName = el('farmName');
const farmMoney = el('farmMoney');
const farmlandCountEl = el('farmlandCount');
const farmlandValueEl = el('farmlandValue');
const playerStatusValueEl = el('playerStatusValue');
const otherFarmsHeadEl = el('otherFarmsHead');
const otherFarmsListEl = el('otherFarmsList');
const farmlandListEl = el('farmlandList');
const siloListEl = el('siloList');
const husbandryListEl = el('husbandryList');
const productionListEl = el('productionList');
const vehicleTableBody = el('vehicleTableBody');
// ---------------------------------------------------------------------
// Theme + fullscreen
// ---------------------------------------------------------------------
const THEME_KEY = 'fs25dash.theme';
function applyStoredTheme() {
try {
const saved = localStorage.getItem(THEME_KEY);
if (saved) document.documentElement.setAttribute('data-theme', saved);
} catch (e) { /* localStorage may be unavailable, ignore */ }
}
applyStoredTheme();
el('themeToggle').addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
const next = current === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', next);
try { localStorage.setItem(THEME_KEY, next); } catch (e) { /* ignore */ }
});
el('fullscreenBtn').addEventListener('click', () => {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch(() => {});
} else {
document.exitFullscreen().catch(() => {});
}
});
// ---------------------------------------------------------------------
// Collapsible panels (state remembered per panel across reloads)
// ---------------------------------------------------------------------
const COLLAPSE_KEY_PREFIX = 'fs25dash.collapsed.';
document.querySelectorAll('.panel[data-panel-id]').forEach((panel) => {
const id = panel.dataset.panelId;
let collapsed = false;
try { collapsed = localStorage.getItem(COLLAPSE_KEY_PREFIX + id) === '1'; } catch (e) { /* ignore */ }
panel.classList.toggle('collapsed', collapsed);
const toggleBtn = panel.querySelector(':scope > .panel-header > .panel-toggle');
if (toggleBtn) {
toggleBtn.addEventListener('click', () => {
const nowCollapsed = panel.classList.toggle('collapsed');
try { localStorage.setItem(COLLAPSE_KEY_PREFIX + id, nowCollapsed ? '1' : '0'); } catch (e) { /* ignore */ }
// A panel that was hidden (display:none) had a 0x0 canvas inside it -
// force a fresh render once it's visible again so the map/sparkline
// pick up their real size immediately instead of waiting for the
// next poll.
if (!nowCollapsed && state.lastData) onData(state.lastData);
});
}
});
// ---------------------------------------------------------------------
// Polling
// ---------------------------------------------------------------------
async function pollOnce() {
try {
const res = await fetch('/api/live', { cache: 'no-store' });
const data = await res.json();
state.lastData = data;
onData(data);
setStatus(data.connected !== false, data);
} catch (err) {
setStatus(false, null);
}
}
function setStatus(live, data) {
statusDot.classList.toggle('live', !!live);
if (live) {
statusText.textContent = 'Live';
} else if (data && data.error) {
statusText.textContent = 'Warte auf Spiel…';
} else {
statusText.textContent = 'Keine Verbindung zum Server';
}
}
setInterval(pollOnce, POLL_INTERVAL_MS);
pollOnce();
// ---------------------------------------------------------------------
// Main render dispatch
// ---------------------------------------------------------------------
function onData(data) {
if (!data) return;
const vehicles = Array.isArray(data.vehicles) ? data.vehicles : [];
vehicleCountEl.textContent = vehicles.length + (vehicles.length === 1 ? ' Fahrzeug' : ' Fahrzeuge');
mapIdTextEl.textContent = data.mission && data.mission.mapId ? ('· ' + data.mission.mapId) : '';
ensureSelection(vehicles, data.controlledVehicleId);
renderVehicleTable(vehicles);
renderSelectedVehicle(vehicles);
renderTime(data.time);
renderWeather(data.weather, data.time);
renderFarm(data.mission, data.farmlands, data.farms);
renderStorage(data.silos, data.husbandries, data.productions, data.farms);
renderPlayerStatus(data.player);
}
function renderPlayerStatus(player) {
if (!player) {
playerStatusValueEl.textContent = '–';
return;
}
if (player.isControllingVehicle) {
playerStatusValueEl.textContent = 'im Fahrzeug';
} else if (typeof player.x === 'number' && typeof player.z === 'number') {
playerStatusValueEl.textContent = 'zu Fuß (' + Math.round(player.x) + ', ' + Math.round(player.z) + ')';
} else {
playerStatusValueEl.textContent = 'zu Fuß';
}
}
function ensureSelection(vehicles, controlledVehicleId) {
// "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 to the manual/fallback logic
// below) until you get back in.
if (state.followMyVehicle && controlledVehicleId != null && vehicles.some((v) => v.id === controlledVehicleId)) {
selectVehicle(controlledVehicleId, { manual: false });
return;
}
if (state.selectedVehicleId != null && vehicles.some((v) => v.id === state.selectedVehicleId)) {
return;
}
if (controlledVehicleId != null && vehicles.some((v) => v.id === controlledVehicleId)) {
selectVehicle(controlledVehicleId, { manual: false });
return;
}
if (vehicles.length > 0) {
selectVehicle(vehicles[0].id, { manual: false });
} else {
state.selectedVehicleId = null;
}
}
/**
* @param {*} id vehicle id to show in the main panel / highlight
* @param {{manual?: boolean}} [opts] pass {manual: true} for an explicit
* user click - this turns follow-mode off so the pick sticks even while
* driving. Internal/automatic selections omit this (or pass false).
*/
function selectVehicle(id, opts) {
if (state.selectedVehicleId !== id) {
state.speedHistory = [];
}
state.selectedVehicleId = id;
if (opts && opts.manual) {
state.followMyVehicle = false;
}
}
function followMyVehicleNow() {
state.followMyVehicle = true;
if (state.lastData) onData(state.lastData);
}
el('followMyVehicleBtn').addEventListener('click', followMyVehicleNow);
// ---------------------------------------------------------------------
// Canvas helpers (still used by the speed sparkline below)
// ---------------------------------------------------------------------
function resizeCanvasToDisplaySize(canvas) {
const ratio = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
const width = Math.max(1, Math.round(rect.width * ratio));
const height = Math.max(1, Math.round(rect.height * ratio));
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
return ratio;
}
function getCssVar(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || '#888';
}
// ---------------------------------------------------------------------
// Vehicle table
// ---------------------------------------------------------------------
function renderVehicleTable(vehicles) {
vehicleTableBody.innerHTML = '';
const sorted = [...vehicles].sort((a, b) => (a.name || '').localeCompare(b.name || '', 'de'));
for (const v of sorted) {
const tr = document.createElement('tr');
if (v.id === state.selectedVehicleId) tr.classList.add('selected');
tr.addEventListener('click', () => { selectVehicle(v.id, { manual: true }); if (state.lastData) onData(state.lastData); });
tr.appendChild(cell(v.name || 'Unbenannt'));
tr.appendChild(cell(isDrivable(v) ? formatNumber(v.speedKmh, 0) : '–'));
tr.appendChild(cell(formatNumber(v.rpm, 0)));
tr.appendChild(cell(v.cruiseControlActive ? `an (${formatNumber(v.cruiseControlSpeed, 0)})` : '–'));
tr.appendChild(cell(formatFuel(v)));
const damageCell = cell(typeof v.damagePercent === 'number' ? Math.round(Math.max(0, v.damagePercent)) + '%' : '–');
if (typeof v.damagePercent === 'number' && v.damagePercent >= 50) {
damageCell.style.color = 'var(--danger)';
damageCell.style.fontWeight = '600';
}
tr.appendChild(damageCell);
vehicleTableBody.appendChild(tr);
}
if (sorted.length === 0) {
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colSpan = 6;
td.textContent = 'Keine Fahrzeuge geladen – starte das Spiel mit dem WebDashboard-Mod und lade einen Spielstand.';
td.style.color = 'var(--text-dim)';
tr.appendChild(td);
vehicleTableBody.appendChild(tr);
}
}
function cell(text) {
const td = document.createElement('td');
td.textContent = text;
return td;
}
// 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.
function isDrivable(v) {
return typeof v.motorStarted === 'boolean' || typeof v.cruiseControlActive === 'boolean';
}
function formatFuel(v) {
if (typeof v.fuelLevel !== 'number' || typeof v.fuelCapacity !== 'number' || v.fuelCapacity <= 0) {
return '–';
}
return Math.round((v.fuelLevel / v.fuelCapacity) * 100) + '%';
}
// ---------------------------------------------------------------------
// Selected vehicle panel
// ---------------------------------------------------------------------
function renderSelectedVehicle(vehicles) {
manualSelectHintEl.hidden = state.followMyVehicle;
followMyVehicleBtn.classList.toggle('active', state.followMyVehicle);
const v = vehicles.find((x) => x.id === state.selectedVehicleId);
if (!v) {
vehicleNameEl.textContent = 'Kein Fahrzeug ausgewählt';
vehicleTypeEl.textContent = '';
setGauge(speedGaugeFill, 0);
setGauge(rpmGaugeFill, 0);
speedValueEl.textContent = '0';
rpmValueEl.textContent = '0';
cruiseValueEl.textContent = 'aus';
motorValueEl.textContent = '–';
loadValueEl.textContent = '–';
fuelTextEl.textContent = '–';
fuelBarEl.style.width = '0%';
damageTextEl.textContent = '–';
damageBarEl.style.width = '0%';
dirtTextEl.textContent = '–';
dirtBarEl.style.width = '0%';
hoursValueEl.textContent = '–';
priceValueEl.textContent = '–';
sellPriceValueEl.textContent = '–';
positionValueEl.textContent = '–';
headingValueEl.textContent = '–';
renderOwnFillUnits(null);
renderImplements(null, vehicles);
return;
}
vehicleNameEl.textContent = v.name || 'Unbenannt';
vehicleTypeEl.textContent = v.typeName || '';
const vehicleIsDrivable = isDrivable(v);
const speed = (vehicleIsDrivable && typeof v.speedKmh === 'number') ? Math.max(0, v.speedKmh) : 0;
const speedMax = Math.max(60, Math.ceil(speed / 20) * 20);
setGauge(speedGaugeFill, speed / speedMax);
speedValueEl.textContent = vehicleIsDrivable ? formatNumber(speed, 0) : '–';
const rpmFraction = typeof v.rpmPercent === 'number' ? v.rpmPercent / 100 : 0;
setGauge(rpmGaugeFill, rpmFraction);
rpmValueEl.textContent = formatNumber(v.rpm, 0);
if (v.cruiseControlActive) {
const maxText = typeof v.cruiseControlMaxSpeed === 'number' ? ' (max ' + formatNumber(v.cruiseControlMaxSpeed, 0) + ')' : '';
cruiseValueEl.textContent = 'an · ' + formatNumber(v.cruiseControlSpeed, 0) + ' km/h' + maxText;
cruiseValueEl.classList.add('active');
} else {
cruiseValueEl.textContent = 'aus';
cruiseValueEl.classList.remove('active');
}
if (typeof v.motorStarted === 'boolean') {
motorValueEl.textContent = v.motorStarted ? 'läuft' : 'aus';
} else {
motorValueEl.textContent = '–';
}
loadValueEl.textContent = typeof v.motorLoadPercent === 'number' ? Math.round(v.motorLoadPercent) + '%' : '–';
if (typeof v.fuelLevel === 'number' && typeof v.fuelCapacity === 'number' && v.fuelCapacity > 0) {
const pct = (v.fuelLevel / v.fuelCapacity) * 100;
const fuelUnit = Array.isArray(v.fillUnits) ? v.fillUnits.find((fu) => fu.fillTypeId === v.fuelType) : null;
const fuelName = fuelUnit && fuelUnit.fillTypeName ? fuelUnit.fillTypeName + ': ' : '';
fuelTextEl.textContent = fuelName + Math.round(v.fuelLevel) + ' / ' + Math.round(v.fuelCapacity) + ' l (' + Math.round(pct) + '%)';
fuelBarEl.style.width = Math.min(100, Math.max(0, pct)) + '%';
} else {
fuelTextEl.textContent = '–';
fuelBarEl.style.width = '0%';
}
if (typeof v.damagePercent === 'number') {
const pct = Math.min(100, Math.max(0, v.damagePercent));
damageTextEl.textContent = Math.round(pct) + '%';
damageBarEl.style.width = pct + '%';
} else {
damageTextEl.textContent = '–';
damageBarEl.style.width = '0%';
}
if (typeof v.dirtPercent === 'number') {
const pct = Math.min(100, Math.max(0, v.dirtPercent));
dirtTextEl.textContent = Math.round(pct) + '%';
dirtBarEl.style.width = pct + '%';
} else {
dirtTextEl.textContent = '–';
dirtBarEl.style.width = '0%';
}
hoursValueEl.textContent = typeof v.operatingHours === 'number' ? formatNumber(v.operatingHours, 1) + ' h' : '–';
priceValueEl.textContent = typeof v.price === 'number' ? formatEuro(v.price) : '–';
sellPriceValueEl.textContent = typeof v.sellPrice === 'number' ? formatEuro(v.sellPrice) : '–';
positionValueEl.textContent = (typeof v.x === 'number' && typeof v.z === 'number')
? Math.round(v.x) + ', ' + Math.round(v.z)
: '–';
headingValueEl.textContent = typeof v.headingRad === 'number'
? Math.round(((v.headingRad * 180 / Math.PI) % 360 + 360) % 360) + '°'
: '–';
renderOwnFillUnits(v);
renderImplements(v, vehicles);
pushSpeedHistory(speed);
renderSpeedHistory();
}
/**
* The selected vehicle's OWN tanks/hoppers (e.g. a combine's grain tank, a
* sprayer's own liquid tank) - separate from the "Tank" bar above, which is
* specifically the fuel/energy fillUnit. The fuel unit is excluded here so
* it isn't shown twice.
*/
function renderOwnFillUnits(v) {
ownFillUnitsListEl.innerHTML = '';
const fillUnits = (v && Array.isArray(v.fillUnits)) ? v.fillUnits : [];
const relevant = fillUnits.filter((fu) => {
if (typeof fu.capacity !== 'number' || fu.capacity <= 0) return false;
if (v && v.fuelType != null && fu.fillTypeId === v.fuelType) return false;
return true;
});
if (relevant.length === 0) {
const empty = document.createElement('div');
empty.className = 'implements-empty';
empty.textContent = '– keine –';
ownFillUnitsListEl.appendChild(empty);
return;
}
for (const fu of relevant) {
const level = typeof fu.fillLevel === 'number' ? fu.fillLevel : 0;
const pct = Math.min(100, Math.max(0, (level / fu.capacity) * 100));
const row = document.createElement('div');
row.className = 'implement-fill';
const label = document.createElement('div');
label.className = 'bar-label';
label.innerHTML = `<span>${fu.fillTypeName || 'Unbekannt'}</span><span>${Math.round(level)} / ${Math.round(fu.capacity)} l (${Math.round(pct)}%)</span>`;
row.appendChild(label);
const track = document.createElement('div');
track.className = 'bar-track';
const fill = document.createElement('div');
fill.className = 'bar-fill';
fill.style.width = pct + '%';
fill.style.background = 'var(--accent)';
track.appendChild(fill);
row.appendChild(track);
ownFillUnitsListEl.appendChild(row);
}
}
/**
* Shows the FULL attachment train behind the given vehicle - not just what's
* directly hitched, but also whatever's hitched behind THAT (a tractor
* pulling a dolly pulling a trailer, etc.). The mod only sends one level of
* attachedImplementIds per vehicle, so this walks that chain recursively,
* looking up each linked vehicle (and its own attachments) from the full
* vehicles list every render. A visited-set guards against a cycle ever
* causing an infinite loop (shouldn't happen, but cheap to be safe).
*/
function renderImplements(vehicle, vehicles) {
implementsListEl.innerHTML = '';
const rootIds = (vehicle && Array.isArray(vehicle.attachedImplementIds)) ? vehicle.attachedImplementIds : [];
if (rootIds.length === 0) {
const empty = document.createElement('div');
empty.className = 'implements-empty';
empty.textContent = '– keine –';
implementsListEl.appendChild(empty);
return;
}
const visited = new Set(vehicle ? [vehicle.id] : []);
for (const rootId of rootIds) {
appendImplementChain(rootId, vehicles, implementsListEl, 0, visited);
}
}
function appendImplementChain(implementId, vehicles, container, depth, visited) {
if (visited.has(implementId)) return;
visited.add(implementId);
const implement = vehicles.find((x) => x.id === implementId);
const card = document.createElement('div');
card.className = 'implement-card';
if (depth > 0) {
card.classList.add('implement-chained');
card.style.marginLeft = (depth * 16) + 'px';
}
const nameEl = document.createElement('div');
nameEl.className = 'implement-name';
nameEl.textContent = (depth > 0 ? '↳ ' : '') + (implement ? (implement.name || 'Unbenannt') : 'Unbekanntes Gerät');
card.appendChild(nameEl);
const fillUnits = (implement && Array.isArray(implement.fillUnits)) ? implement.fillUnits : [];
const relevant = fillUnits.filter((fu) => typeof fu.capacity === 'number' && fu.capacity > 0);
if (relevant.length === 0) {
const none = document.createElement('div');
none.className = 'implement-empty-tank';
none.textContent = 'kein Tank';
card.appendChild(none);
} else {
for (const fu of relevant) {
const level = typeof fu.fillLevel === 'number' ? fu.fillLevel : 0;
const pct = Math.min(100, Math.max(0, (level / fu.capacity) * 100));
const row = document.createElement('div');
row.className = 'implement-fill';
const label = document.createElement('div');
label.className = 'bar-label';
label.innerHTML = `<span>${fu.fillTypeName || 'Unbekannt'}</span><span>${Math.round(level)} / ${Math.round(fu.capacity)} l (${Math.round(pct)}%)</span>`;
row.appendChild(label);
const track = document.createElement('div');
track.className = 'bar-track';
const fill = document.createElement('div');
fill.className = 'bar-fill';
fill.style.width = pct + '%';
fill.style.background = 'var(--accent)';
track.appendChild(fill);
row.appendChild(track);
card.appendChild(row);
}
}
container.appendChild(card);
const childIds = (implement && Array.isArray(implement.attachedImplementIds)) ? implement.attachedImplementIds : [];
for (const childId of childIds) {
appendImplementChain(childId, vehicles, container, depth + 1, visited);
}
}
function setGauge(fillEl, fraction) {
const clamped = Math.max(0, Math.min(1, fraction || 0));
fillEl.style.strokeDashoffset = String(GAUGE_ARC_LENGTH * (1 - clamped));
// Real telemetry is never exactly 0 (physics jitter gives e.g. 0.0004 km/h),
// so comparing to 0 doesn't catch it - a small threshold does.
fillEl.classList.toggle('has-value', clamped > 0.01);
}
function pushSpeedHistory(speed) {
const now = Date.now();
state.speedHistory.push({ t: now, v: speed });
const cutoff = now - SPEED_HISTORY_WINDOW_MS;
while (state.speedHistory.length > 0 && state.speedHistory[0].t < cutoff) {
state.speedHistory.shift();
}
}
function renderSpeedHistory() {
const ratio = resizeCanvasToDisplaySize(speedHistoryCanvas);
const w = speedHistoryCanvas.width;
const h = speedHistoryCanvas.height;
speedHistoryCtx.clearRect(0, 0, w, h);
const points = state.speedHistory;
if (points.length < 2) return;
const now = Date.now();
const maxV = Math.max(20, ...points.map((p) => p.v));
speedHistoryCtx.beginPath();
points.forEach((p, i) => {
const fx = 1 - (now - p.t) / SPEED_HISTORY_WINDOW_MS;
const x = fx * w;
const y = h - (p.v / maxV) * (h - 4) - 2;
if (i === 0) speedHistoryCtx.moveTo(x, y); else speedHistoryCtx.lineTo(x, y);
});
speedHistoryCtx.strokeStyle = getCssVar('--accent');
speedHistoryCtx.lineWidth = 2 * ratio;
speedHistoryCtx.stroke();
}
// ---------------------------------------------------------------------
// Time
// ---------------------------------------------------------------------
function renderTime(time) {
if (!time) {
clockText.textContent = '--:--';
dayText.textContent = 'Tag –';
seasonText.textContent = '';
periodTextEl.textContent = '';
scaleText.textContent = '';
return;
}
// dayTimeMinutes first: it's the precise, continuously-updating clock
// (observed as milliseconds since midnight, e.g. 33359013 ms = ~9.27h).
// currentHour was preferred before, but it's only ever a whole number in
// practice, so the displayed time never showed minutes - only use it as
// a fallback if dayTimeMinutes isn't available at all.
let minutes = null;
if (typeof time.dayTimeMinutes === 'number') {
minutes = time.dayTimeMinutes > 1440 ? time.dayTimeMinutes / 60000 : time.dayTimeMinutes;
} else if (typeof time.currentHour === 'number') {
minutes = time.currentHour * 60;
}
if (minutes != null) {
minutes = ((minutes % 1440) + 1440) % 1440;
const hh = Math.floor(minutes / 60);
const mm = Math.floor(minutes % 60);
clockText.textContent = String(hh).padStart(2, '0') + ':' + String(mm).padStart(2, '0');
} else {
clockText.textContent = '--:--';
}
dayText.textContent = typeof time.currentDay === 'number' ? ('Tag ' + time.currentDay) : 'Tag –';
seasonText.textContent = time.currentSeason != null ? ('Saison ' + time.currentSeason) : '';
periodTextEl.textContent = typeof time.daysPerPeriod === 'number' ? ('(' + time.daysPerPeriod + ' Tage/Saison)') : '';
scaleText.textContent = typeof time.timeScale === 'number' ? (time.timeScale + '× Zeitraffer') : '';
}
// ---------------------------------------------------------------------
// Weather
// ---------------------------------------------------------------------
function renderWeather(weather, time) {
if (!weather) {
weatherIcon.textContent = '❓';
weatherType.textContent = 'Unbekannt';
weatherTemp.textContent = '';
weatherBadgesEl.innerHTML = '';
weatherExtraEl.innerHTML = '';
forecastStrip.innerHTML = '<div class="forecast-empty">Keine Wetterdaten vom Spiel verfügbar.</div>';
return;
}
const name = weather.currentTypeName;
weatherIcon.textContent = WEATHER_ICONS[name] || '❓';
weatherType.textContent = (name && WEATHER_LABELS_DE[name]) || 'Unbekannt';
weatherTemp.textContent = typeof weather.temperatureCelsius === 'number'
? Math.round(weather.temperatureCelsius) + ' °C'
: '';
weatherBadgesEl.innerHTML = '';
const badges = [];
if (weather.isRaining) badges.push('🌧️ Regen');
if (weather.isSnowing) badges.push('❄️ Schnee');
if (time && time.isNight) badges.push('🌙 Nacht');
for (const text of badges) {
const b = document.createElement('span');
b.className = 'weather-badge active';
b.textContent = text;
weatherBadgesEl.appendChild(b);
}
weatherExtraEl.innerHTML = '';
if (weather.isRaining && typeof weather.rainFallScale === 'number') {
const span = document.createElement('span');
span.textContent = 'Regenintensität: ' + Math.round(weather.rainFallScale * 100) + '%';
weatherExtraEl.appendChild(span);
}
if (typeof weather.snowHeight === 'number' && weather.snowHeight > 0.001) {
const span = document.createElement('span');
span.textContent = 'Schneehöhe: ' + weather.snowHeight.toFixed(2) + ' m';
weatherExtraEl.appendChild(span);
}
const forecast = Array.isArray(weather.forecast) ? weather.forecast : [];
if (forecast.length === 0) {
forecastStrip.innerHTML = '<div class="forecast-empty">Keine Vorhersagedaten vom Spiel verfügbar.</div>';
return;
}
forecastStrip.innerHTML = '';
for (const f of forecast) {
const day = document.createElement('div');
day.className = 'forecast-day';
const label = document.createElement('div');
label.className = 'fc-label';
label.textContent = '+' + f.dayOffset + ' Tag';
const icon = document.createElement('div');
icon.className = 'fc-icon';
icon.textContent = WEATHER_ICONS[f.typeName] || '❓';
const temp = document.createElement('div');
temp.className = 'fc-temp';
if (typeof f.minTemperatureCelsius === 'number' && typeof f.maxTemperatureCelsius === 'number') {
temp.textContent = Math.round(f.minTemperatureCelsius) + '° / ' + Math.round(f.maxTemperatureCelsius) + '°';
}
day.appendChild(label);
day.appendChild(icon);
day.appendChild(temp);
forecastStrip.appendChild(day);
}
}
// ---------------------------------------------------------------------
// Farm
// ---------------------------------------------------------------------
function renderFarm(mission, farmlands, farms) {
if (!mission) {
farmName.textContent = '–';
farmMoney.textContent = '–';
farmlandCountEl.textContent = '–';
farmlandValueEl.textContent = '–';
otherFarmsHeadEl.hidden = true;
otherFarmsListEl.innerHTML = '';
farmlandListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
return;
}
const farmArr = Array.isArray(farms) ? farms : [];
let name = mission.farmName || ('Betrieb #' + (mission.farmId != null ? mission.farmId : '–'));
if (farmArr.length > 1) {
name += ` (von ${farmArr.length} Betrieben)`;
}
farmName.textContent = name;
farmMoney.textContent = formatEuro(mission.money);
const owned = (Array.isArray(farmlands) ? farmlands : []).filter((f) => f.isOwned && f.farmId === mission.farmId);
farmlandCountEl.textContent = owned.length > 0 ? String(owned.length) : '–';
const totalValue = owned.reduce((sum, f) => sum + (typeof f.price === 'number' ? f.price : 0), 0);
farmlandValueEl.textContent = owned.length > 0 ? formatEuro(totalValue) : '–';
// Every other farm the mod knows about (i.e. owns at least one farmland) -
// useful on shared/multiplayer savegames to see who else is playing.
const others = farmArr.filter((f) => f.id !== mission.farmId);
otherFarmsHeadEl.hidden = others.length === 0;
otherFarmsListEl.innerHTML = '';
for (const f of others) {
const row = document.createElement('div');
row.className = 'storage-fill-row';
row.innerHTML = `<span>${f.name || ('Betrieb #' + f.id)}</span><span>${typeof f.money === 'number' ? formatEuro(f.money) : '–'}</span>`;
otherFarmsListEl.appendChild(row);
}
// Individual owned farmland plots (name + price) - the stat chips above
// only show the aggregate count/value.
farmlandListEl.innerHTML = '';
if (owned.length === 0) {
farmlandListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
} else {
for (const f of owned) {
const row = document.createElement('div');
row.className = 'storage-fill-row';
row.innerHTML = `<span>${f.name || ('Grundstück #' + f.id)}</span><span>${typeof f.price === 'number' ? formatEuro(f.price) : '–'}</span>`;
farmlandListEl.appendChild(row);
}
}
}
// ---------------------------------------------------------------------
// Storage (silos) & animal husbandries
// ---------------------------------------------------------------------
// 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 rather than disappearing.
const 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',
};
function productionStatusClass(name) {
if (name === 'RUNNING' || name === 'ACTIVE') return 'ok';
if (!name) return '';
return 'warn';
}
function renderStorage(silos, husbandries, productions, farms) {
const showFarmBadge = Array.isArray(farms) && farms.length > 1;
siloListEl.innerHTML = '';
const filledSilos = (Array.isArray(silos) ? silos : []).filter((s) => Array.isArray(s.fillTypes) && s.fillTypes.length > 0);
if (filledSilos.length === 0) {
siloListEl.innerHTML = '<div class="storage-empty">– keine befüllten Silos –</div>';
} else {
for (const silo of filledSilos) {
const card = document.createElement('div');
card.className = 'storage-item';
const nameEl = document.createElement('div');
nameEl.className = 'storage-item-name';
nameEl.textContent = (silo.name || 'Unbenannt') + farmSuffix(silo.ownerFarmId, showFarmBadge);
card.appendChild(nameEl);
for (const ft of silo.fillTypes) {
const row = document.createElement('div');
row.className = 'storage-fill-row';
const level = typeof ft.fillLevel === 'number' ? Math.round(ft.fillLevel) : 0;
row.innerHTML = `<span>${ft.fillTypeName || 'Unbekannt'}</span><span>${level.toLocaleString('de-DE')} l</span>`;
card.appendChild(row);
}
siloListEl.appendChild(card);
}
}
husbandryListEl.innerHTML = '';
const husbandryArr = Array.isArray(husbandries) ? husbandries : [];
if (husbandryArr.length === 0) {
husbandryListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
} else {
for (const h of husbandryArr) {
const card = document.createElement('div');
card.className = 'storage-item';
const nameEl = document.createElement('div');
nameEl.className = 'storage-item-name';
nameEl.textContent = (h.name || 'Unbenannt') + farmSuffix(h.ownerFarmId, showFarmBadge);
card.appendChild(nameEl);
const countEl = document.createElement('div');
countEl.className = 'storage-animal-count';
const count = typeof h.numAnimals === 'number' ? h.numAnimals : '–';
const max = typeof h.maxNumAnimals === 'number' ? ' / ' + h.maxNumAnimals : '';
countEl.textContent = count + max;
card.appendChild(countEl);
const subEl = document.createElement('div');
subEl.className = 'storage-animal-sub';
subEl.textContent = 'Tiere';
card.appendChild(subEl);
husbandryListEl.appendChild(card);
}
}
productionListEl.innerHTML = '';
const productionArr = Array.isArray(productions) ? productions : [];
if (productionArr.length === 0) {
productionListEl.innerHTML = '<div class="storage-empty">– keine –</div>';
} else {
for (const p of productionArr) {
const card = document.createElement('div');
card.className = 'storage-item';
const nameEl = document.createElement('div');
nameEl.className = 'storage-item-name';
nameEl.textContent = (p.name || 'Unbenannt') + farmSuffix(p.ownerFarmId, showFarmBadge);
card.appendChild(nameEl);
for (const r of (Array.isArray(p.recipes) ? p.recipes : [])) {
const head = document.createElement('div');
head.className = 'production-recipe-head';
const statusLabel = PRODUCTION_STATUS_LABELS[r.statusName] || r.statusName || '';
head.innerHTML = `<span>${r.name || 'Rezept'}</span>`
+ (statusLabel ? `<span class="production-status ${productionStatusClass(r.statusName)}">${statusLabel}</span>` : '');
card.appendChild(head);
const inputsText = (Array.isArray(r.inputs) ? r.inputs : [])
.map((i) => (i.fillTypeName || '?') + (typeof i.amount === 'number' ? ` (${i.amount})` : ''))
.join(' + ') || '–';
const outputsText = (Array.isArray(r.outputs) ? r.outputs : [])
.map((o) => (o.fillTypeName || '?') + (typeof o.amount === 'number' ? ` (${o.amount})` : ''))
.join(' + ') || '–';
const flow = document.createElement('div');
flow.className = 'production-flow';
flow.textContent = inputsText + ' → ' + outputsText;
card.appendChild(flow);
}
const contents = Array.isArray(p.contents) ? p.contents : [];
if (contents.length > 0) {
const contentHead = document.createElement('div');
contentHead.className = 'production-content-head';
contentHead.textContent = 'Lagerbestand';
card.appendChild(contentHead);
for (const c of contents) {
const row = document.createElement('div');
row.className = 'storage-fill-row';
const level = typeof c.fillLevel === 'number' ? Math.round(c.fillLevel) : 0;
row.innerHTML = `<span>${c.fillTypeName || 'Unbekannt'}</span><span>${level.toLocaleString('de-DE')} l</span>`;
card.appendChild(row);
}
}
productionListEl.appendChild(card);
}
}
}
function farmSuffix(ownerFarmId, show) {
return (show && ownerFarmId != null) ? ` (Betrieb #${ownerFarmId})` : '';
}
// ---------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------
function formatNumber(n, digits) {
if (typeof n !== 'number' || Number.isNaN(n)) return '–';
return n.toFixed(digits);
}
function formatEuro(n) {
if (typeof n !== 'number' || Number.isNaN(n)) return '–';
return Math.round(n).toLocaleString('de-DE') + ' €';
}
window.addEventListener('resize', () => {
if (state.lastData) onData(state.lastData);
});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

+274
View File
@@ -0,0 +1,274 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>FS25 Live Dashboard</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<span class="brand-mark">FS25</span>
<span class="brand-title">Live Dashboard</span>
<span class="brand-sub" id="mapIdText"></span>
</div>
<div class="topbar-right">
<div class="status" id="status">
<span class="status-dot" id="statusDot"></span>
<span id="statusText">Verbinde…</span>
</div>
<button class="icon-btn" id="themeToggle" title="Hell/Dunkel umschalten">🌓</button>
<button class="icon-btn" id="fullscreenBtn" title="Vollbild">⛶</button>
</div>
</header>
<main class="grid">
<!-- Selected vehicle -->
<section class="panel vehicle-panel" data-panel-id="vehicle">
<div class="panel-header">
<h2 id="vehicleName">Kein Fahrzeug ausgewählt</h2>
<span class="panel-sub" id="vehicleType"></span>
<button class="link-btn" id="followMyVehicleBtn" title="Wieder automatisch dem gesteuerten Fahrzeug folgen">📍 Mein Fahrzeug</button>
<button class="panel-toggle" title="Ein-/Ausklappen">▾</button>
</div>
<div class="panel-body">
<div class="manual-select-hint" id="manualSelectHint" hidden>🔒 manuell ausgewählt – klicke „Mein Fahrzeug“ um wieder automatisch zu folgen</div>
<div class="gauge-row">
<div class="gauge-box">
<svg viewBox="0 0 200 155" class="gauge">
<path d="M20,100 A80,80 0 0 1 180,100" class="gauge-track" />
<path d="M20,100 A80,80 0 0 1 180,100" class="gauge-fill" id="speedGaugeFill" />
<text x="100" y="128" class="gauge-value" id="speedValue">0</text>
<text x="100" y="148" class="gauge-unit">km/h</text>
</svg>
<div class="gauge-caption">Geschwindigkeit</div>
</div>
<div class="gauge-box">
<svg viewBox="0 0 200 155" class="gauge">
<path d="M20,100 A80,80 0 0 1 180,100" class="gauge-track" />
<path d="M20,100 A80,80 0 0 1 180,100" class="gauge-fill gauge-fill-rpm" id="rpmGaugeFill" />
<text x="100" y="128" class="gauge-value" id="rpmValue">0</text>
<text x="100" y="148" class="gauge-unit">U/min</text>
</svg>
<div class="gauge-caption">Drehzahl</div>
</div>
</div>
<div class="stat-row">
<div class="stat-chip" id="cruiseChip">
<span class="stat-label">Tempomat</span>
<span class="stat-value" id="cruiseValue">aus</span>
</div>
<div class="stat-chip">
<span class="stat-label">Motor</span>
<span class="stat-value" id="motorValue">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Last</span>
<span class="stat-value" id="loadValue">–</span>
</div>
</div>
<div class="stat-row">
<div class="stat-chip">
<span class="stat-label">Betriebsstunden</span>
<span class="stat-value" id="hoursValue">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Neuwert</span>
<span class="stat-value" id="priceValue">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Verkaufswert</span>
<span class="stat-value" id="sellPriceValue">–</span>
</div>
</div>
<div class="stat-row">
<div class="stat-chip">
<span class="stat-label">Position</span>
<span class="stat-value" id="positionValue">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Ausrichtung</span>
<span class="stat-value" id="headingValue">–</span>
</div>
</div>
<div class="bar-row">
<div class="bar-block">
<div class="bar-label"><span>Tank</span><span id="fuelText">–</span></div>
<div class="bar-track"><div class="bar-fill bar-fuel" id="fuelBar"></div></div>
</div>
<div class="bar-block">
<div class="bar-label"><span>Schaden</span><span id="damageText">–</span></div>
<div class="bar-track"><div class="bar-fill bar-damage" id="damageBar"></div></div>
</div>
<div class="bar-block">
<div class="bar-label"><span>Verschmutzung</span><span id="dirtText">–</span></div>
<div class="bar-track"><div class="bar-fill bar-dirt" id="dirtBar"></div></div>
</div>
</div>
<div class="implements-block">
<div class="bar-label"><span>Eigene Ladung / Behälter</span></div>
<div id="ownFillUnitsList" class="implements-list">
<div class="implements-empty">– keine –</div>
</div>
</div>
<div class="implements-block">
<div class="bar-label"><span>Angekoppelte Geräte</span></div>
<div id="implementsList" class="implements-list">
<div class="implements-empty">– keine –</div>
</div>
</div>
<div class="sparkline-block">
<div class="bar-label"><span>Geschwindigkeit (letzte 60s)</span></div>
<canvas id="speedHistory" height="48"></canvas>
</div>
</div>
</section>
<!-- Time -->
<section class="panel time-panel" data-panel-id="time">
<div class="panel-header">
<h2>Zeit</h2>
<button class="panel-toggle" title="Ein-/Ausklappen">▾</button>
</div>
<div class="panel-body">
<div class="clock" id="clockText">--:--</div>
<div class="time-sub">
<span id="dayText">Tag –</span>
<span id="seasonText"></span>
<span id="periodText"></span>
<span id="scaleText"></span>
</div>
</div>
</section>
<!-- Weather -->
<section class="panel weather-panel" data-panel-id="weather">
<div class="panel-header">
<h2>Wetter</h2>
<button class="panel-toggle" title="Ein-/Ausklappen">▾</button>
</div>
<div class="panel-body">
<div class="weather-now" id="weatherNow">
<div class="weather-icon" id="weatherIcon">❓</div>
<div class="weather-now-text">
<div class="weather-type" id="weatherType">Unbekannt</div>
<div class="weather-temp" id="weatherTemp"></div>
</div>
<div class="weather-badges" id="weatherBadges"></div>
</div>
<div class="time-sub" id="weatherExtra"></div>
<div class="forecast-strip" id="forecastStrip">
<div class="forecast-empty">Keine Vorhersagedaten vom Spiel verfügbar.</div>
</div>
</div>
</section>
<!-- Farm -->
<section class="panel farm-panel" data-panel-id="farm">
<div class="panel-header">
<h2>Betrieb</h2>
<button class="panel-toggle" title="Ein-/Ausklappen">▾</button>
</div>
<div class="panel-body">
<div class="farm-row">
<div class="stat-chip">
<span class="stat-label">Betrieb</span>
<span class="stat-value" id="farmName">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Kontostand</span>
<span class="stat-value" id="farmMoney">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Eigene Grundstücke</span>
<span class="stat-value" id="farmlandCount">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Grundstückswert</span>
<span class="stat-value" id="farmlandValue">–</span>
</div>
<div class="stat-chip">
<span class="stat-label">Spielerstatus</span>
<span class="stat-value" id="playerStatusValue">–</span>
</div>
</div>
<div class="storage-subhead" id="otherFarmsHead" hidden>Andere Betriebe</div>
<div id="otherFarmsList" class="storage-list"></div>
<div class="storage-subhead">Eigene Grundstücke</div>
<div id="farmlandList" class="storage-list">
<div class="storage-empty">– keine –</div>
</div>
</div>
</section>
<!-- Storage, animals & production -->
<section class="panel storage-panel" data-panel-id="storage">
<div class="panel-header">
<h2>Lager, Tierhaltung &amp; Produktion</h2>
<button class="panel-toggle" title="Ein-/Ausklappen">▾</button>
</div>
<div class="panel-body">
<div class="storage-subhead">Silos</div>
<div id="siloList" class="storage-list">
<div class="storage-empty">– keine Daten –</div>
</div>
<div class="storage-subhead">Ställe</div>
<div id="husbandryList" class="storage-list">
<div class="storage-empty">– keine Daten –</div>
</div>
<div class="storage-subhead">Produktionen</div>
<div id="productionList" class="storage-list">
<div class="storage-empty">– keine Daten –</div>
</div>
</div>
</section>
<!-- Vehicle table -->
<section class="panel table-panel" data-panel-id="table">
<div class="panel-header">
<h2>Alle Fahrzeuge</h2>
<span class="panel-sub" id="vehicleCount">0 Fahrzeuge</span>
<button class="panel-toggle" title="Ein-/Ausklappen">▾</button>
</div>
<div class="panel-body">
<div class="table-wrap">
<table id="vehicleTable">
<thead>
<tr>
<th>Name</th>
<th>km/h</th>
<th>U/min</th>
<th>Tempomat</th>
<th>Tank</th>
<th>Schaden</th>
</tr>
</thead>
<tbody id="vehicleTableBody"></tbody>
</table>
</div>
</div>
</section>
</main>
</div>
<script src="app.js"></script>
</body>
</html>
+290
View File
@@ -0,0 +1,290 @@
:root {
color-scheme: dark;
--bg: #0e1512;
--panel: #161f1b;
--panel-border: #26332c;
--text: #eaf2ec;
--text-dim: #8fa39a;
--accent: #5fd68a;
--accent-dim: #2f6b4a;
--warn: #e0b34d;
--danger: #e0644d;
--rpm: #4d9be0;
--grid-line: #22302a;
}
[data-theme="light"] {
color-scheme: light;
--bg: #f2f5f2;
--panel: #ffffff;
--panel-border: #dbe4dd;
--text: #16211b;
--text-dim: #5c6d63;
--accent: #1f9d54;
--accent-dim: #bfe8cf;
--warn: #a56a00;
--danger: #b53a24;
--rpm: #1c6fb5;
--grid-line: #e2e9e3;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--text);
font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
height: 100%;
}
.app { min-height: 100vh; display: flex; flex-direction: column; }
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 20px;
background: var(--panel);
border-bottom: 1px solid var(--panel-border);
}
.brand { display: flex; align-items: baseline; gap: 10px; }
.brand-mark {
font-weight: 800;
letter-spacing: 1px;
color: var(--accent);
font-size: 15px;
padding: 3px 8px;
border: 1px solid var(--accent-dim);
border-radius: 6px;
}
.brand-title { font-weight: 600; font-size: 16px; color: var(--text-dim); }
.brand-sub { font-size: 12px; color: var(--text-dim); opacity: .7; }
.topbar-right { display: flex; align-items: center; gap: 10px; }
.status { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-dim); }
.status-dot {
width: 9px; height: 9px; border-radius: 50%;
background: var(--danger);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--danger) 25%, transparent);
}
.status-dot.live {
background: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent);
}
.icon-btn {
background: transparent;
border: 1px solid var(--panel-border);
color: var(--text);
border-radius: 6px;
width: 32px; height: 32px;
cursor: pointer;
font-size: 15px;
}
.icon-btn:hover { border-color: var(--accent); }
.grid {
flex: 1;
display: grid;
gap: 14px;
padding: 14px;
grid-template-columns: 1.4fr 1fr;
grid-template-areas:
"time vehicle"
"weather vehicle"
"farm vehicle"
"storage vehicle"
"table table";
max-width: 1400px;
margin: 0 auto;
width: 100%;
}
@media (max-width: 900px) {
.grid { grid-template-columns: 1fr; grid-template-areas: "vehicle" "time" "weather" "farm" "storage" "table"; }
}
.panel {
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 12px;
padding: 14px 16px 16px;
display: flex;
flex-direction: column;
}
.vehicle-panel { grid-area: vehicle; }
.time-panel { grid-area: time; }
.weather-panel { grid-area: weather; }
.farm-panel { grid-area: farm; }
.storage-panel { grid-area: storage; }
.table-panel { grid-area: table; }
.panel-header { display: flex; align-items: baseline; justify-content: space-between; margin-bottom: 10px; }
.panel-header h2 { margin: 0; font-size: 14px; letter-spacing: .3px; color: var(--text-dim); text-transform: uppercase; }
.panel-sub { font-size: 12px; color: var(--text-dim); }
.panel-toggle {
flex: 0 0 auto;
background: transparent;
border: none;
color: var(--text-dim);
cursor: pointer;
font-size: 13px;
padding: 2px 4px;
line-height: 1;
transition: transform .2s ease;
}
.panel-toggle:hover { color: var(--text); }
.panel.collapsed .panel-toggle { transform: rotate(-90deg); }
.panel.collapsed .panel-body { display: none; }
.panel.collapsed { padding-bottom: 14px; }
.link-btn {
background: transparent;
border: 1px solid var(--panel-border);
color: var(--text-dim);
border-radius: 6px;
padding: 3px 8px;
font-size: 12px;
cursor: pointer;
}
.link-btn:hover { border-color: var(--accent); color: var(--text); }
.link-btn.active { border-color: var(--accent); color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, transparent); }
#vehicleName { color: var(--text) !important; text-transform: none !important; font-size: 16px !important; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.vehicle-panel .panel-header { gap: 10px; }
#followMyVehicleBtn { flex: 0 0 auto; }
.manual-select-hint { font-size: 11px; color: var(--warn); margin: -4px 0 8px; }
.gauge-row { display: flex; gap: 10px; }
.gauge-box { flex: 1; text-align: center; }
.gauge { width: 100%; max-width: 220px; } /* keep the arc compact even in a wide panel */
.gauge-track, .gauge-fill { fill: none; stroke-width: 14; stroke-linecap: round; }
.gauge-track { stroke: var(--grid-line); }
.gauge-fill {
stroke: var(--accent);
stroke-dasharray: 251.33; /* pi * radius(80) - must match the arc's actual path length */
stroke-dashoffset: 251.33;
transition: stroke-dashoffset .25s ease, opacity .15s ease;
opacity: 0; /* hidden at 0% by default rather than relying on dashoffset alone -
round linecaps can leave a stray dot of color at the arc's start
even at "empty", this guarantees a clean look at 0 */
}
.gauge-fill.has-value { opacity: 1; }
.gauge-fill-rpm { stroke: var(--rpm); }
.gauge-value { fill: var(--text); font-size: 30px; font-weight: 700; text-anchor: middle; font-family: inherit; }
.gauge-unit { fill: var(--text-dim); font-size: 11px; text-anchor: middle; font-family: inherit; }
.gauge-caption { font-size: 12px; color: var(--text-dim); margin-top: 6px; }
.stat-row, .farm-row { display: flex; gap: 10px; margin-top: 4px; flex-wrap: wrap; }
.stat-chip {
flex: 1;
min-width: 90px;
background: var(--bg);
border: 1px solid var(--grid-line);
border-radius: 8px;
padding: 8px 10px;
display: flex;
flex-direction: column;
gap: 2px;
}
.stat-label { font-size: 11px; color: var(--text-dim); text-transform: uppercase; letter-spacing: .3px; }
.stat-value { font-size: 15px; font-weight: 600; }
.stat-value.active { color: var(--accent); }
.bar-row { margin-top: 12px; display: flex; flex-direction: column; gap: 10px; }
.bar-block { }
.bar-label { display: flex; justify-content: space-between; font-size: 12px; color: var(--text-dim); margin-bottom: 4px; }
.bar-track { height: 10px; background: var(--grid-line); border-radius: 5px; overflow: hidden; }
.bar-fill { height: 100%; width: 0%; transition: width .3s ease, background-color .3s ease; }
.bar-fuel { background: var(--warn); }
.bar-damage { background: var(--danger); }
.bar-dirt { background: #8a6a3d; }
.sparkline-block { margin-top: 14px; }
#speedHistory { width: 100%; height: 48px; display: block; }
.implements-block { margin-top: 14px; }
.implements-empty { font-size: 12px; color: var(--text-dim); }
.implements-list { display: flex; flex-direction: column; gap: 8px; }
.implement-card {
background: var(--bg);
border: 1px solid var(--grid-line);
border-radius: 8px;
padding: 8px 10px;
}
.implement-name { font-size: 13px; font-weight: 600; margin-bottom: 6px; }
.implement-fill { margin-top: 6px; }
.implement-fill:first-of-type { margin-top: 0; }
.implement-empty-tank { font-size: 11px; color: var(--text-dim); }
.implement-chained { border-left: 2px solid var(--accent-dim); }
.clock { font-size: 42px; font-weight: 700; letter-spacing: 1px; }
.time-sub { display: flex; gap: 14px; color: var(--text-dim); font-size: 13px; margin-top: 4px; flex-wrap: wrap; }
.weather-now { display: flex; align-items: center; gap: 14px; }
.weather-icon { font-size: 40px; }
.weather-type { font-size: 16px; font-weight: 600; }
.weather-temp { color: var(--text-dim); font-size: 13px; }
.weather-badges { display: flex; gap: 6px; margin-left: auto; flex-wrap: wrap; }
.weather-badge {
font-size: 11px;
padding: 3px 8px;
border-radius: 999px;
background: var(--grid-line);
color: var(--text-dim);
white-space: nowrap;
}
.weather-badge.active { background: color-mix(in srgb, var(--rpm) 20%, transparent); color: var(--rpm); }
.forecast-strip { display: flex; gap: 10px; margin-top: 14px; overflow-x: auto; }
.forecast-empty { color: var(--text-dim); font-size: 12px; padding: 8px 0; }
.forecast-day {
flex: 0 0 auto;
min-width: 64px;
text-align: center;
background: var(--bg);
border: 1px solid var(--grid-line);
border-radius: 8px;
padding: 8px 6px;
}
.forecast-day .fc-label { font-size: 11px; color: var(--text-dim); }
.forecast-day .fc-icon { font-size: 20px; margin: 4px 0; }
.forecast-day .fc-temp { font-size: 11px; color: var(--text-dim); }
.storage-subhead { font-size: 11px; color: var(--text-dim); text-transform: uppercase; letter-spacing: .3px; margin: 10px 0 6px; }
.storage-subhead:first-of-type { margin-top: 0; }
.storage-empty { font-size: 12px; color: var(--text-dim); }
.storage-list { display: flex; flex-direction: column; gap: 8px; }
.storage-item {
background: var(--bg);
border: 1px solid var(--grid-line);
border-radius: 8px;
padding: 8px 10px;
}
.storage-item-name { font-size: 13px; font-weight: 600; margin-bottom: 4px; }
.storage-fill-row { display: flex; justify-content: space-between; font-size: 12px; color: var(--text-dim); padding: 2px 0; }
.storage-fill-row span:last-child { color: var(--text); }
.storage-animal-count { font-size: 15px; font-weight: 600; }
.storage-animal-sub { font-size: 11px; color: var(--text-dim); }
.production-recipe-head { display: flex; justify-content: space-between; align-items: center; font-size: 13px; font-weight: 600; margin-top: 8px; }
.production-recipe-head:first-of-type { margin-top: 6px; }
.production-flow { font-size: 12px; color: var(--text-dim); margin-top: 2px; }
.production-status { font-size: 10px; padding: 2px 7px; border-radius: 999px; background: var(--grid-line); color: var(--text-dim); font-weight: 500; white-space: nowrap; }
.production-status.ok { background: color-mix(in srgb, var(--accent) 20%, transparent); color: var(--accent); }
.production-status.warn { background: color-mix(in srgb, var(--warn) 20%, transparent); color: var(--warn); }
.production-content-head { font-size: 11px; color: var(--text-dim); text-transform: uppercase; letter-spacing: .3px; margin-top: 10px; margin-bottom: 4px; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th, td { text-align: left; padding: 7px 8px; border-bottom: 1px solid var(--grid-line); white-space: nowrap; }
th { color: var(--text-dim); font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: .3px; }
tbody tr { cursor: pointer; }
tbody tr:hover { background: var(--grid-line); }
tbody tr.selected { background: color-mix(in srgb, var(--accent) 14%, transparent); }