# -*- coding: utf-8 -*- # view/widgets/bars/goth_burger_topbar.py from __future__ import annotations import tkinter as tk from PIL import Image, ImageDraw, ImageGrab, ImageTk from resources.code_res.game_constants import ( BG_COLOR, FONT_COLOR_HEADING_SUB, FONT_COLOR_STATUS_LOSS, FONT_COLOR_TITLE_MAIN, FONT_SIZE_BODY, FONT_SIZE_SMALL_MIN, SUBTLE_BORDER, UI_ACCENT_AMETHYST, UI_ACCENT_GOLD, ) from resources.code_res.i18n import t from view.widgets.buttons.button_art_compositor import ButtonArtCompositor from view.widgets.buttons.image_button import ImageButton COMPACT_TOPBAR_HEIGHT = 44 COMPACT_TOPBAR_TWO_LINE_H = 58 DRAWER_BG_COLOR = "#171421" _ANIM_STEPS = 8 _ANIM_STEP_MS = 15 _BURGER_BTN_CACHE: dict[tuple[int, int, bool], ImageTk.PhotoImage] = {} def _is_timer_seg(txt: str) -> bool: if ":" not in txt or "'" in txt: return False tail = txt.rsplit(" ", 1)[-1] parts = tail.split(":") return len(parts) in (2, 3) and all(p.isdigit() for p in parts) def _is_redundant_pot_or_street(clean_seg: str, game_folder: str) -> bool: """Filtert doppelte Pot-/Street-Segmente bei Poker & Blackjack (stehen bereits in der Tischmitte).""" if game_folder not in ("poker", "blackjack"): return False low = clean_seg.lower() if low.startswith("pot:") or low.startswith("gesamt-pot") or low.startswith("gold-pot"): return True if low in ("pre-flop", "flop", "turn", "river", "showdown"): return True return False def _get_burger_button_photo(assets, w: int, h: int, hovered: bool) -> ImageTk.PhotoImage: key = (w, h, hovered) if key in _BURGER_BTN_CACHE: return _BURGER_BTN_CACHE[key] src = assets.raw_btn_purple if hovered else assets.raw_btn_default if src is not None: bg, _ = ButtonArtCompositor.scale_button_3slice(src, w, h) else: bg = Image.new("RGBA", (w, h), (26, 20, 38, 240)) draw = ImageDraw.Draw(bg) bar_col = UI_ACCENT_GOLD if hovered else "#ffffff" shadow_col = "#09060e" cx = w // 2 half_len = 9 for dy in (-6, 0, 6): y = h // 2 + dy draw.rounded_rectangle((cx - half_len + 1, y, cx + half_len + 1, y + 2), radius=1, fill=shadow_col) draw.rounded_rectangle((cx - half_len, y - 1, cx + half_len, y + 1), radius=1, fill=bar_col) photo = ImageTk.PhotoImage(bg) _BURGER_BTN_CACHE[key] = photo return photo class CompactBurgerTopbar(tk.Canvas): """ Kompakt-/Mobile-Kopfleiste mit Burger-Button links und dynamischem 1–2-zeiligem HUD rechts: - Übernimmt sämtliche HUD- und Status-Texte aus der Fußleiste oben rechts neben [ ☰ ]. - Wächst bei Bedarf automatisch von 44 px auf 58 px (2 Zeilen), sodass die Karten sauber nach unten rücken. """ def __init__(self, parent, controller_bar): self._cur_h = COMPACT_TOPBAR_HEIGHT super().__init__( parent, height=self._cur_h, bg=BG_COLOR, bd=0, highlightthickness=0, ) self._bar = controller_bar self._root_win = controller_bar._root_win self.assets = controller_bar.assets self.sounds = controller_bar.sounds setattr(self._bar.ctx, "_compact_topbar_hud_cb", self.refresh_hud_texts) self._bg_slice_photo: ImageTk.PhotoImage | None = None self._btn_norm_ph: ImageTk.PhotoImage | None = None self._btn_hov_ph: ImageTk.PhotoImage | None = None self._btn_item_id: int | None = None self._hud_refs: list[ImageTk.PhotoImage] = [] self._timer_item_id: int | None = None self._timer_live_ph: ImageTk.PhotoImage | None = None self._last_timer_txt: str = "" self._last_hud_sig: tuple | None = None self._last_bg_key: tuple[int, int, int, int, int, int] = (0, 0, 0, 0, 0, 0) self._backdrop_cv: tk.Canvas | None = None self._backdrop_item_id: int | None = None self._backdrop_frames: list[ImageTk.PhotoImage] = [] self._drawer_panel: tk.Canvas | None = None self._drawer_refs: list = [] self._drawer_buttons: list[ImageButton] = [] self._panel_w: int = 272 self._anim_job: str | None = None self._is_closing: bool = False self._esc_bind_id: str | None = None self.bind("", self._on_configure) self.bind("", self._on_destroy) @property def total_height(self) -> int: return self._cur_h def _on_destroy(self, event=None): if event is not None and event.widget is not self: return if getattr(self._bar.ctx, "_compact_topbar_hud_cb", None) == self.refresh_hud_texts: setattr(self._bar.ctx, "_compact_topbar_hud_cb", None) self.close_drawer(animate=False) def _on_configure(self, event): if event.widget is not self or event.width < 60: return self.sync_layout() def _collect_hud_segments(self) -> tuple[list[str], str]: hud_var = getattr(self._bar.ctx, "_active_hud_var", None) st_var = getattr(self._bar.ctx, "_active_status_var", None) g_folder = getattr(self._bar.ctx, "game_folder", "") or "" segs: list[str] = [] if hud_var is not None: raw = (hud_var.get() or "").replace("•", "|") for p in raw.split("|"): s = p.strip() if s.startswith("~"): s = s[1:].strip() if s and not _is_redundant_pot_or_street(s, g_folder): segs.append(s) if not segs: for attr in ("_title_text", "title_text", "_title", "title"): val = getattr(self._bar, attr, None) if isinstance(val, str) and val.strip(): segs.append(val.strip()) break extra_lbl = getattr(self._bar, "extra_label", None) if extra_lbl is not None: try: ex_txt = str(extra_lbl.cget("text") or "").strip() if ex_txt and ex_txt not in segs: segs.append(ex_txt) except Exception: pass st_txt = (st_var.get() or "").strip() if st_var is not None else "" return segs, st_txt def _render_seg(self, txt: str, color: str = FONT_COLOR_HEADING_SUB, max_w: int | None = None) -> ImageTk.PhotoImage: if _is_timer_seg(txt): pil_s = self.assets.render_goth_text_pil( txt, size_px=FONT_SIZE_SMALL_MIN, color=color, max_width=max_w, align="left", uncached=True ) return ImageTk.PhotoImage(pil_s) return self.assets.get_goth_text_photo( txt, size_px=FONT_SIZE_SMALL_MIN, color=color, max_width=max_w, align="left" ) def refresh_hud_texts(self): if not self.winfo_exists(): return w = self.winfo_width() if w < 80: return segs, st_txt = self._collect_hud_segments() masked = tuple(f"" if _is_timer_seg(s) else s for s in segs) sig = (w, masked, st_txt) if sig == self._last_hud_sig: cur_t = next((s for s in segs if _is_timer_seg(s)), "") if ( cur_t and cur_t != self._last_timer_txt and self._timer_item_id is not None and self.type(self._timer_item_id) ): self._last_timer_txt = cur_t self._timer_live_ph = self._render_seg(cur_t) self.itemconfigure(self._timer_item_id, image=self._timer_live_ph) return self._draw_hud_area(w, segs, st_txt, sig) def _set_bar_height(self, target_h: int): if target_h == self._cur_h: return self._cur_h = target_h self.configure(height=target_h) if int(self._bar.cget("height")) != target_h: self._bar.configure(height=target_h) self._last_bg_key = (0, 0, 0, 0, 0, 0) def sync_layout(self): if not self.winfo_exists(): return w = max(1, self.winfo_width()) if w < 60: return segs, st_txt = self._collect_hud_segments() masked = tuple(f"" if _is_timer_seg(s) else s for s in segs) self._draw_hud_area(w, segs, st_txt, (w, masked, st_txt), force_bg=False) def _draw_bg_and_burger(self, w: int, force: bool = False): rw = max(1, self._root_win.winfo_width()) rh = max(1, self._root_win.winfo_height()) ox = max(0, min(max(0, rw - w), self.winfo_rootx() - self._root_win.winfo_rootx())) oy = max(0, min(max(0, rh - self._cur_h), self.winfo_rooty() - self._root_win.winfo_rooty())) key = (w, self._cur_h, rw, rh, ox, oy) if not force and key == self._last_bg_key: return self._last_bg_key = key self._bg_slice_photo = self.assets.get_bg_patch_photo( rw, rh, ox, oy, min(w, rw - ox), min(self._cur_h, rh - oy) ) self.delete("c_bg") self.delete("burger_hit") if self._bg_slice_photo is not None: self.create_image(0, 0, image=self._bg_slice_photo, anchor="nw", tags="c_bg") self.tag_lower("c_bg") bw, bh = 48, 34 bx, by = 12 + bw // 2, self._cur_h // 2 self._btn_norm_ph = _get_burger_button_photo(self.assets, bw, bh, False) self._btn_hov_ph = _get_burger_button_photo(self.assets, bw, bh, True) self._btn_item_id = self.create_image( bx, by, image=self._btn_norm_ph, anchor="center", tags="burger_hit" ) hit = self.create_rectangle( bx - bw // 2, by - bh // 2, bx + bw // 2, by + bh // 2, fill="", outline="", width=0, tags="burger_hit", ) self.tag_raise(hit) self.tag_bind("burger_hit", "", lambda _e: self._set_hover(True)) self.tag_bind("burger_hit", "", lambda _e: self._set_hover(False)) self.tag_bind("burger_hit", "", self._toggle_drawer) def _draw_hud_area(self, w: int, segs: list[str], st_txt: str, sig: tuple, force_bg: bool = False): x_start = 72 avail_w = max(120, w - x_start - 12) pipe_ph = self.assets.get_goth_text_photo("|", FONT_SIZE_SMALL_MIN, SUBTLE_BORDER) pipe_step = pipe_ph.width() + 10 rendered: list[tuple[str, ImageTk.PhotoImage]] = [ (s, self._render_seg(s, FONT_COLOR_HEADING_SUB, max_w=avail_w)) for s in segs ] # Segmente gierig auf Zeile 1 und optional Zeile 2 aufteilen line1: list[tuple[str, ImageTk.PhotoImage]] = [] line2: list[tuple[str, ImageTk.PhotoImage]] = [] w1 = w2 = 0 for item in rendered: iw = item[1].width() add1 = iw + (pipe_step if line1 else 0) if not line2 and (w1 + add1 <= avail_w or not line1): line1.append(item) w1 += add1 else: add2 = iw + (pipe_step if line2 else 0) if w2 + add2 <= avail_w or not line2: line2.append(item) w2 += add2 st_ph = None if st_txt: rem2 = avail_w - (w2 + (pipe_step if line2 else 0)) if not line2: st_ph = self._render_seg(st_txt, UI_ACCENT_AMETHYST, max_w=avail_w) elif rem2 >= 90: st_ph = self._render_seg(st_txt, UI_ACCENT_AMETHYST, max_w=rem2) need_two_lines = bool(line2 or st_ph is not None) target_h = COMPACT_TOPBAR_TWO_LINE_H if need_two_lines else COMPACT_TOPBAR_HEIGHT height_changed = (target_h != self._cur_h) if height_changed: self._set_bar_height(target_h) self._draw_bg_and_burger(w, force=force_bg or height_changed) self.delete("c_hud") self._hud_refs.clear() self._hud_refs.append(pipe_ph) self._timer_item_id = None self._last_timer_txt = "" y1 = 17 if need_two_lines else (self._cur_h // 2) y2 = 41 def _place_row(entries: list[tuple[str, ImageTk.PhotoImage]], row_y: int, row_w: int, extra_st=None): total_rw = row_w + ((pipe_step if entries else 0) + extra_st.width() if extra_st else 0) # Rechtsbündig/zentriert im Raum neben dem Burger-Button ausrichten cx = x_start + max(0, (avail_w - total_rw) // 2) for idx, (s_txt, ph) in enumerate(entries): if idx > 0: self.create_image(cx + 3, row_y, image=pipe_ph, anchor="w", tags="c_hud") cx += pipe_step iid = self.create_image(cx, row_y, image=ph, anchor="w", tags="c_hud") if _is_timer_seg(s_txt) and self._timer_item_id is None: self._timer_item_id = iid self._timer_live_ph = ph self._last_timer_txt = s_txt else: self._hud_refs.append(ph) cx += ph.width() if extra_st is not None: if entries: self.create_image(cx + 3, row_y, image=pipe_ph, anchor="w", tags="c_hud") cx += pipe_step self._hud_refs.append(extra_st) self.create_image(cx, row_y, image=extra_st, anchor="w", tags="c_hud") if line1: _place_row(line1, y1, w1, extra_st=None) if need_two_lines: _place_row(line2, y2, w2, extra_st=st_ph) self.create_line(10, self._cur_h - 1, w - 10, self._cur_h - 1, fill=SUBTLE_BORDER, width=1, tags="c_hud") self._last_hud_sig = sig def _set_hover(self, hov: bool): self.configure(cursor="hand2" if hov else "") if self._btn_item_id is not None: ph = self._btn_hov_ph if hov else self._btn_norm_ph if ph is not None: self.itemconfigure(self._btn_item_id, image=ph) def _cancel_anim(self): if self._anim_job is not None: try: self.after_cancel(self._anim_job) except Exception: pass self._anim_job = None def _capture_live_window_pil(self, rw: int, rh: int) -> Image.Image: try: self._root_win.update_idletasks() rx, ry = self._root_win.winfo_rootx(), self._root_win.winfo_rooty() snap = ImageGrab.grab(bbox=(rx, ry, rx + rw, ry + rh)) if snap.size != (rw, rh): snap = snap.resize((rw, rh), Image.Resampling.BILINEAR) return snap.convert("RGB") except Exception: fb = self.assets.get_window_bg_pil(rw, rh) return fb.convert("RGB") if fb is not None else Image.new("RGB", (rw, rh), (15, 12, 22)) def _build_dim_frames(self, base_rgb: Image.Image) -> list[ImageTk.PhotoImage]: dark_target = Image.new("RGB", base_rgb.size, (7, 5, 12)) frames: list[ImageTk.PhotoImage] = [] for step in range(_ANIM_STEPS + 1): eased = 1.0 - (1.0 - (step / _ANIM_STEPS)) ** 3 frames.append(ImageTk.PhotoImage(Image.blend(base_rgb, dark_target, eased * 0.58))) return frames def _toggle_drawer(self, _event=None): self.sounds.play("click") if self._backdrop_cv is not None and self._backdrop_cv.winfo_exists(): self.close_drawer(animate=True) return self._open_drawer() def close_drawer(self, animate: bool = False, on_closed=None): self._cancel_anim() if self._esc_bind_id is not None: try: self._root_win.unbind("", self._esc_bind_id) except Exception: pass self._esc_bind_id = None if ( not animate or self._backdrop_cv is None or not self._backdrop_cv.winfo_exists() or self._drawer_panel is None or not self._drawer_panel.winfo_exists() ): self._destroy_drawer_now() if callable(on_closed): on_closed() return if not self._is_closing: self._is_closing = True self._run_slide_step(_ANIM_STEPS - 1, opening=False, on_done=on_closed) def _destroy_drawer_now(self): self._cancel_anim() self._is_closing = False for b in self._drawer_buttons: try: if b.winfo_exists(): b.destroy() except Exception: pass self._drawer_buttons.clear() self._drawer_refs.clear() self._backdrop_frames.clear() self._backdrop_item_id = None for wgt in (self._drawer_panel, self._backdrop_cv): if wgt is not None: try: if wgt.winfo_exists(): wgt.destroy() except Exception: pass self._drawer_panel = self._backdrop_cv = None def _open_drawer(self): self.close_drawer(animate=False) rw = max(320, self._root_win.winfo_width()) rh = max(420, self._root_win.winfo_height()) self._backdrop_frames = self._build_dim_frames(self._capture_live_window_pil(rw, rh)) ov = tk.Canvas(self._root_win, bg=BG_COLOR, bd=0, highlightthickness=0) ov.place(x=0, y=0, width=rw, height=rh) tk.Widget.tkraise(ov) self._backdrop_cv = ov self._backdrop_item_id = ov.create_image(0, 0, image=self._backdrop_frames[0], anchor="nw", tags="outside") ov.tag_bind("outside", "", lambda _e: (self.sounds.play("click"), self.close_drawer(animate=True))) panel_w = min(276, int(rw * 0.76)) self._panel_w = panel_w panel = tk.Canvas( ov, width=panel_w, height=rh, bg=DRAWER_BG_COLOR, bd=0, relief="flat", highlightthickness=1, highlightbackground=SUBTLE_BORDER, highlightcolor=SUBTLE_BORDER, ) panel.place(x=-panel_w, y=0, width=panel_w, height=rh) self._drawer_panel = panel self._populate_drawer_panel(panel, panel_w) try: self._esc_bind_id = self._root_win.bind( "", lambda _e: (self.sounds.play("click"), self.close_drawer(animate=True), "break")[2], add="+" ) except tk.TclError: self._esc_bind_id = None self._is_closing = False self._run_slide_step(1, opening=True) def _populate_drawer_panel(self, panel: tk.Canvas, panel_w: int): pcx = panel_w // 2 bw, bh = 48, 34 bx, by = 12 + bw // 2, self._cur_h // 2 b_norm = _get_burger_button_photo(self.assets, bw, bh, False) b_hov = _get_burger_button_photo(self.assets, bw, bh, True) self._drawer_refs.extend([b_norm, b_hov]) b_id = panel.create_image(bx, by, image=b_norm, anchor="center", tags="close_burger") b_hit = panel.create_rectangle(bx - bw // 2, by - bh // 2, bx + bw // 2, by + bh // 2, fill="", outline="", width=0, tags="close_burger") panel.tag_raise(b_hit) panel.tag_bind("close_burger", "", lambda _e: (panel.configure(cursor="hand2"), panel.itemconfigure(b_id, image=b_hov))) panel.tag_bind("close_burger", "", lambda _e: (panel.configure(cursor=""), panel.itemconfigure(b_id, image=b_norm))) panel.tag_bind("close_burger", "", lambda _e: (self.sounds.play("click"), self.close_drawer(animate=True))) sep1_y = self._cur_h + 4 panel.create_line(14, sep1_y, panel_w - 14, sep1_y, fill=SUBTLE_BORDER, width=1) prof = self._bar.ctx.profile or {} prog = self._bar.ctx.refresh_game_progress() if prof else {} av_px = 56 av_ph = self.assets.get_avatar_photo(prof.get("avatar_ref"), size_px=av_px) self._drawer_refs.append(av_ph) av_cx, hdr_cy = 18 + av_px // 2, sep1_y + 40 panel.create_image(av_cx, hdr_cy, image=av_ph, anchor="center") u_name = str(prof.get("name", "") or "Soul") if prof.get("is_online"): u_name = f"{u_name} [ON]" lvl_num = int(prog.get("level", 1) or 1) xp_val = int(prog.get("total_points", prog.get("current_xp", 0)) or 0) tx_left = av_cx + av_px // 2 + 12 max_tw = max(90, panel_w - tx_left - 14) name_ph = self.assets.get_goth_text_photo(u_name, FONT_SIZE_BODY + 2, FONT_COLOR_TITLE_MAIN, max_width=max_tw, align="left") xp_ph = self.assets.get_goth_text_photo(f"Lv. {lvl_num} • {xp_val} XP", FONT_SIZE_SMALL_MIN, FONT_COLOR_HEADING_SUB, max_width=max_tw, align="left") self._drawer_refs.extend([name_ph, xp_ph]) panel.create_image(tx_left, hdr_cy - 12, image=name_ph, anchor="w") panel.create_image(tx_left, hdr_cy + 13, image=xp_ph, anchor="w") sep2_y = hdr_cy + 42 panel.create_line(14, sep2_y, panel_w - 14, sep2_y, fill=SUBTLE_BORDER, width=1) cur_y = sep2_y + 32 btn_w = panel_w - 32 btn_norm, btn_purp = self.assets.raw_btn_default, self.assets.raw_btn_purple locked = self._bar._locked_exit if locked: lk_ph = self.assets.get_goth_text_photo(t("devils_deal_locked_badge"), FONT_SIZE_SMALL_MIN, FONT_COLOR_STATUS_LOSS, max_width=btn_w) self._drawer_refs.append(lk_ph) panel.create_image(pcx, cur_y, image=lk_ph, anchor="center") cur_y += 42 else: b_main = ImageButton( panel, t("btn_back_main"), btn_norm, btn_purp, lambda: self.close_drawer(animate=False, on_closed=self._bar._on_main_menu), sound_mgr=self.sounds, width=btn_w, height=38, style="amethyst", ) self._drawer_buttons.append(b_main) panel.create_window(pcx, cur_y, window=b_main, anchor="center") cur_y += 48 if self._bar._stats_enabled: b_stats = ImageButton( panel, t("btn_stats"), btn_norm, btn_purp, lambda: self.close_drawer(animate=False, on_closed=self._bar._trigger_central_stats), sound_mgr=self.sounds, width=btn_w, height=38, style="amethyst", ) self._drawer_buttons.append(b_stats) panel.create_window(pcx, cur_y, window=b_stats, anchor="center") cur_y += 48 b_set = ImageButton( panel, t("btn_settings"), btn_norm, btn_purp, lambda: self.close_drawer(animate=False, on_closed=lambda: self._bar.ctx.open_settings(on_lang_refresh=self._bar._on_lang_refresh)), sound_mgr=self.sounds, width=btn_w, height=38, style="amethyst", ) self._drawer_buttons.append(b_set) panel.create_window(pcx, cur_y, window=b_set, anchor="center") def _run_slide_step(self, step_idx: int, opening: bool, on_done=None): self._anim_job = None if self._backdrop_cv is None or not self._backdrop_cv.winfo_exists() or self._drawer_panel is None or not self._drawer_panel.winfo_exists(): self._destroy_drawer_now() return clamped = max(0, min(_ANIM_STEPS, step_idx)) eased = 1.0 - (1.0 - (clamped / _ANIM_STEPS)) ** 3 self._drawer_panel.place_configure(x=int(round(-self._panel_w * (1.0 - eased)))) if self._backdrop_item_id is not None and clamped < len(self._backdrop_frames): self._backdrop_cv.itemconfigure(self._backdrop_item_id, image=self._backdrop_frames[clamped]) if opening and clamped < _ANIM_STEPS: self._anim_job = self.after(_ANIM_STEP_MS, self._run_slide_step, clamped + 1, True, on_done) elif not opening and clamped > 0: self._anim_job = self.after(_ANIM_STEP_MS, self._run_slide_step, clamped - 1, False, on_done) elif not opening: self._destroy_drawer_now() if callable(on_done): on_done()