421 lines
15 KiB
Python
421 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
||
# view/widgets/goth_topbar.py
|
||
from __future__ import annotations
|
||
|
||
from types import SimpleNamespace
|
||
import tkinter as tk
|
||
from PIL import Image, ImageTk
|
||
|
||
from resources.code_res.game_constants import (
|
||
BG_COLOR,
|
||
FONT_COLOR_BODY_DEFAULT,
|
||
FONT_COLOR_STATUS_LOSS,
|
||
FONT_SIZE_BODY,
|
||
FONT_SIZE_SMALL_MIN,
|
||
)
|
||
from resources.code_res.i18n import t
|
||
from view.dialogs.audio_settings_dialog import is_german_active
|
||
from view.widgets.image_button import ImageButton
|
||
|
||
|
||
def format_compact_user_badge(profile: dict, progress: dict) -> str:
|
||
"""Nutzername (max. 8 Zeichen), Spiel-Level als Nummer und Spiel-XP."""
|
||
raw_name = str(profile.get("name", "") or "").strip()
|
||
short_name = raw_name[:8]
|
||
|
||
lvl_num = int(progress.get("level", 1) or 1)
|
||
raw_exp = progress.get("total_points", progress.get("current_xp", 0))
|
||
exp_val = min(99_999_999, max(0, int(raw_exp or 0)))
|
||
exp_str = str(exp_val)[:8]
|
||
|
||
return f"{short_name} Lv. {lvl_num} {exp_str} XP"
|
||
|
||
|
||
def _noop_configure(**_kwargs):
|
||
pass
|
||
|
||
|
||
class GothTopbar(tk.Canvas):
|
||
"""
|
||
Statische, universelle Kopfleiste für alle Spiele:
|
||
- Einmaliges Setup beim Laden der Ansicht: `configure_stats_link(stats_endpoint, on_stats_back)`
|
||
- Links: 'Hauptmenü' + 'Statistiken' (öffnet zentral UnifiedStatsView für `stats_endpoint`)
|
||
- Rechts: Level/XP-Text (zentriert im rechten Flügel) + 'Einstellungen'
|
||
- Zur Laufzeit ändert sich ausschließlich der Level/XP-Text ohne Layout-Redraw!
|
||
"""
|
||
|
||
# Fein-Offsets für die Position von "Kuro Lv. X Y XP"
|
||
BADGE_X_OFFSET = 0 # Negativ = weiter nach links zur Mitte, Positiv = näher an Einstellungen
|
||
BADGE_Y_OFFSET = 7 # Gleiche optische Zeilenhöhe wie die Button-Beschriftung
|
||
|
||
def __init__(
|
||
self,
|
||
parent,
|
||
ctx,
|
||
stats_endpoint: str | None = None,
|
||
on_stats_back=None,
|
||
badge_text: str | None = None,
|
||
stats_enabled: bool = True,
|
||
on_lang_refresh=None,
|
||
locked_exit: bool = False,
|
||
on_main_menu=None,
|
||
# Optionale Alt-Parameter zur Abwärtskompatibilität bestehender Spiele:
|
||
title: str = "",
|
||
on_game_menu=None,
|
||
on_stats=None,
|
||
extra_right_text: str = "",
|
||
):
|
||
del title, on_game_menu, on_stats, extra_right_text
|
||
self._root_win = parent.winfo_toplevel()
|
||
root_h = max(680, self._root_win.winfo_height())
|
||
self._bar_h = max(68, int(root_h * 0.098))
|
||
|
||
super().__init__(
|
||
parent,
|
||
height=self._bar_h,
|
||
bg=BG_COLOR,
|
||
bd=0,
|
||
highlightthickness=0,
|
||
)
|
||
self.ctx = ctx
|
||
self.assets = ctx.assets
|
||
self.sounds = ctx.sounds
|
||
self._locked_exit = bool(locked_exit)
|
||
self._on_main_menu = on_main_menu or ctx.back_to_main_menu
|
||
self._stats_enabled = bool(stats_enabled)
|
||
self._on_lang_refresh = on_lang_refresh
|
||
|
||
self._stats_endpoint: str | None = (
|
||
stats_endpoint if stats_endpoint is not None else getattr(ctx, "game_folder", None)
|
||
)
|
||
self._on_stats_back = on_stats_back
|
||
|
||
self._bg_slice_photo: ImageTk.PhotoImage | None = None
|
||
self._lock_photo: ImageTk.PhotoImage | None = None
|
||
self._badge_photo: ImageTk.PhotoImage | None = None
|
||
self._badge_item_id: int | None = None
|
||
self._badge_anchor_xy: tuple[int, int] = (0, 0)
|
||
self._badge_max_w: int = 260
|
||
|
||
self._badge_color: str = FONT_COLOR_BODY_DEFAULT
|
||
self._badge_size_px: int = FONT_SIZE_SMALL_MIN + 1
|
||
self._badge_custom_override: str | None = badge_text
|
||
self._badge_text: str = ""
|
||
self._refresh_badge_text_from_db()
|
||
|
||
self._last_render_key: tuple[int, int, int, int, int, int] = (0, 0, 0, 0, 0, 0)
|
||
self._sync_job: str | None = None
|
||
self._root_cfg_bind_id: str | None = None
|
||
|
||
self._left_widgets: list[tuple[ImageButton, int]] = []
|
||
self._right_widgets: list[tuple[ImageButton, int]] = []
|
||
self.stats_btn: ImageButton | None = None
|
||
|
||
# Klassenlose Namespace-Adapter für volle Abwärtskompatibilität zu bestehenden Views
|
||
self.title_label = SimpleNamespace(text="", configure=_noop_configure, config=_noop_configure)
|
||
self.extra_label = SimpleNamespace(text="", configure=_noop_configure, config=_noop_configure)
|
||
self.level_label = SimpleNamespace(
|
||
text=self._badge_text,
|
||
configure=self._configure_level_slot,
|
||
config=self._configure_level_slot,
|
||
refresh_from_db=self.update_level_xp_text,
|
||
set_text=self.update_level_xp_text,
|
||
)
|
||
|
||
self._build_static_buttons()
|
||
|
||
self.bind("<Configure>", self._on_configure)
|
||
self.bind("<Destroy>", self._on_destroy)
|
||
try:
|
||
self._root_cfg_bind_id = self._root_win.bind(
|
||
"<Configure>", self._on_root_configure, add="+"
|
||
)
|
||
except tk.TclError:
|
||
self._root_cfg_bind_id = None
|
||
|
||
self.after(10, self._sync_bg_and_layout)
|
||
|
||
@property
|
||
def total_height(self) -> int:
|
||
return self._bar_h
|
||
|
||
def _refresh_badge_text_from_db(self):
|
||
if self._badge_custom_override is not None:
|
||
self._badge_text = self._badge_custom_override
|
||
else:
|
||
prof = self.ctx.profile or {}
|
||
prog = self.ctx.refresh_game_progress() if prof else {}
|
||
self._badge_text = format_compact_user_badge(prof, prog) if prof else ""
|
||
if hasattr(self, "level_label"):
|
||
self.level_label.text = self._badge_text
|
||
|
||
def _configure_level_slot(self, **kwargs):
|
||
prev_txt, prev_col = self._badge_text, self._badge_color
|
||
if "fg" in kwargs and kwargs["fg"] != self._badge_color:
|
||
self._badge_color = kwargs["fg"]
|
||
if "text" in kwargs:
|
||
self._badge_custom_override = None
|
||
self._refresh_badge_text_from_db()
|
||
if self._badge_text != prev_txt or self._badge_color != prev_col:
|
||
self._update_badge_item_only()
|
||
|
||
def configure_stats_link(self, game_endpoint: str | None, on_back_view=None):
|
||
"""Stellt beim Laden einer Ansicht einmalig den Statistik-Endpunkt ein – ohne Redraw!"""
|
||
self._stats_endpoint = game_endpoint
|
||
self._on_stats_back = on_back_view
|
||
if self.stats_btn is not None and self.stats_btn.winfo_exists():
|
||
self.stats_btn.set_enabled(bool(self._stats_enabled))
|
||
|
||
def update_level_xp_text(self, text: str | None = None):
|
||
"""Aktualisiert ausschließlich den Level/XP-Text rechts oben ohne Layout-Redraw."""
|
||
prev = self._badge_text
|
||
self._badge_custom_override = text
|
||
self._refresh_badge_text_from_db()
|
||
if self._badge_text != prev:
|
||
self._update_badge_item_only()
|
||
|
||
set_badge_text = update_level_xp_text
|
||
|
||
def set_locked_exit(self, locked: bool):
|
||
locked = bool(locked)
|
||
if locked == self._locked_exit:
|
||
return
|
||
self._locked_exit = locked
|
||
self._build_static_buttons()
|
||
self._last_render_key = (0, 0, 0, 0, 0, 0)
|
||
self._sync_bg_and_layout()
|
||
|
||
def _trigger_central_stats(self):
|
||
if self._locked_exit or not self._stats_enabled:
|
||
return
|
||
from view.unified_stats_view import UnifiedStatsView
|
||
|
||
UnifiedStatsView.open(
|
||
self.ctx,
|
||
game_endpoint=self._stats_endpoint,
|
||
on_back=self._on_stats_back,
|
||
)
|
||
|
||
def _build_static_buttons(self):
|
||
for wgt, _bw in self._left_widgets + self._right_widgets:
|
||
try:
|
||
if wgt.winfo_exists():
|
||
wgt.place_forget()
|
||
wgt.destroy()
|
||
except Exception:
|
||
pass
|
||
self._left_widgets.clear()
|
||
self._right_widgets.clear()
|
||
self.stats_btn = None
|
||
|
||
btn_norm = self.assets.raw_btn_default
|
||
btn_purp = self.assets.raw_btn_purple
|
||
|
||
if not self._locked_exit:
|
||
b_main = ImageButton(
|
||
self,
|
||
t("btn_back_main"),
|
||
btn_norm,
|
||
btn_purp,
|
||
self._on_main_menu,
|
||
sound_mgr=self.sounds,
|
||
width=112,
|
||
height=32,
|
||
style="amethyst",
|
||
)
|
||
self._left_widgets.append((b_main, b_main.pixel_width))
|
||
|
||
if self._stats_enabled:
|
||
self.stats_btn = ImageButton(
|
||
self,
|
||
t("btn_stats"),
|
||
btn_norm,
|
||
btn_purp,
|
||
self._trigger_central_stats,
|
||
sound_mgr=self.sounds,
|
||
width=102,
|
||
height=32,
|
||
enabled=True,
|
||
style="amethyst",
|
||
)
|
||
self._left_widgets.append((self.stats_btn, self.stats_btn.pixel_width))
|
||
|
||
settings_lbl = "Einstellungen" if is_german_active() else "Settings"
|
||
b_settings = ImageButton(
|
||
self,
|
||
settings_lbl,
|
||
btn_norm,
|
||
btn_purp,
|
||
lambda: self.ctx.open_settings(on_lang_refresh=self._on_lang_refresh),
|
||
sound_mgr=self.sounds,
|
||
width=122,
|
||
height=32,
|
||
style="amethyst",
|
||
)
|
||
self._right_widgets.append((b_settings, b_settings.pixel_width))
|
||
|
||
def _on_destroy(self, event=None):
|
||
if event is not None and event.widget is not self:
|
||
return
|
||
if self._sync_job is not None:
|
||
try:
|
||
self.after_cancel(self._sync_job)
|
||
except Exception:
|
||
pass
|
||
self._sync_job = None
|
||
if self._root_cfg_bind_id is not None:
|
||
try:
|
||
self._root_win.unbind("<Configure>", self._root_cfg_bind_id)
|
||
except Exception:
|
||
pass
|
||
self._root_cfg_bind_id = None
|
||
|
||
def _on_root_configure(self, event=None):
|
||
if event is not None and event.widget is not self._root_win:
|
||
return
|
||
self._schedule_sync()
|
||
|
||
def _on_configure(self, event):
|
||
if event.widget is not self or event.width < 100:
|
||
return
|
||
self._schedule_sync()
|
||
|
||
def _schedule_sync(self):
|
||
if not self.winfo_exists():
|
||
return
|
||
if self._sync_job is not None:
|
||
try:
|
||
self.after_cancel(self._sync_job)
|
||
except Exception:
|
||
pass
|
||
self._sync_job = self.after(18, self._sync_bg_and_layout)
|
||
|
||
def _sync_bg_and_layout(self):
|
||
self._sync_job = None
|
||
if not self.winfo_exists():
|
||
return
|
||
|
||
rw = max(1, self._root_win.winfo_width())
|
||
rh = max(600, self._root_win.winfo_height())
|
||
w = max(1, self.winfo_width())
|
||
if w < 100 or rw < 100:
|
||
return
|
||
|
||
target_h = max(68, int(rh * 0.098))
|
||
if target_h != self._bar_h:
|
||
self._bar_h = target_h
|
||
self.configure(height=target_h)
|
||
|
||
ox = max(0, min(max(0, rw - w), self.winfo_rootx() - self._root_win.winfo_rootx()))
|
||
oy = max(0, min(max(0, rh - target_h), self.winfo_rooty() - self._root_win.winfo_rooty()))
|
||
|
||
render_key = (w, target_h, rw, rh, ox, oy)
|
||
tk.Widget.tkraise(self)
|
||
if render_key == self._last_render_key:
|
||
return
|
||
self._last_render_key = render_key
|
||
|
||
self._render_bg_slice(w, target_h, rw, rh, ox, oy)
|
||
self._layout_static_items(w, target_h, rh)
|
||
|
||
def _render_bg_slice(
|
||
self, w: int, bar_h: int, rw: int, rh: int, ox: int, oy: int
|
||
):
|
||
slice_w = min(w, rw - ox)
|
||
slice_h = min(bar_h, rh - oy)
|
||
if slice_w < 40 or slice_h < 20:
|
||
return
|
||
|
||
if hasattr(self.assets, "get_bg_patch_photo"):
|
||
self._bg_slice_photo = self.assets.get_bg_patch_photo(
|
||
rw, rh, ox, oy, slice_w, slice_h
|
||
)
|
||
else:
|
||
src = (
|
||
self.assets.raw_bg_vertical
|
||
if (rh > rw and self.assets.raw_bg_vertical is not None)
|
||
else (self.assets.raw_bg_horizontal or self.assets.raw_bg)
|
||
)
|
||
if src is None:
|
||
return
|
||
full_scaled = src.resize((rw, rh), Image.Resampling.BILINEAR)
|
||
self._bg_slice_photo = ImageTk.PhotoImage(
|
||
full_scaled.crop((ox, oy, ox + slice_w, oy + slice_h))
|
||
)
|
||
|
||
if self._bg_slice_photo is None:
|
||
return
|
||
self.delete("topbar_bg")
|
||
self.create_image(0, 0, image=self._bg_slice_photo, anchor="nw", tags="topbar_bg")
|
||
self.tag_lower("topbar_bg")
|
||
|
||
def _layout_static_items(self, w: int, bar_h: int, root_h: int):
|
||
self.delete("topbar_lock")
|
||
pad_x = max(96, int(w * 0.095))
|
||
btn_cy = min(bar_h - 18, max(42, int(root_h * 0.066)))
|
||
|
||
left_x = pad_x
|
||
if self._locked_exit:
|
||
self._lock_photo = self.assets.get_goth_text_photo(
|
||
t("devils_deal_locked_badge"),
|
||
size_px=FONT_SIZE_BODY,
|
||
color=FONT_COLOR_STATUS_LOSS,
|
||
align="left",
|
||
)
|
||
self.create_image(
|
||
left_x, btn_cy, image=self._lock_photo, anchor="w", tags="topbar_lock"
|
||
)
|
||
left_x += self._lock_photo.width() + 10
|
||
else:
|
||
for wgt, bw in self._left_widgets:
|
||
bh = wgt.pixel_height
|
||
wgt.place(x=left_x, y=btn_cy - bh // 2, width=bw, height=bh)
|
||
tk.Widget.tkraise(wgt)
|
||
left_x += bw + 8
|
||
|
||
right_x = w - pad_x
|
||
for wgt, bw in reversed(self._right_widgets):
|
||
bh = wgt.pixel_height
|
||
wgt.place(x=right_x - bw, y=btn_cy - bh // 2, width=bw, height=bh)
|
||
tk.Widget.tkraise(wgt)
|
||
right_x -= (bw + 8)
|
||
|
||
# Zentriert den Spieler-Badge mittig im rechten Flügel zwischen Mittelornament (~55% w) und Einstellungen
|
||
right_wing_start = max(left_x + 24, int(w * 0.555))
|
||
if right_x > right_wing_start + 80:
|
||
badge_cx = (right_wing_start + right_x) // 2 + self.BADGE_X_OFFSET
|
||
self._badge_max_w = max(120, right_x - right_wing_start - 16)
|
||
else:
|
||
badge_cx = (left_x + right_x) // 2 + self.BADGE_X_OFFSET
|
||
self._badge_max_w = max(120, right_x - left_x - 20)
|
||
|
||
self._badge_anchor_xy = (badge_cx, btn_cy + self.BADGE_Y_OFFSET)
|
||
self._update_badge_item_only()
|
||
|
||
def _update_badge_item_only(self):
|
||
if not self.winfo_exists():
|
||
return
|
||
bx, by = self._badge_anchor_xy
|
||
if bx <= 0 or not self._badge_text:
|
||
if self._badge_item_id is not None:
|
||
self.delete(self._badge_item_id)
|
||
self._badge_item_id = None
|
||
return
|
||
|
||
self._badge_photo = self.assets.get_goth_text_photo(
|
||
self._badge_text,
|
||
size_px=self._badge_size_px,
|
||
color=self._badge_color,
|
||
max_width=self._badge_max_w,
|
||
align="center",
|
||
)
|
||
if self._badge_item_id is not None and self.type(self._badge_item_id):
|
||
self.itemconfigure(self._badge_item_id, image=self._badge_photo, anchor="center")
|
||
self.coords(self._badge_item_id, bx, by)
|
||
else:
|
||
self._badge_item_id = self.create_image(
|
||
bx, by, image=self._badge_photo, anchor="center", tags="topbar_badge"
|
||
)
|
||
|
||
def refresh_text_slots(self):
|
||
self._update_badge_item_only() |