# -*- coding: utf-8 -*- # games/solitaire/base/solitaire_bottom_bar.py from __future__ import annotations import tkinter as tk from PIL import Image, ImageTk import resources.code_res.game_constants as gc from resources.code_res.game_constants import ( BG_COLOR, FONT_COLOR_HEADING_SUB, FONT_SIZE_SMALL_MIN, UI_ACCENT_AMETHYST, ) from view.widgets.image_button import ImageButton BG_SAFE_SIDE_RATIO = getattr(gc, "BG_SAFE_SIDE_RATIO", 0.088) BG_SAFE_BOTTOM_RATIO = getattr(gc, "BG_SAFE_BOTTOM_RATIO", 0.095) class SolitaireBottomBar(tk.Canvas): """ Gerahmte HUD- & Aktionsleiste innerhalb der unteren Safe-Area von background.jpg. Unterstützt kompakte Pipe-Trenner ('|') sowie zwei optionale Overflow-Erweiterungsflächen links (für Text-Segmente mit Präfix '~') und rechts (für sekundäre Aktions-Buttons), die automatisch nur dann eingeblendet werden, wenn der Platz in der Hauptleiste eng wird. """ CONTENT_H = 48 SUB_TOP_GAP = 3 SUB_BAR_H = 38 MIN_BOTTOM_INSET = 56 # Fein-Offsets für den linken HUD-Textblock ("Punkte: 0 | Züge: 0 | ...") HUD_TEXT_X_OFFSET = 0 # Positiv = weiter nach rechts zur Mitte, Negativ = näher an den linken Rahmen HUD_TEXT_Y_OFFSET = 6 # Optische Vertikalzentrierung im Goldrahmen def __init__(self, parent, ctx, hud_var: tk.StringVar, status_var: tk.StringVar): root_h = max(720, ctx.root.winfo_height()) self._bottom_inset = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO)) init_h = self.CONTENT_H + self._bottom_inset super().__init__( parent, height=init_h, bg=BG_COLOR, bd=0, highlightthickness=0, ) self.ctx = ctx self.assets = ctx.assets self.hud_var = hud_var self.status_var = status_var self._buttons: list[ImageButton] = [] self._bg_ph: ImageTk.PhotoImage | None = None self._frame_ph: ImageTk.PhotoImage | None = None self._sub_left_frame_ph: ImageTk.PhotoImage | None = None self._sub_right_frame_ph: ImageTk.PhotoImage | None = None self._txt_refs: list[ImageTk.PhotoImage] = [] self._last_btn_split: tuple[tuple[int, ...], tuple[int, ...]] | None = None self.hud_var.trace_add("write", lambda *_: self.refresh_texts()) self.status_var.trace_add("write", lambda *_: self.refresh_texts()) self.bind("", self._on_configure) def set_buttons( self, buttons: list[ImageButton], overflow_buttons: list[ImageButton] | None = None, ): """ Setzt die aktiven Leisten-Buttons und räumt alte Button-Widgets sauber ab. Buttons in `overflow_buttons` (oder mit Attribut `can_overflow=True`) bleiben solange möglich oben in der Hauptleiste und weichen bei Platzmangel automatisch rechtsbündig in die untere rechte Erweiterungsfläche aus. """ primary_list = list(buttons) extra_list = list(overflow_buttons) if overflow_buttons else [] for b in extra_list: setattr(b, "can_overflow", True) combined = primary_list + extra_list keep_ids = {id(b) for b in combined} for old_b in self._buttons: if id(old_b) not in keep_ids: try: if old_b.winfo_exists(): old_b.place_forget() old_b.destroy() except Exception: pass self._buttons = combined self._last_btn_split = None self.relayout() self.after(20, self.relayout) def relayout(self): if not self.winfo_exists(): return w = self.winfo_width() h = self.winfo_height() if w >= 120 and h >= 40: self._slice_bg(w, h) self._layout(w, h) def _slice_bg(self, w: int, h: int): root = self.ctx.root rw = max(w, root.winfo_width()) rh = max(h, root.winfo_height()) ox = max(0, min(rw - w, self.winfo_rootx() - root.winfo_rootx())) oy = max(0, min(rh - h, self.winfo_rooty() - root.winfo_rooty())) if hasattr(self.assets, "get_bg_patch_photo"): self._bg_ph = self.assets.get_bg_patch_photo(rw, rh, ox, oy, w, 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 scaled = src.resize((rw, rh), Image.Resampling.BILINEAR) self._bg_ph = ImageTk.PhotoImage(scaled.crop((ox, oy, ox + w, oy + h))) if self._bg_ph is None: return self.delete("bb_bg") self.create_image(0, 0, image=self._bg_ph, anchor="nw", tags="bb_bg") self.tag_lower("bb_bg") def _on_configure(self, event): if event.widget is not self: return w, h = max(1, event.width), max(1, event.height) if w < 120: return root_h = max(600, self.ctx.root.winfo_height()) new_bot = max(self.MIN_BOTTOM_INSET, int(root_h * BG_SAFE_BOTTOM_RATIO)) if new_bot != self._bottom_inset: self._bottom_inset = new_bot h = self.CONTENT_H + self._bottom_inset self.configure(height=h) self._slice_bg(w, h) self._layout(w, h) def _render_seg_photo(self, txt: str) -> ImageTk.PhotoImage: # Dynamische Timer-Segmente (z. B. 00:12) nicht dauerhaft im Text-Cache ablegen if ":" in txt and any(ch.isdigit() for ch in txt) and "'" not in txt: try: pil_seg = self.assets.render_goth_text_pil( txt, size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left", uncached=True, ) except TypeError: pil_seg = self.assets.render_goth_text_pil( txt, size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left", ) return ImageTk.PhotoImage(pil_seg) return self.assets.get_goth_text_photo( txt, size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="left", ) def _prepare_hud_segments(self) -> tuple[list[dict], ImageTk.PhotoImage, int]: raw_hud = (self.hud_var.get() or "").replace("•", "|") raw_parts = [p.strip() for p in raw_hud.split("|") if p.strip()] pipe_ph = self.assets.get_goth_text_photo( "|", size_px=FONT_SIZE_SMALL_MIN + 1, color=FONT_COLOR_HEADING_SUB, align="center", ) pipe_step = pipe_ph.width() + 12 items: list[dict] = [] for part in raw_parts: can_ovf = part.startswith("~") clean_txt = part[1:].strip() if can_ovf else part if not clean_txt: continue ph = self._render_seg_photo(clean_txt) items.append({ "text": clean_txt, "photo": ph, "w": ph.width(), "can_overflow": can_ovf, }) return items, pipe_ph, pipe_step @staticmethod def _calc_segs_width(segs: list[dict], pipe_step: int) -> int: if not segs: return 0 return sum(s["w"] for s in segs) + max(0, len(segs) - 1) * pipe_step @staticmethod def _calc_btns_width(btns: list[ImageButton]) -> int: if not btns: return 0 return sum(b.pixel_width for b in btns) + max(0, len(btns) - 1) * 6 def _compute_partition( self, w: int ) -> tuple[list[dict], list[dict], list[ImageButton], list[ImageButton], ImageTk.PhotoImage, int]: seg_items, pipe_ph, pipe_step = self._prepare_hud_segments() side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO)) avail_main_w = max(200, (w - 2 * side_inset) - 32) min_mid_gap = 22 avail_left_wing = max(120, int(w * 0.415) - side_inset - 24) avail_right_wing = max(120, (w - side_inset) - int(w * 0.585) - 24) top_segs = list(seg_items) sub_segs: list[dict] = [] alive_btns = [b for b in self._buttons if b.winfo_exists()] top_btns = list(alive_btns) sub_btns: list[ImageButton] = [] def fits_main() -> bool: sw = self._calc_segs_width(top_segs, pipe_step) bw = self._calc_btns_width(top_btns) if sw > 0 and bw > 0: return (sw + min_mid_gap + bw) <= avail_main_w return (sw + bw) <= avail_main_w guard = 0 while not fits_main() and guard < 24: guard += 1 moved = False for idx in range(len(top_btns) - 1, -1, -1): cand = top_btns[idx] if getattr(cand, "can_overflow", False): test_sub = [cand] + sub_btns if self._calc_btns_width(test_sub) <= avail_right_wing or not sub_btns: sub_btns.insert(0, top_btns.pop(idx)) moved = True break if moved: continue for idx in range(len(top_segs) - 1, 0, -1): cand_s = top_segs[idx] if cand_s["can_overflow"]: test_sub_s = [cand_s] + sub_segs if self._calc_segs_width(test_sub_s, pipe_step) <= avail_left_wing or not sub_segs: sub_segs.insert(0, top_segs.pop(idx)) moved = True break if moved: continue if len(top_btns) > 1: cand = top_btns[-1] if self._calc_btns_width([cand] + sub_btns) <= avail_right_wing or not sub_btns: sub_btns.insert(0, top_btns.pop()) continue if len(top_segs) > 1: cand_s = top_segs[-1] if self._calc_segs_width([cand_s] + sub_segs, pipe_step) <= avail_left_wing or not sub_segs: sub_segs.insert(0, top_segs.pop()) continue break return top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step def _get_bar_box_photo(self, box_key: str, w: int, h: int, scale: float = 0.80): try: return self.assets.get_box_photo(box_key, (w, h), border_scale=scale) except TypeError: return self.assets.get_box_photo(box_key, (w, h)) def refresh_texts(self): if not self.winfo_exists() or self.winfo_width() < 120: return w, h = self.winfo_width(), self.winfo_height() _ts, _ss, top_b, sub_b, _pp, _ps = self._compute_partition(w) cur_split = (tuple(id(b) for b in top_b), tuple(id(b) for b in sub_b)) if cur_split != self._last_btn_split: self._layout(w, h) else: self._render_partition(w, place_buttons=False) def _layout(self, w: int, _h: int): self.delete("bb_frame") side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO)) frame_w = max(240, w - 2 * side_inset) cy = self.CONTENT_H // 2 self._frame_ph = self._get_bar_box_photo( "box_gold_double", frame_w, self.CONTENT_H - 2, scale=0.85 ) if self._frame_ph: self.create_image(w // 2, cy, image=self._frame_ph, anchor="center", tags="bb_frame") self._render_partition(w, place_buttons=True) def _render_partition(self, w: int, place_buttons: bool = True): self.delete("bb_txt") self.delete("bb_sub_frame") self._txt_refs.clear() self._sub_left_frame_ph = None self._sub_right_frame_ph = None top_segs, sub_segs, top_btns, sub_btns, pipe_ph, pipe_step = self._compute_partition(w) self._txt_refs.append(pipe_ph) side_inset = max(92, int(w * BG_SAFE_SIDE_RATIO)) cy_main = self.CONTENT_H // 2 txt_cy_main = cy_main + self.HUD_TEXT_Y_OFFSET sub_top = self.CONTENT_H + self.SUB_TOP_GAP cy_sub = sub_top + self.SUB_BAR_H // 2 txt_cy_sub = cy_sub + self.HUD_TEXT_Y_OFFSET # 1. Hauptleisten-Buttons (oben rechts) rx_main = w - side_inset - 16 if place_buttons: for btn in reversed(top_btns): bw = btn.pixel_width bh = btn.pixel_height btn.place(x=rx_main - bw, y=cy_main - bh // 2, width=bw, height=bh) tk.Widget.tkraise(btn) rx_main -= (bw + 6) else: rx_main -= self._calc_btns_width(top_btns) # 2. Rechte Erweiterungsfläche (nur sichtbar, wenn Buttons nach unten ausgelagert wurden) if sub_btns: sub_btns_w = self._calc_btns_width(sub_btns) r_box_w = sub_btns_w + 26 r_box_right = w - side_inset r_box_cx = r_box_right - r_box_w // 2 self.create_rectangle( r_box_right - r_box_w + 4, sub_top + 4, r_box_right - 4, sub_top + self.SUB_BAR_H - 4, fill="#100d17", outline="", tags="bb_sub_frame", ) self._sub_right_frame_ph = self._get_bar_box_photo( "box_gold_double", r_box_w, self.SUB_BAR_H, scale=0.72 ) if self._sub_right_frame_ph: self.create_image( r_box_cx, cy_sub, image=self._sub_right_frame_ph, anchor="center", tags="bb_sub_frame", ) if place_buttons: rx_sub = r_box_right - 13 for btn in reversed(sub_btns): bw = btn.pixel_width bh = min(btn.pixel_height, self.SUB_BAR_H - 6) btn.place(x=rx_sub - bw, y=cy_sub - bh // 2, width=bw, height=bh) tk.Widget.tkraise(btn) rx_sub -= (bw + 6) if place_buttons: self._last_btn_split = ( tuple(id(b) for b in top_btns), tuple(id(b) for b in sub_btns), ) # 3. Hauptleisten-Text im freien linken Bereich auf der X-Achse zentrieren min_lx = side_inset + 22 right_limit = rx_main - 14 st_str = (self.status_var.get() or "").replace("•", "|") segs_w = self._calc_segs_width(top_segs, pipe_step) st_ph = None total_txt_w = segs_w if st_str and (right_limit - (min_lx + segs_w)) >= 90: avail_st_w = right_limit - (min_lx + segs_w + (pipe_step if top_segs else 0)) st_ph = self.assets.get_goth_text_photo( st_str, size_px=FONT_SIZE_SMALL_MIN, color=UI_ACCENT_AMETHYST, max_width=max(80, avail_st_w), align="left", ) total_txt_w += (pipe_step if top_segs else 0) + st_ph.width() avail_txt_span = max(0, right_limit - min_lx) if total_txt_w > 0 and avail_txt_span > total_txt_w: # Sanfte Zentrierung im freien Raum links neben den Buttons centered_lx = min_lx + (avail_txt_span - total_txt_w) // 2 + self.HUD_TEXT_X_OFFSET lx = max(min_lx, min(right_limit - total_txt_w, centered_lx)) else: lx = min_lx + self.HUD_TEXT_X_OFFSET for i, seg in enumerate(top_segs): if i > 0: self.create_image(lx + 5, txt_cy_main, image=pipe_ph, anchor="w", tags="bb_txt") lx += pipe_step ph = seg["photo"] self._txt_refs.append(ph) self.create_image(lx, txt_cy_main, image=ph, anchor="w", tags="bb_txt") lx += ph.width() if st_ph is not None: if top_segs: self.create_image(lx + 6, txt_cy_main, image=pipe_ph, anchor="w", tags="bb_txt") lx += pipe_step self._txt_refs.append(st_ph) self.create_image(lx, txt_cy_main, image=st_ph, anchor="w", tags="bb_txt") # 4. Linke Erweiterungsfläche (nur sichtbar, wenn Text-Segmente nach unten ausgelagert wurden) if sub_segs: sub_txt_w = self._calc_segs_width(sub_segs, pipe_step) l_box_w = sub_txt_w + 36 l_box_left = side_inset l_box_cx = l_box_left + l_box_w // 2 self.create_rectangle( l_box_left + 4, sub_top + 4, l_box_left + l_box_w - 4, sub_top + self.SUB_BAR_H - 4, fill="#100d17", outline="", tags="bb_sub_frame", ) self._sub_left_frame_ph = self._get_bar_box_photo( "box_gold_double", l_box_w, self.SUB_BAR_H, scale=0.72 ) if self._sub_left_frame_ph: self.create_image( l_box_cx, cy_sub, image=self._sub_left_frame_ph, anchor="center", tags="bb_sub_frame", ) sub_lx = l_box_cx - sub_txt_w // 2 for i, seg in enumerate(sub_segs): if i > 0: self.create_image(sub_lx + 5, txt_cy_sub, image=pipe_ph, anchor="w", tags="bb_txt") sub_lx += pipe_step ph = seg["photo"] self._txt_refs.append(ph) self.create_image(sub_lx, txt_cy_sub, image=ph, anchor="w", tags="bb_txt") sub_lx += ph.width()