# -*- coding: utf-8 -*- # view/menus/profile_view.py from __future__ import annotations from pathlib import Path import tkinter as tk from tkinter import filedialog from PIL import ImageTk from models.avatar_composer import AvatarComposer, DEFAULT_AVATAR_FILENAME from models.database import Database from resources.code_res.game_constants import ( BG_COLOR, FONT_COLOR_BODY_DEFAULT, FONT_COLOR_BODY_MUTED, FONT_COLOR_HEADING_SUB, FONT_COLOR_STATUS_LOSS, FONT_COLOR_STATUS_WIN, FONT_COLOR_TITLE_MAIN, FONT_SIZE_BODY, FONT_SIZE_HEADING, FONT_SIZE_SMALL_MIN, SUBTLE_BORDER, UI_ACCENT_AMETHYST, UI_ACCENT_GOLD, ) from resources.code_res.i18n import t from view.widgets.goth_dropdown import GothDropdown from view.widgets.goth_entry import GothEntry from view.widgets.image_button import ImageButton class ProfileView: """ Vollflächige Seelen-Profilansicht (Desktop & Mobile): - Großes Profilbild, Gesamt-Profillevel & XP-Fortschritt über alle Spiele - Eindeutige Profil-Umbenennung per ID - Visuelles Auswahl-Raster aller runden Avatar-Presets + eigener Bild-Upload mit empty_ring.png """ def __init__(self, root_view): self.root = root_view self.ctrl = root_view.ctrl self.assets = root_view.assets self.sounds = root_view.ctrl.sounds self._cv: tk.Canvas | None = None self._on_back = None self._owned_widgets: list[tk.Widget] = [] self._photo_refs: list[ImageTk.PhotoImage] = [] self._cfg_bind_id: str | None = None self._feedback_txt: str = "" self._feedback_err: bool = False self._btn_back: ImageButton | None = None self._name_entry: GothEntry | None = None self._name_var: tk.StringVar | None = None self._btn_save_name: ImageButton | None = None self._btn_upload: ImageButton | None = None def _destroy_owned_widgets(self): for wgt in self._owned_widgets: try: if wgt is not None and wgt.winfo_exists(): wgt.destroy() except Exception: pass self._owned_widgets.clear() self._btn_back = self._btn_save_name = self._btn_upload = None self._name_entry = None def _unbind_canvas(self): if self._cv is not None and self._cfg_bind_id is not None: try: self._cv.unbind("", self._cfg_bind_id) except Exception: pass self._cfg_bind_id = None def show(self, on_back=None, feedback_txt: str = "", feedback_err: bool = False): if not self.ctrl.active_profile: self.ctrl.start() return GothDropdown.close_any_open_popup() ImageButton.close_active_hover_tip() self._unbind_canvas() self._destroy_owned_widgets() self._on_back = on_back self._feedback_txt = feedback_txt self._feedback_err = feedback_err # Frisches Profil inkl. avatar_ref aus DB holen fresh = Database.get_profile_by_id(self.ctrl.active_profile["id"]) if fresh: if self.ctrl.is_online_mode: fresh = dict(fresh) fresh["is_online"] = True fresh["online_endpoint"] = self.ctrl.online_session.endpoint_label self.ctrl.active_profile = fresh self.root.clear_window(apply_global_bg=True) cv = self.root.bg_widget if not isinstance(cv, tk.Canvas): cv = tk.Canvas(self.root, bg=BG_COLOR, highlightthickness=0, bd=0) cv.place(relx=0, rely=0, relwidth=1, relheight=1) self._cv = cv self._build_controls(cv) self._cfg_bind_id = cv.bind("", self._on_configure, add="+") self.root.update_idletasks() self._draw_scene(max(980, cv.winfo_width()), max(700, cv.winfo_height())) def _handle_back(self): ImageButton.close_active_hover_tip() self._unbind_canvas() self._destroy_owned_widgets() if callable(self._on_back): self._on_back() else: self.ctrl.show_main_menu() def _build_controls(self, cv: tk.Canvas): prof = self.ctrl.active_profile is_online = bool(prof.get("is_online")) btn_norm = self.assets.raw_btn_default btn_purp = self.assets.raw_btn_purple btn_fire = self.assets.raw_btn_fire or btn_purp self._btn_back = ImageButton( cv, t("btn_back_main"), btn_norm, btn_purp, self._handle_back, sound_mgr=self.sounds, width=152, height=36, style="amethyst", ) self._name_var = tk.StringVar(value=prof["name"]) self._name_entry = GothEntry( cv, self.assets, width=250, height=38, textvariable=self._name_var, enabled=not is_online, ) self._name_entry.bind_return(lambda _e: self._on_save_name()) self._btn_save_name = ImageButton( cv, t("profile_btn_save_name"), btn_fire, btn_fire, self._on_save_name, sound_mgr=self.sounds, width=176, height=38, enabled=not is_online, style="fire", ) self._btn_upload = ImageButton( cv, t("profile_btn_upload_avatar"), btn_fire, btn_fire, self._on_upload_custom_avatar, sound_mgr=self.sounds, width=224, height=36, style="fire", ) self._owned_widgets.extend([ self._btn_back, self._name_entry, self._btn_save_name, self._btn_upload ]) def _on_save_name(self): if not self.ctrl.active_profile or self._name_entry is None: return pid = self.ctrl.active_profile["id"] candidate = self._name_entry.get().strip() if candidate == self.ctrl.active_profile["name"]: return ok, info_or_err = Database.rename_profile(pid, candidate) if not ok: self.sounds.play("lose") self._feedback_txt = t(info_or_err) self._feedback_err = True else: self.sounds.play("win") self.ctrl.active_profile["name"] = info_or_err self._feedback_txt = t("profile_msg_name_saved", info_or_err) self._feedback_err = False if self._cv and self._cv.winfo_exists(): self._draw_scene(max(980, self._cv.winfo_width()), max(700, self._cv.winfo_height())) def _on_select_preset(self, filename: str): if not self.ctrl.active_profile: return pid = self.ctrl.active_profile["id"] Database.update_profile_avatar(pid, filename) self.ctrl.active_profile["avatar_ref"] = filename self._feedback_txt = t("profile_msg_avatar_updated") self._feedback_err = False if self._cv and self._cv.winfo_exists(): self._draw_scene(max(980, self._cv.winfo_width()), max(700, self._cv.winfo_height())) def _on_upload_custom_avatar(self): if not self.ctrl.active_profile: return picked = filedialog.askopenfilename( parent=self.root, title=t("profile_upload_dialog_title"), filetypes=[ ("Images", "*.png *.jpg *.jpeg *.webp *.bmp"), ("All Files", "*"), ], ) if not picked or isinstance(picked, tuple): return pid = self.ctrl.active_profile["id"] try: new_ref = AvatarComposer.import_custom_avatar( self.assets.res, Path(str(picked)), pid ) Database.update_profile_avatar(pid, new_ref) self.assets.invalidate_avatar_cache() self.ctrl.active_profile["avatar_ref"] = new_ref self.sounds.play("win") self._feedback_txt = t("profile_msg_custom_uploaded") self._feedback_err = False except Exception as exc: self.sounds.play("lose") self._feedback_txt = t("profile_err_upload_failed", str(exc)) self._feedback_err = True if self._cv and self._cv.winfo_exists(): self._draw_scene(max(980, self._cv.winfo_width()), max(700, self._cv.winfo_height())) def _on_configure(self, event): if event.widget == self._cv and event.width >= 200 and event.height >= 200: self._draw_scene(event.width, event.height) def _draw_scene(self, w: int, h: int): cv = self._cv if cv is None or not cv.winfo_exists() or not self.ctrl.active_profile: return cv.delete("profile_fg") self._photo_refs.clear() prof = self.ctrl.active_profile pid = prof["id"] cur_avatar_ref = prof.get("avatar_ref") or DEFAULT_AVATAR_FILENAME overall = Database.get_profile_overall_progress(pid) pad_x = max(72, int(w * 0.075)) content_w = min(1080, w - 2 * pad_x) left_x = (w - content_w) // 2 top_y = max(56, int(h * 0.088)) if self._btn_back and self._btn_back.winfo_exists(): cv.create_window(left_x, top_y, window=self._btn_back, anchor="w", tags="profile_fg") hdr_ph = self.assets.get_goth_text_photo( t("profile_view_title"), FONT_SIZE_HEADING + 2, FONT_COLOR_TITLE_MAIN ) self._photo_refs.append(hdr_ph) cv.create_image(w // 2, top_y, image=hdr_ph, anchor="center", tags="profile_fg") sep_y = top_y + 34 cv.create_line(left_x, sep_y, left_x + content_w, sep_y, fill=SUBTLE_BORDER, width=1, tags="profile_fg") # --- 1. Obere Karte: Große Avatar-Vorschau, Gesamtlevel & Namensänderung --- cur_y = sep_y + 18 top_card_h = 166 top_cy = cur_y + top_card_h // 2 top_box = self.assets.get_box_photo("box_gold_double", (content_w, top_card_h)) if top_box: self._photo_refs.append(top_box) cv.create_image(w // 2, top_cy, image=top_box, anchor="center", tags="profile_fg") big_av_sz = 128 big_av_ph = self.assets.get_avatar_photo(cur_avatar_ref, size_px=big_av_sz) self._photo_refs.append(big_av_ph) av_cx = left_x + 30 + big_av_sz // 2 cv.create_image(av_cx, top_cy, image=big_av_ph, anchor="center", tags="profile_fg") info_x = av_cx + big_av_sz // 2 + 26 lvl_txt = t( "profile_overall_rank_line", overall["level"], overall["title"], overall["total_points"], ) lvl_ph = self.assets.get_goth_text_photo( lvl_txt, FONT_SIZE_HEADING - 3, FONT_COLOR_TITLE_MAIN, max_width=content_w - 220, align="left", ) summary_txt = t( "profile_overall_matches_line", overall["games_played"], overall["games_won"], overall["win_pct"], ) sum_ph = self.assets.get_goth_text_photo( summary_txt, FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=content_w - 430, align="left", ) self._photo_refs.extend([lvl_ph, sum_ph]) cv.create_image(info_x, cur_y + 30, image=lvl_ph, anchor="w", tags="profile_fg") cv.create_image(info_x, cur_y + 60, image=sum_ph, anchor="w", tags="profile_fg") # XP-Fortschrittsbalken zum nächsten Gesamtlevel oben rechts in der Karte bar_w = 210 bx2 = left_x + content_w - 28 bx1 = bx2 - bar_w by1, by2 = cur_y + 53, cur_y + 67 cv.create_rectangle(bx1, by1, bx2, by2, fill="#0b0810", outline=UI_ACCENT_GOLD, width=1, tags="profile_fg") xp_ratio = max(0.0, min(1.0, float(overall["current_xp"]) / max(1.0, float(overall["needed_xp"])))) if xp_ratio > 0.0: fw = max(2, int((bar_w - 4) * xp_ratio)) cv.create_rectangle( bx1 + 2, by1 + 2, bx1 + 2 + fw, by2 - 2, fill=UI_ACCENT_AMETHYST, outline="", tags="profile_fg", ) # Namenszeile unten in der oberen Karte row_name_y = cur_y + 116 n_lbl = self.assets.get_goth_text_photo( t("profile_lbl_name"), FONT_SIZE_BODY + 1, FONT_COLOR_BODY_DEFAULT, align="left" ) self._photo_refs.append(n_lbl) cv.create_image(info_x, row_name_y, image=n_lbl, anchor="w", tags="profile_fg") entry_x = info_x + n_lbl.width() + 14 if self._name_entry and self._name_entry.winfo_exists(): cv.create_window(entry_x, row_name_y, window=self._name_entry, anchor="w", tags="profile_fg") if self._btn_save_name and self._btn_save_name.winfo_exists(): cv.create_window( entry_x + 264, row_name_y, window=self._btn_save_name, anchor="w", tags="profile_fg" ) if self._feedback_txt: fb_col = FONT_COLOR_STATUS_LOSS if self._feedback_err else FONT_COLOR_STATUS_WIN fb_ph = self.assets.get_goth_text_photo( self._feedback_txt, FONT_SIZE_SMALL_MIN, fb_col, max_width=max(160, (left_x + content_w - 26) - (entry_x + 455)), align="right", ) self._photo_refs.append(fb_ph) cv.create_image(left_x + content_w - 28, row_name_y, image=fb_ph, anchor="e", tags="profile_fg") # --- 2. Untere Karte: Avatar-Galerie (Presets + eigener Bild-Upload) --- gal_top = cur_y + top_card_h + 18 bot_margin = max(54, int(h * 0.082)) gal_h = max(250, h - gal_top - bot_margin) gal_cy = gal_top + gal_h // 2 gal_box = self.assets.get_box_photo("box_big", (content_w, gal_h)) if gal_box: self._photo_refs.append(gal_box) cv.create_image(w // 2, gal_cy, image=gal_box, anchor="center", tags="profile_fg") sec_hdr = self.assets.get_goth_text_photo( t("profile_sec_avatars"), FONT_SIZE_HEADING - 3, FONT_COLOR_HEADING_SUB, align="left" ) sec_hint = self.assets.get_goth_text_photo( t("profile_sec_avatars_desc"), FONT_SIZE_SMALL_MIN, FONT_COLOR_BODY_MUTED, max_width=content_w - 290, align="left", ) self._photo_refs.extend([sec_hdr, sec_hint]) cv.create_image(left_x + 28, gal_top + 26, image=sec_hdr, anchor="w", tags="profile_fg") cv.create_image(left_x + 28, gal_top + 52, image=sec_hint, anchor="w", tags="profile_fg") if self._btn_upload and self._btn_upload.winfo_exists(): cv.create_window( left_x + content_w - 26, gal_top + 38, window=self._btn_upload, anchor="e", tags="profile_fg", ) # Alle verfügbaren Avatare sammeln (ggf. eigener Custom-Avatar zuerst + alle Presets) items: list[tuple[str, bool]] = [] if str(cur_avatar_ref).startswith("custom:"): items.append((cur_avatar_ref, True)) for fname in AvatarComposer.list_preset_filenames(self.assets.res): items.append((fname, False)) grid_y1 = gal_top + 74 grid_y2 = gal_top + gal_h - 18 grid_avail_h = max(140, grid_y2 - grid_y1) grid_avail_w = content_w - 64 cols = min(len(items), max(4, min(6, grid_avail_w // 146))) rows = (len(items) + cols - 1) // cols icon_px = max(72, min(104, (grid_avail_h - (rows - 1) * 14) // max(1, rows) - 12)) hover_px = icon_px + 10 step_x = min(icon_px + 38, grid_avail_w // max(1, cols)) step_y = icon_px + 18 start_y = (grid_y1 + grid_y2) // 2 - ((rows - 1) * step_y) // 2 for idx, (av_ref, is_custom) in enumerate(items): r, c = divmod(idx, cols) in_row = min(cols, len(items) - r * cols) ix = w // 2 - ((in_row - 1) * step_x) // 2 + c * step_x iy = start_y + r * step_y is_selected = (av_ref == cur_avatar_ref) self._draw_avatar_choice_slot( cv, ix, iy, idx, av_ref, icon_px, hover_px, is_selected, is_custom ) def _draw_avatar_choice_slot( self, cv: tk.Canvas, cx: int, cy: int, idx: int, av_ref: str, icon_px: int, hover_px: int, is_selected: bool, is_custom: bool, ): tag = f"av_slot_{idx}" tags = ("profile_fg", tag) ph_norm = self.assets.get_avatar_photo(av_ref, size_px=icon_px) ph_hov = self.assets.get_avatar_photo(av_ref, size_px=hover_px) self._photo_refs.extend([ph_norm, ph_hov]) ring_r = icon_px // 2 + 5 ring_id = cv.create_oval( cx - ring_r, cy - ring_r, cx + ring_r, cy + ring_r, outline=UI_ACCENT_GOLD if is_selected else "", width=3 if is_selected else 2, tags=tags, ) img_id = cv.create_image(cx, cy, image=ph_norm, anchor="center", tags=tags) if is_custom: badge_ph = self.assets.get_goth_text_photo( t("profile_custom_badge"), max(12, FONT_SIZE_SMALL_MIN - 3), FONT_COLOR_TITLE_MAIN ) self._photo_refs.append(badge_ph) cv.create_image(cx, cy + icon_px // 2 + 8, image=badge_ph, anchor="center", tags=tags) hit = cv.create_rectangle( cx - hover_px // 2 - 4, cy - hover_px // 2 - 4, cx + hover_px // 2 + 4, cy + hover_px // 2 + 4, fill="", outline="", width=0, tags=tags, ) cv.tag_raise(hit) def _enter(_e): cv.configure(cursor="hand2") cv.itemconfigure(img_id, image=ph_hov) if not is_selected: cv.itemconfigure(ring_id, outline=UI_ACCENT_AMETHYST) def _leave(_e): cv.configure(cursor="") cv.itemconfigure(img_id, image=ph_norm) if not is_selected: cv.itemconfigure(ring_id, outline="") cv.tag_bind(tag, "", _enter) cv.tag_bind(tag, "", _leave) cv.tag_bind( tag, "", lambda _e, r=av_ref: (self.sounds.play("click"), self._on_select_preset(r)), )