154 lines
5.5 KiB
Python
154 lines
5.5 KiB
Python
"""Splash screen на старте: плакат с диктатором + опциональная музыка."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import contextlib
|
||
import logging
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tkinter as tk
|
||
from pathlib import Path
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
_MAX_IMAGE_SIDE_PX = 600
|
||
|
||
|
||
def show_splash(
|
||
image_path: Path,
|
||
audio_path: Path | None,
|
||
duration_sec: float = 5.0,
|
||
) -> None:
|
||
"""Показывает splash-окно на duration_sec секунд (blocking).
|
||
|
||
Окно без рамки, поверх всех, кликабельно для досрочного закрытия (Esc / клик).
|
||
Если картинка не найдена — функция возвращает управление сразу. Если аудио
|
||
не найдено или формат не поддерживается платформой — splash показывается без
|
||
звука.
|
||
|
||
Args:
|
||
image_path: PNG/JPG для splash. Если файла нет — splash не показывается.
|
||
audio_path: Опциональный аудиофайл. На macOS играется через `afplay`
|
||
(mp3/m4a/wav/aiff/ogg). На Windows используется `winsound`, который
|
||
принимает только `.wav`. Прочее — игнорируется с warning'ом в логе.
|
||
duration_sec: Сколько показывать (5 сек по умолчанию).
|
||
"""
|
||
if not image_path.exists():
|
||
logger.warning("Splash: картинка не найдена: %s", image_path)
|
||
return
|
||
|
||
audio_proc = _play_audio_async(audio_path) if audio_path is not None else None
|
||
|
||
try:
|
||
_run_tk_window(image_path, duration_sec)
|
||
finally:
|
||
_stop_audio(audio_proc)
|
||
|
||
|
||
def _run_tk_window(image_path: Path, duration_sec: float) -> None:
|
||
"""Создаёт borderless Tk-окно с картинкой по центру экрана."""
|
||
try:
|
||
from PIL import Image, ImageTk
|
||
except ImportError as exc:
|
||
logger.warning("Splash: Pillow недоступен (%s), пропускаю", exc)
|
||
return
|
||
|
||
root = tk.Tk()
|
||
root.title("Voice Dictator")
|
||
root.attributes("-topmost", True)
|
||
with contextlib.suppress(tk.TclError):
|
||
root.overrideredirect(True)
|
||
|
||
try:
|
||
img = Image.open(image_path)
|
||
img.thumbnail((_MAX_IMAGE_SIDE_PX, _MAX_IMAGE_SIDE_PX), Image.Resampling.LANCZOS)
|
||
photo = ImageTk.PhotoImage(img)
|
||
except Exception as exc:
|
||
logger.warning("Splash: не удалось открыть картинку: %s", exc)
|
||
with contextlib.suppress(tk.TclError):
|
||
root.destroy()
|
||
return
|
||
|
||
label = tk.Label(root, image=photo, borderwidth=0, highlightthickness=0)
|
||
label.image = photo # type: ignore[attr-defined]
|
||
label.pack()
|
||
|
||
root.update_idletasks()
|
||
width = root.winfo_width()
|
||
height = root.winfo_height()
|
||
screen_w = root.winfo_screenwidth()
|
||
screen_h = root.winfo_screenheight()
|
||
x = (screen_w - width) // 2
|
||
y = (screen_h - height) // 2
|
||
root.geometry(f"+{x}+{y}")
|
||
|
||
def _close(_event: object = None) -> None:
|
||
with contextlib.suppress(tk.TclError):
|
||
root.destroy()
|
||
|
||
root.after(int(duration_sec * 1000), _close)
|
||
root.bind("<Button-1>", _close)
|
||
root.bind("<Escape>", _close)
|
||
|
||
with contextlib.suppress(Exception):
|
||
root.mainloop()
|
||
|
||
|
||
def _play_audio_async(path: Path) -> subprocess.Popen[bytes] | None:
|
||
"""Стартует воспроизведение в фоне. Возвращает процесс (для terminate) или None."""
|
||
if not path.exists():
|
||
logger.debug("Splash audio: файл не найден: %s", path)
|
||
return None
|
||
|
||
if sys.platform == "darwin":
|
||
return _play_audio_macos(path)
|
||
if sys.platform == "win32":
|
||
_play_audio_windows(path)
|
||
return None
|
||
logger.debug("Splash audio: платформа %s не поддержана", sys.platform)
|
||
return None
|
||
|
||
|
||
def _play_audio_macos(path: Path) -> subprocess.Popen[bytes] | None:
|
||
afplay = shutil.which("afplay") or "/usr/bin/afplay"
|
||
try:
|
||
return subprocess.Popen(
|
||
[afplay, str(path)],
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
start_new_session=True,
|
||
)
|
||
except OSError as exc:
|
||
logger.warning("Splash audio: afplay не запустился: %s", exc)
|
||
return None
|
||
|
||
|
||
def _play_audio_windows(path: Path) -> None:
|
||
if path.suffix.lower() != ".wav":
|
||
logger.warning(
|
||
"Splash audio: на Windows поддерживается только .wav, получено %s",
|
||
path.suffix,
|
||
)
|
||
return
|
||
try:
|
||
import winsound
|
||
|
||
winsound.PlaySound( # type: ignore[attr-defined]
|
||
str(path),
|
||
winsound.SND_FILENAME | winsound.SND_ASYNC, # type: ignore[attr-defined]
|
||
)
|
||
except Exception as exc:
|
||
logger.warning("Splash audio: winsound не запустился: %s", exc)
|
||
|
||
|
||
def _stop_audio(proc: subprocess.Popen[bytes] | None) -> None:
|
||
"""Останавливает audio (Mac terminate, Win winsound.PURGE)."""
|
||
if proc is not None:
|
||
with contextlib.suppress(Exception):
|
||
proc.terminate()
|
||
if sys.platform == "win32":
|
||
with contextlib.suppress(Exception):
|
||
import winsound
|
||
|
||
winsound.PlaySound(None, winsound.SND_PURGE) # type: ignore[attr-defined]
|