490 lines
18 KiB
Python
490 lines
18 KiB
Python
"""Небольшие интерактивные элементы: строки навигации, кнопки-иконки, спарклайн.
|
|
|
|
Всё рисуется на canvas и использует один набор иконок, поэтому хром выглядит
|
|
одинаково во всех вкладках и не зависит от emoji/глифов.
|
|
"""
|
|
|
|
import tkinter as tk
|
|
|
|
import customtkinter as ctk
|
|
|
|
from ..theme import c, ui_font
|
|
from .icons import draw, render_icon
|
|
|
|
|
|
class IconCanvas(tk.Canvas):
|
|
def __init__(self, master, name, size=18, color=None, bg=None):
|
|
# ВАЖНО: не использовать self._name — tkinter сам пишет туда имя виджета.
|
|
self._icon_name = name
|
|
self._icon_size = size
|
|
self._icon_color = color or c("text_dim")
|
|
self._bg = bg or c("sidebar")
|
|
self._photo = None
|
|
super().__init__(master, width=size, height=size, bg=self._bg,
|
|
highlightthickness=0, bd=0)
|
|
self._paint()
|
|
|
|
def _paint(self):
|
|
self.delete("all")
|
|
try:
|
|
self.configure(bg=self._bg)
|
|
except Exception:
|
|
pass
|
|
photo = render_icon(self._icon_name, int(self._icon_size), self._icon_color)
|
|
if photo is not None:
|
|
self._photo = photo
|
|
self.create_image(self._icon_size / 2, self._icon_size / 2,
|
|
image=photo, anchor="center")
|
|
return
|
|
self._photo = None
|
|
draw(self, self._icon_name, self._icon_size, self._icon_color, bg=self._bg)
|
|
|
|
def set(self, bg=None, color=None):
|
|
if bg is not None:
|
|
self._bg = bg
|
|
if color is not None:
|
|
self._icon_color = color
|
|
self._paint()
|
|
|
|
|
|
class Dot(tk.Canvas):
|
|
def __init__(self, master, size=8, color=None, bg=None):
|
|
self._bg = bg or c("sidebar")
|
|
self._color = color or c("text_faint")
|
|
super().__init__(master, width=size, height=size, bg=self._bg,
|
|
highlightthickness=0, bd=0)
|
|
self._size = size
|
|
self._draw()
|
|
|
|
def _draw(self):
|
|
self.delete("all")
|
|
r = self._size / 2 - 0.5
|
|
self.create_oval(0.5, 0.5, self._size - 0.5, self._size - 0.5,
|
|
fill=self._color, outline="")
|
|
|
|
def set(self, bg=None, color=None):
|
|
if bg is not None:
|
|
self._bg = bg
|
|
self.configure(bg=bg)
|
|
if color is not None:
|
|
self._color = color
|
|
self._draw()
|
|
|
|
|
|
class Sparkline(tk.Canvas):
|
|
"""Подпись Xenith: маленький след потерь обучения."""
|
|
|
|
def __init__(self, master, width=64, height=18, bg=None, color=None):
|
|
self._bg = bg or c("panel")
|
|
self._color = color or c("accent")
|
|
super().__init__(master, width=width, height=height, bg=self._bg,
|
|
highlightthickness=0, bd=0)
|
|
self._pw = width
|
|
self._ph = height
|
|
self.set_values([])
|
|
|
|
def set_values(self, values):
|
|
self.delete("all")
|
|
try:
|
|
self.configure(bg=self._bg)
|
|
except Exception:
|
|
pass
|
|
w, h = self._pw, self._ph
|
|
self.create_line(0, h - 1, w, h - 1, fill=c("border"))
|
|
vals = [v for v in (values or []) if v is not None]
|
|
if len(vals) < 2:
|
|
return
|
|
vals = vals[-24:]
|
|
mn, mx = min(vals), max(vals)
|
|
if mx - mn < 1e-9:
|
|
mx = mn + 1e-9
|
|
step = w / (len(vals) - 1)
|
|
pts = []
|
|
for i, v in enumerate(vals):
|
|
x = i * step
|
|
y = 2 + (mx - v) / (mx - mn) * (h - 5)
|
|
pts.extend([x, y])
|
|
self.create_line(*pts, fill=self._color, width=1.5,
|
|
capstyle="round", joinstyle="round")
|
|
|
|
|
|
class _Interactive(ctk.CTkFrame):
|
|
"""База: клик по нажатию + корректный hover без «залипания»."""
|
|
|
|
def __init__(self, master, **kwargs):
|
|
super().__init__(master, **kwargs)
|
|
self._command = None
|
|
self._hover_job = None
|
|
|
|
def _wire(self, widgets):
|
|
for w in widgets:
|
|
w.bind("<Button-1>", self._on_click)
|
|
w.bind("<Enter>", self._on_enter)
|
|
w.bind("<Leave>", self._on_leave)
|
|
try:
|
|
w.configure(cursor="hand2")
|
|
except Exception:
|
|
pass
|
|
|
|
def _on_click(self, event=None):
|
|
if self._command is not None:
|
|
self._command()
|
|
|
|
def _on_enter(self, event=None):
|
|
if self._hover_job is not None:
|
|
try:
|
|
self.after_cancel(self._hover_job)
|
|
except Exception:
|
|
pass
|
|
self._hover_job = None
|
|
self._set_hover(True)
|
|
|
|
def _on_leave(self, event=None):
|
|
if self._hover_job is not None:
|
|
return
|
|
self._hover_job = self.after(20, self._check_pointer)
|
|
|
|
def _check_pointer(self):
|
|
self._hover_job = None
|
|
try:
|
|
if not self.winfo_exists():
|
|
return
|
|
x, y = self.winfo_pointerxy()
|
|
widget = self.winfo_containing(x, y)
|
|
except Exception:
|
|
widget = None
|
|
inside = False
|
|
t = widget
|
|
while t is not None:
|
|
if t is self:
|
|
inside = True
|
|
break
|
|
t = getattr(t, "master", None)
|
|
self._set_hover(inside)
|
|
|
|
def destroy(self):
|
|
if self._hover_job is not None:
|
|
try:
|
|
self.after_cancel(self._hover_job)
|
|
except Exception:
|
|
pass
|
|
self._hover_job = None
|
|
super().destroy()
|
|
|
|
def _set_hover(self, hover):
|
|
pass
|
|
|
|
|
|
class NavItem(_Interactive):
|
|
def __init__(self, master, app, key, text, icon):
|
|
super().__init__(master, height=34, corner_radius=8, fg_color=c("sidebar"))
|
|
self.pack_propagate(False)
|
|
self.app = app
|
|
self.key = key
|
|
self._active = False
|
|
self._command = lambda: self.app.switch_view(self.key)
|
|
|
|
self._icon = IconCanvas(self, icon, 18, c("text_faint"), c("sidebar"))
|
|
self._icon.pack(side="left", padx=(10, 10))
|
|
|
|
self._label = ctk.CTkLabel(self, text=text, font=ui_font(13),
|
|
text_color=c("text_dim"), anchor="w")
|
|
self._label.pack(side="left", fill="x", expand=True, padx=(0, 8))
|
|
|
|
self._wire([self, self._icon, self._label])
|
|
|
|
def set_active(self, active: bool):
|
|
self._active = bool(active)
|
|
self._set_hover(False)
|
|
|
|
def invoke(self):
|
|
self._on_click()
|
|
|
|
def _set_hover(self, hover):
|
|
if self._active:
|
|
bg, txt, ic = c("nav_active_bg"), c("nav_active_text"), c("nav_active_text")
|
|
elif hover:
|
|
bg, txt, ic = c("sidebar_hover"), c("text"), c("text_dim")
|
|
else:
|
|
bg, txt, ic = c("sidebar"), c("text_dim"), c("text_faint")
|
|
self.configure(fg_color=bg)
|
|
self._icon.set(bg=bg, color=ic)
|
|
self._label.configure(text_color=txt)
|
|
|
|
|
|
class IconTextButton(_Interactive):
|
|
def __init__(self, master, text, icon, command, height=36, icon_size=16,
|
|
bg=None, hover=None, border=None, text_color=None, icon_color=None):
|
|
self._bg = bg or c("control")
|
|
self._hover = hover or c("card_hover")
|
|
self._text_color = text_color or c("text")
|
|
self._icon_color = icon_color or c("text_dim")
|
|
super().__init__(master, height=height, corner_radius=8, fg_color=self._bg,
|
|
border_width=1 if border else 0,
|
|
border_color=border or c("border"))
|
|
self.pack_propagate(False)
|
|
self._command = command
|
|
|
|
self._icon = IconCanvas(self, icon, icon_size, self._icon_color, self._bg)
|
|
self._icon.pack(side="left", padx=(12, 8))
|
|
|
|
self._label = ctk.CTkLabel(self, text=text, font=ui_font(13),
|
|
text_color=self._text_color, anchor="w")
|
|
self._label.pack(side="left", fill="x", expand=True, padx=(0, 8))
|
|
|
|
self._wire([self, self._icon, self._label])
|
|
|
|
def _set_hover(self, hover):
|
|
bg = self._hover if hover else self._bg
|
|
self.configure(fg_color=bg)
|
|
self._icon.set(bg=bg, color=c("text") if hover else self._icon_color)
|
|
self._label.configure(text_color=c("text") if hover else self._text_color)
|
|
|
|
|
|
class IconButton(_Interactive):
|
|
def __init__(self, master, icon, command, size=32, icon_size=16, radius=8,
|
|
bg=None, hover=None, icon_color=None, hover_icon_color=None):
|
|
self._bg = bg or c("content")
|
|
self._hover = hover or c("card_hover")
|
|
self._icon_color = icon_color or c("text_dim")
|
|
self._hover_icon_color = hover_icon_color or icon_color or c("text")
|
|
self._enabled = True
|
|
super().__init__(master, width=size, height=size, corner_radius=radius,
|
|
fg_color=self._bg)
|
|
self.pack_propagate(False)
|
|
self.grid_propagate(False)
|
|
self._command = command
|
|
|
|
self._icon = IconCanvas(self, icon, icon_size, self._icon_color, self._bg)
|
|
self._icon.place(relx=0.5, rely=0.5, anchor="center")
|
|
|
|
self._wire([self, self._icon])
|
|
|
|
def set_enabled(self, enabled: bool):
|
|
self._enabled = bool(enabled)
|
|
if self._enabled:
|
|
self._set_hover(False)
|
|
else:
|
|
bg = c("control")
|
|
self.configure(fg_color=bg)
|
|
self._icon.set(bg=bg, color=c("text_faint"))
|
|
|
|
def _on_click(self, event=None):
|
|
if not getattr(self, "_enabled", True):
|
|
return
|
|
super()._on_click(event)
|
|
|
|
def _set_hover(self, hover):
|
|
if not getattr(self, "_enabled", True):
|
|
return
|
|
bg = self._hover if hover else self._bg
|
|
self.configure(fg_color=bg)
|
|
color = self._hover_icon_color if hover else self._icon_color
|
|
self._icon.set(bg=bg, color=color)
|
|
|
|
|
|
class ModelChip(_Interactive):
|
|
"""Чипса выбранной модели по центру верхней панели."""
|
|
|
|
def __init__(self, master, command):
|
|
self._loaded = False
|
|
super().__init__(master, height=32, corner_radius=8, fg_color=c("card"),
|
|
border_width=1, border_color=c("border"))
|
|
self.pack_propagate(False)
|
|
self._command = command
|
|
|
|
self._dot = Dot(self, 8, c("text_faint"), c("card"))
|
|
self._dot.pack(side="left", padx=(12, 8))
|
|
|
|
self._label = ctk.CTkLabel(self, text="Модель не загружена", font=ui_font(12),
|
|
text_color=c("text_dim"), anchor="w")
|
|
self._label.pack(side="left", padx=(0, 10))
|
|
|
|
self._chevron = IconCanvas(self, "chevron_down", 13, c("text_faint"), c("card"))
|
|
self._chevron.pack(side="right", padx=(0, 10))
|
|
|
|
self._wire([self, self._dot, self._label, self._chevron])
|
|
|
|
def set_model(self, name: str, loaded: bool):
|
|
self._loaded = bool(loaded)
|
|
if loaded and name:
|
|
label = name if len(name) <= 30 else name[:29] + "…"
|
|
self._label.configure(text=label)
|
|
self._dot.set(color=c("success"))
|
|
else:
|
|
self._label.configure(text="Модель не загружена")
|
|
self._dot.set(color=c("text_faint"))
|
|
self._set_hover(False)
|
|
|
|
def _set_hover(self, hover):
|
|
bg = c("card_hover") if hover else c("card")
|
|
self.configure(fg_color=bg)
|
|
self._dot.set(bg=bg)
|
|
self._chevron.set(bg=bg, color=(c("text") if hover else c("text_faint")))
|
|
self._label.configure(text_color=c("text") if (hover or self._loaded) else c("text_dim"))
|
|
|
|
|
|
class EngineChip(_Interactive):
|
|
"""Чипса активного движка рядом с моделью."""
|
|
|
|
def __init__(self, master, command):
|
|
super().__init__(master, height=32, width=176, corner_radius=8,
|
|
fg_color=c("card"), border_width=1, border_color=c("border"))
|
|
self.pack_propagate(False)
|
|
self._command = command
|
|
self._ready = True
|
|
|
|
self._dot = Dot(self, 8, c("text_faint"), c("card"))
|
|
self._dot.pack(side="left", padx=(12, 8))
|
|
|
|
self._label = ctk.CTkLabel(self, text="Движок —", font=ui_font(11),
|
|
text_color=c("text_dim"), anchor="w")
|
|
self._label.pack(side="left", fill="x", expand=True)
|
|
|
|
self._chevron = IconCanvas(self, "chevron_down", 13, c("text_faint"), c("card"))
|
|
self._chevron.pack(side="right", padx=(2, 10))
|
|
|
|
self._wire([self, self._dot, self._label, self._chevron])
|
|
|
|
def set_engine(self, name: str, ready: bool = True):
|
|
ready = bool(ready)
|
|
text = str(name or "—")
|
|
if len(text) > 20:
|
|
text = text[:19] + "…"
|
|
label = f"Движок: {text}"
|
|
if label == self._label.cget("text") and ready == self._ready:
|
|
return
|
|
self._ready = ready
|
|
self._label.configure(text=label)
|
|
self._dot.set(color=(c("success") if ready else c("danger")))
|
|
self._set_hover(False)
|
|
|
|
def _set_hover(self, hover):
|
|
bg = c("card_hover") if hover else c("card")
|
|
self.configure(fg_color=bg)
|
|
self._dot.set(bg=bg)
|
|
self._chevron.set(bg=bg, color=(c("text") if hover else c("text_faint")))
|
|
self._label.configure(text_color=(c("text") if hover else c("text_dim")))
|
|
|
|
|
|
class Segmented(ctk.CTkFrame):
|
|
"""Сегментированный переключатель с корректным контрастом.
|
|
|
|
У выбранного сегмента текст берёт роль accent_ink: тёмный на янтаре в
|
|
тёмной теме и светлый — в светлой. У стандартного CTkSegmentedButton
|
|
цвет текста общий для всех сегментов, из-за чего на янтаре он проваливается.
|
|
"""
|
|
|
|
def __init__(self, master, values, command=None, height: int = 32,
|
|
width: int = None, font_size: int = 11, pad: int = 2):
|
|
self._values = [str(v) for v in values]
|
|
self._command = command
|
|
self._current = None
|
|
self._buttons = {}
|
|
if width is None:
|
|
width = sum(max(56, int(len(v) * 7.2) + 32)
|
|
for v in self._values) + pad * 2 + 2
|
|
count = len(self._values)
|
|
segment_width = max(28, (int(width) - pad * 2 - 2) // max(1, count))
|
|
super().__init__(master, fg_color=c("control"), corner_radius=8,
|
|
border_width=1, border_color=c("border"),
|
|
height=height, width=width)
|
|
self.grid_propagate(False)
|
|
self.grid_rowconfigure(0, weight=1)
|
|
for index, value in enumerate(self._values):
|
|
self.grid_columnconfigure(index, weight=1, uniform="seg")
|
|
btn = ctk.CTkButton(
|
|
self, text=value, height=max(18, height - pad * 2 - 2),
|
|
width=segment_width,
|
|
corner_radius=max(4, 8 - pad),
|
|
fg_color="transparent", hover_color=c("control_hover"),
|
|
text_color=c("text_dim"), font=ui_font(font_size),
|
|
command=lambda v=value: self._on_click(v),
|
|
)
|
|
btn.grid(
|
|
row=0, column=index, sticky="nsew",
|
|
padx=(pad if index == 0 else 0,
|
|
pad if index == count - 1 else 0),
|
|
pady=pad,
|
|
)
|
|
self._buttons[value] = btn
|
|
self.set(self._values[0])
|
|
|
|
def _on_click(self, value):
|
|
self.set(value)
|
|
if self._command is not None:
|
|
self._command(value)
|
|
|
|
def set(self, value, notify: bool = False):
|
|
value = str(value)
|
|
if value not in self._buttons:
|
|
return
|
|
self._current = value
|
|
for item, btn in self._buttons.items():
|
|
active = item == value
|
|
try:
|
|
btn.configure(
|
|
fg_color=c("accent_soft") if active else "transparent",
|
|
hover_color=(c("accent_soft") if active else c("control_hover")),
|
|
text_color=(c("accent_text") if active else c("text_dim")),
|
|
)
|
|
except Exception:
|
|
pass
|
|
if notify and self._command is not None:
|
|
self._command(value)
|
|
|
|
def get(self):
|
|
return self._current
|
|
|
|
|
|
def soft_scrollbar(scrollable, bg_role: str = "content"):
|
|
"""Прячет полосу прокрутки, пока содержимое помещается целиком.
|
|
|
|
Ширина полосы сохраняется, поэтому при появлении длинного списка текст
|
|
не сдвигается. В покое полоса сливается с фоном панели и не читается
|
|
как разделитель.
|
|
"""
|
|
|
|
bar = getattr(scrollable, "_scrollbar", None)
|
|
canvas = getattr(scrollable, "_parent_canvas", None)
|
|
if bar is None or canvas is None:
|
|
return None
|
|
idle = c("scrollbar_hover")
|
|
hover = c("border_strong")
|
|
base = c(bg_role)
|
|
state = {"visible": None}
|
|
|
|
def apply_visibility(overflow: bool):
|
|
if state["visible"] == overflow:
|
|
return
|
|
state["visible"] = overflow
|
|
try:
|
|
if overflow:
|
|
bar.configure(fg_color=base, button_color=idle,
|
|
button_hover_color=hover)
|
|
else:
|
|
bar.configure(fg_color=base, button_color=base,
|
|
button_hover_color=base)
|
|
except Exception:
|
|
pass
|
|
|
|
def on_scroll(first, last):
|
|
try:
|
|
bar.set(first, last)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
overflow = not (float(first) <= 0.001 and float(last) >= 0.999)
|
|
except Exception:
|
|
overflow = True
|
|
apply_visibility(overflow)
|
|
|
|
try:
|
|
bar.configure(width=8, fg_color=base, button_color=base,
|
|
button_hover_color=base)
|
|
canvas.configure(yscrollcommand=on_scroll)
|
|
state["visible"] = False
|
|
except Exception:
|
|
return None
|
|
return on_scroll
|