# -*- coding: utf-8 -*- # view/widgets/bars/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.layout_mode import LayoutMode from view.widgets.bars.goth_burger_topbar import COMPACT_TOPBAR_HEIGHT, CompactBurgerTopbar from view.widgets.buttons.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] if profile.get("is_online"): short_name = f"{short_name} [ON]" 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 DesktopGothTopbar(tk.Canvas): """Unveränderte Desktop-Kopfleiste für Fenster ab Normalgröße.""" BADGE_X_OFFSET = 0 BADGE_Y_OFFSET = 7 def __init__(self, parent, controller_bar): self._ctrl_bar = controller_bar self._root_win = controller_bar._root_win 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 = controller_bar.ctx self.assets = controller_bar.assets self.sounds = controller_bar.sounds 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._last_render_key: tuple[int, int, int, int, int, int] = (0, 0, 0, 0, 0, 0) self._left_widgets: list[tuple[ImageButton, int]] = [] self._right_widgets: list[tuple[ImageButton, int]] = [] self.stats_btn: ImageButton | None = None self.build_static_buttons() self.bind("", self._on_configure) @property def total_height(self) -> int: return self._bar_h def _on_configure(self, event): if event.widget is not self or event.width < 100: return self.sync_bg_and_layout() 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._ctrl_bar._locked_exit: b_main = ImageButton( self, t("btn_back_main"), btn_norm, btn_purp, self._ctrl_bar._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._ctrl_bar._stats_enabled: self.stats_btn = ImageButton( self, t("btn_stats"), btn_norm, btn_purp, self._ctrl_bar._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)) b_settings = ImageButton( self, t("btn_settings"), btn_norm, btn_purp, lambda: self.ctx.open_settings(on_lang_refresh=self._ctrl_bar._on_lang_refresh), sound_mgr=self.sounds, width=122, height=32, style="amethyst", ) self._right_widgets.append((b_settings, b_settings.pixel_width)) def sync_bg_and_layout(self): 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) if render_key == self._last_render_key: return self._last_render_key = render_key slice_w = min(w, rw - ox) slice_h = min(target_h, rh - oy) if slice_w >= 40 and slice_h >= 20: self._bg_slice_photo = self.assets.get_bg_patch_photo(rw, rh, ox, oy, slice_w, slice_h) if self._bg_slice_photo is not None: self.delete("topbar_bg") self.create_image(0, 0, image=self._bg_slice_photo, anchor="nw", tags="topbar_bg") self.tag_lower("topbar_bg") self._layout_static_items(w, target_h, rh) 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._ctrl_bar._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) 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 txt = self._ctrl_bar._badge_text if bx <= 0 or not txt: 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( txt, size_px=self._ctrl_bar._badge_size_px, color=self._ctrl_bar._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" ) class GothTopbar(tk.Frame): """ Vorgeschalteter Größen-Regler für alle Spiele: - Normales Fenster: zeigt `DesktopGothTopbar` - Kompaktes Fenster (< 920x680, z. B. 658x768 Split-Screen): zeigt `CompactBurgerTopbar` """ 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, 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() rw = max(480, self._root_win.winfo_width()) rh = max(620, self._root_win.winfo_height()) self._is_compact = LayoutMode.is_compact(rw, rh) init_h = COMPACT_TOPBAR_HEIGHT if self._is_compact else max(68, int(rh * 0.098)) super().__init__(parent, height=init_h, bg=BG_COLOR, bd=0, highlightthickness=0) self.pack_propagate(False) 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._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._desktop_bar: DesktopGothTopbar | None = None self._compact_bar: CompactBurgerTopbar | None = None self._sync_job: str | None = None self._root_cfg_bind_id: str | None = None 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._apply_mode_widget(force=True) self.bind("", self._on_destroy) try: self._root_cfg_bind_id = self._root_win.bind( "", self._on_root_configure, add="+" ) except tk.TclError: self._root_cfg_bind_id = None self.after(10, self._sync_mode_and_layout) @property def total_height(self) -> int: if self._is_compact: return COMPACT_TOPBAR_HEIGHT return self._desktop_bar.total_height if self._desktop_bar else 68 @property def stats_btn(self) -> ImageButton | None: return self._desktop_bar.stats_btn if self._desktop_bar else None def _apply_mode_widget(self, force: bool = False): rw = max(480, self._root_win.winfo_width()) rh = max(620, self._root_win.winfo_height()) want_compact = LayoutMode.is_compact(rw, rh) if not force and want_compact == self._is_compact: return self._is_compact = want_compact if want_compact: if self._desktop_bar is not None: self._desktop_bar.pack_forget() if self._compact_bar is None: self._compact_bar = CompactBurgerTopbar(self, self) self.configure(height=COMPACT_TOPBAR_HEIGHT) self._compact_bar.pack(fill="both", expand=True) self._compact_bar._last_render_key = (0, 0, 0, 0, 0) self._compact_bar.sync_layout() else: if self._compact_bar is not None: self._compact_bar.close_drawer() self._compact_bar.pack_forget() if self._desktop_bar is None: self._desktop_bar = DesktopGothTopbar(self, self) target_h = max(68, int(rh * 0.098)) self.configure(height=target_h) self._desktop_bar.pack(fill="both", expand=True) self._desktop_bar._last_render_key = (0, 0, 0, 0, 0, 0) self._desktop_bar.sync_bg_and_layout() 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) and self._desktop_bar: self._desktop_bar.update_badge_item_only() def configure_stats_link(self, game_endpoint: str | None, on_back_view=None): self._stats_endpoint = game_endpoint self._on_stats_back = on_back_view if self._desktop_bar and self._desktop_bar.stats_btn is not None: self._desktop_bar.stats_btn.set_enabled(bool(self._stats_enabled)) def update_level_xp_text(self, text: str | None = None): prev = self._badge_text self._badge_custom_override = text self._refresh_badge_text_from_db() if self._badge_text != prev and self._desktop_bar and not self._is_compact: self._desktop_bar.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 if self._compact_bar is not None: self._compact_bar.close_drawer() if self._desktop_bar is not None: self._desktop_bar.build_static_buttons() self._desktop_bar._last_render_key = (0, 0, 0, 0, 0, 0) if not self._is_compact: self._desktop_bar.sync_bg_and_layout() def _trigger_central_stats(self): if self._locked_exit or not self._stats_enabled: return from view.stats.unified_stats_view import UnifiedStatsView UnifiedStatsView.open( self.ctx, game_endpoint=self._stats_endpoint, on_back=self._on_stats_back, ) 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("", 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 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_mode_and_layout) def _sync_mode_and_layout(self): self._sync_job = None if not self.winfo_exists(): return self._apply_mode_widget(force=False) tk.Widget.tkraise(self) if self._is_compact and self._compact_bar is not None: self._compact_bar.sync_layout() elif not self._is_compact and self._desktop_bar is not None: rh = max(620, self._root_win.winfo_height()) target_h = max(68, int(rh * 0.098)) if int(self.cget("height")) != target_h: self.configure(height=target_h) self._desktop_bar.sync_bg_and_layout() def refresh_text_slots(self): if self._desktop_bar and not self._is_compact: self._desktop_bar.update_badge_item_only()