codis 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/ui/zen_media.py
ADDED
|
@@ -0,0 +1,2271 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Codis - Zen Media Player
|
|
3
|
+
========================
|
|
4
|
+
Módulo responsável pelo player de mídia integrado ao modo Zen do Codis.
|
|
5
|
+
|
|
6
|
+
Componentes principais:
|
|
7
|
+
- :class:`ZenMediaPlayer` - Motor de reprodução (MPV ou VLC), thread-safe.
|
|
8
|
+
- :class:`ZenMiniOrb` - Janela-bolinha compacta; clique expande para o HUD.
|
|
9
|
+
- :class:`ZenPlaylistPopup` - Popup de seleção rápida de faixa no HUD.
|
|
10
|
+
- :class:`ZenMediaDialog` - Diálogo de configuração de playlist e autoplay.
|
|
11
|
+
|
|
12
|
+
Arquitetura de janelas
|
|
13
|
+
----------------------
|
|
14
|
+
HUD e MiniOrb são ``tk.Toplevel`` **reais** (não ``tk.Frame`` com ``place()``).
|
|
15
|
+
Isso garante:
|
|
16
|
+
* Movimentação e redimensionamento nativos pelo gerenciador de janelas do OS.
|
|
17
|
+
* Independência do Codis: minimizar/maximizar o Codis não afeta o player.
|
|
18
|
+
* Clicar fora não fecha nem esconde o player.
|
|
19
|
+
* Fechar o HUD via ``✕`` converte para a bolinha - nunca some completamente.
|
|
20
|
+
* A bolinha converte de volta para o HUD completo com um clique.
|
|
21
|
+
|
|
22
|
+
Isolamento
|
|
23
|
+
----------
|
|
24
|
+
Por padrão o mpv/VLC rodam num processo filho (:mod:`src.ui.zen_media_host`,
|
|
25
|
+
controlado por :class:`~src.ui.zen_media_client.MediaHostClient`). Uma falha
|
|
26
|
+
nativa do libvlc/libmpv, que o Python não consegue capturar, derruba só esse
|
|
27
|
+
processo: o Codis registra o ocorrido e a próxima faixa sobe um novo. Com
|
|
28
|
+
``CODIS_MEDIA_INPROC=1`` o motor roda dentro do próprio processo.
|
|
29
|
+
|
|
30
|
+
Concorrência
|
|
31
|
+
------------
|
|
32
|
+
* ``stop`` e a troca de faixa não bloqueiam a thread principal (sem ``join()``).
|
|
33
|
+
* O contador de geração ``_gen`` descarta callbacks de reproduções antigas.
|
|
34
|
+
* Criar e encerrar backends roda em threads daemon, uma operação por vez
|
|
35
|
+
(``_backend_lock``): dois players nunca disputam a mesma superfície.
|
|
36
|
+
|
|
37
|
+
Vídeo
|
|
38
|
+
-----
|
|
39
|
+
O motor não cria janelas. A interface registra uma superfície com
|
|
40
|
+
:meth:`ZenMediaPlayer.set_video_surface` (o id nativo de um ``tk.Frame``) e o
|
|
41
|
+
mpv/VLC desenham o vídeo dentro dela. Sem superfície registrada, arquivos de
|
|
42
|
+
vídeo tocam só o áudio. Se a superfície muda no meio da faixa (janela
|
|
43
|
+
minimizada, player encaixado ou destacado), a faixa é reiniciada na posição
|
|
44
|
+
atual com a saída correta.
|
|
45
|
+
|
|
46
|
+
Uma janela só pode ser destruída depois que o backend parou de desenhar nela;
|
|
47
|
+
senão o libvlc acessa um HWND que não existe mais e derruba o processo. Quem
|
|
48
|
+
vai destruir a superfície chama :meth:`ZenMediaPlayer.release_video_surface`
|
|
49
|
+
com um ``on_released``, e o motor o chama quando ela estiver livre.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
from __future__ import annotations
|
|
53
|
+
|
|
54
|
+
import contextlib
|
|
55
|
+
import logging
|
|
56
|
+
import math
|
|
57
|
+
import os
|
|
58
|
+
import random
|
|
59
|
+
import shutil
|
|
60
|
+
import sys
|
|
61
|
+
import threading
|
|
62
|
+
import time
|
|
63
|
+
import tkinter as tk
|
|
64
|
+
from collections.abc import Callable
|
|
65
|
+
from pathlib import Path
|
|
66
|
+
from tkinter import filedialog
|
|
67
|
+
from typing import Any, NamedTuple
|
|
68
|
+
from urllib.parse import urlparse
|
|
69
|
+
|
|
70
|
+
from src.i18n import _t
|
|
71
|
+
from src.theme.utils import alpha_blend_hex
|
|
72
|
+
from src.ui.grab_safe import safe_grab_set
|
|
73
|
+
from src.ui.zen_audio import apply_vlc_equalizer, clamp_gains, mpv_af_string
|
|
74
|
+
from src.ui.zen_media_client import HOST_QUIT_WAIT, MediaHostClient, RemotePlayback
|
|
75
|
+
|
|
76
|
+
logger = logging.getLogger("Codis.ZenMedia")
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
import mpv
|
|
80
|
+
|
|
81
|
+
MPV_AVAILABLE = True
|
|
82
|
+
except Exception:
|
|
83
|
+
MPV_AVAILABLE = False
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
import vlc
|
|
87
|
+
|
|
88
|
+
VLC_AVAILABLE = True
|
|
89
|
+
except Exception:
|
|
90
|
+
VLC_AVAILABLE = False
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _is_youtube(url: str) -> bool:
|
|
94
|
+
"""True se o host da URL é youtube.com, youtu.be ou um subdomínio deles.
|
|
95
|
+
|
|
96
|
+
Compara o *hostname* parseado (não substring), para que ``evil.com/?youtube.com``
|
|
97
|
+
ou ``youtube.com.evil.com`` não sejam tratados como YouTube.
|
|
98
|
+
"""
|
|
99
|
+
try:
|
|
100
|
+
# aceita também "youtube.com/watch?v=..." sem esquema
|
|
101
|
+
parsed = urlparse(url if "://" in url else "//" + url)
|
|
102
|
+
host = (parsed.hostname or "").lower()
|
|
103
|
+
except ValueError:
|
|
104
|
+
return False
|
|
105
|
+
return any(host == d or host.endswith("." + d) for d in ("youtube.com", "youtu.be"))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _parse_entry(entry) -> dict[str, str]:
|
|
109
|
+
"""Converte uma entrada de playlist em dicionário ``{name, url}``.
|
|
110
|
+
|
|
111
|
+
Aceita strings simples (caminhos ou URLs) ou dicionários já formatados.
|
|
112
|
+
Para URLs do YouTube extrai um nome legível do ID de vídeo.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
entry: String de caminho/URL ou dicionário com chaves ``name`` e ``url``.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
Dicionário com as chaves ``"name"`` e ``"url"``.
|
|
119
|
+
"""
|
|
120
|
+
if isinstance(entry, dict):
|
|
121
|
+
return {
|
|
122
|
+
"name": str(entry.get("name", entry.get("url", "Faixa"))),
|
|
123
|
+
"url": str(entry.get("url", "")),
|
|
124
|
+
}
|
|
125
|
+
url = str(entry)
|
|
126
|
+
if _is_youtube(url):
|
|
127
|
+
if "watch?v=" in url:
|
|
128
|
+
name = url.rsplit("watch?v=", 1)[-1].split("&", 1)[0]
|
|
129
|
+
else:
|
|
130
|
+
name = url.rsplit("/", 1)[-1]
|
|
131
|
+
else:
|
|
132
|
+
name = Path(url).name or url
|
|
133
|
+
return {"name": name, "url": url}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _fmt_time(s: float) -> str:
|
|
137
|
+
"""Formata segundos em string legível ``M:SS`` ou ``H:MM:SS``.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
s: Tempo em segundos. Valores nulos ou negativos retornam ``"0:00"``.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
String formatada no padrão ``M:SS`` ou ``H:MM:SS``.
|
|
144
|
+
"""
|
|
145
|
+
if not s or s < 0:
|
|
146
|
+
return "0:00"
|
|
147
|
+
s = int(s)
|
|
148
|
+
h = s // 3600
|
|
149
|
+
m = (s % 3600) // 60
|
|
150
|
+
s = s % 60
|
|
151
|
+
return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _clamp(value: float, lo: float, hi: float) -> float:
|
|
155
|
+
"""Restringe *value* ao intervalo [lo, hi].
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
value: Valor a restringir.
|
|
159
|
+
lo: Limite inferior.
|
|
160
|
+
hi: Limite superior.
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
Valor restrito ao intervalo.
|
|
164
|
+
"""
|
|
165
|
+
return max(lo, min(hi, value))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
_alpha_blend_hex = alpha_blend_hex
|
|
169
|
+
|
|
170
|
+
# Tempo máximo esperando o VLC sair da abertura da mídia antes de pará-lo.
|
|
171
|
+
_VLC_OPEN_WAIT = 4.0
|
|
172
|
+
# Intervalo mínimo entre a última busca e o ``stop()``: o libvlc ainda processa
|
|
173
|
+
# a busca depois de ``set_time`` retornar e parar nesse intervalo derruba o processo.
|
|
174
|
+
_VLC_SEEK_SETTLE = 0.8
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class _Retired(NamedTuple):
|
|
178
|
+
"""Backend já desanexado do player, aguardando o encerramento em segundo plano."""
|
|
179
|
+
|
|
180
|
+
instance: Any
|
|
181
|
+
kind: str | None
|
|
182
|
+
stop_ev: threading.Event
|
|
183
|
+
poll: threading.Thread | None
|
|
184
|
+
wid: int | None
|
|
185
|
+
seeked_at: float = 0.0
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class ZenMediaPlayer:
|
|
189
|
+
"""Motor de reprodução de mídia usando python-vlc ou python-mpv.
|
|
190
|
+
|
|
191
|
+
Thread-safety
|
|
192
|
+
-------------
|
|
193
|
+
1. **Contador de geração** (``_gen``): cada ``play()`` incrementa o contador
|
|
194
|
+
e os callbacks do backend conferem se a geração ainda é a mesma antes de
|
|
195
|
+
agir. Isso evita que o ``end-file`` de uma faixa antiga acione ``next()``
|
|
196
|
+
na faixa nova.
|
|
197
|
+
|
|
198
|
+
2. **Stop não-bloqueante**: desanexa a instância imediatamente e encerra
|
|
199
|
+
numa thread daemon. A thread principal não espera por ela, a não ser
|
|
200
|
+
em :meth:`shutdown`, que mantém o laço do Tk girando enquanto aguarda.
|
|
201
|
+
|
|
202
|
+
3. **Uma operação de backend por vez** (``_backend_lock``): o encerramento
|
|
203
|
+
do player anterior termina antes de o próximo ser criado. A troca de
|
|
204
|
+
geração e a atribuição da instância ativa são atômicas
|
|
205
|
+
(``_state_lock``), então um worker atrasado nunca sobrescreve um player
|
|
206
|
+
mais novo.
|
|
207
|
+
|
|
208
|
+
Attributes:
|
|
209
|
+
AUDIO_EXTENSIONS: Extensões de arquivo reconhecidas como mídia
|
|
210
|
+
(áudio e vídeo, usadas nos seletores e ao carregar pastas).
|
|
211
|
+
VIDEO_EXTENSIONS: Subconjunto de extensões que contêm vídeo.
|
|
212
|
+
REPEAT_OFF: Sem repetição.
|
|
213
|
+
REPEAT_ONE: Repetir faixa atual.
|
|
214
|
+
REPEAT_ALL: Repetir playlist inteira.
|
|
215
|
+
"""
|
|
216
|
+
|
|
217
|
+
AUDIO_EXTENSIONS: frozenset = frozenset(
|
|
218
|
+
{
|
|
219
|
+
".mp3",
|
|
220
|
+
".flac",
|
|
221
|
+
".wav",
|
|
222
|
+
".m4a",
|
|
223
|
+
".ogg",
|
|
224
|
+
".aac",
|
|
225
|
+
".wma",
|
|
226
|
+
".opus",
|
|
227
|
+
".mp4",
|
|
228
|
+
".mkv",
|
|
229
|
+
".webm",
|
|
230
|
+
".avi",
|
|
231
|
+
".mov",
|
|
232
|
+
".wmv",
|
|
233
|
+
".flv",
|
|
234
|
+
".m4v",
|
|
235
|
+
".ts",
|
|
236
|
+
".3gp",
|
|
237
|
+
}
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
VIDEO_EXTENSIONS: frozenset = frozenset(
|
|
241
|
+
{
|
|
242
|
+
".mp4",
|
|
243
|
+
".mkv",
|
|
244
|
+
".webm",
|
|
245
|
+
".avi",
|
|
246
|
+
".mov",
|
|
247
|
+
".wmv",
|
|
248
|
+
".flv",
|
|
249
|
+
".m4v",
|
|
250
|
+
".ts",
|
|
251
|
+
".3gp",
|
|
252
|
+
}
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
REPEAT_OFF = "off"
|
|
256
|
+
REPEAT_ONE = "one"
|
|
257
|
+
REPEAT_ALL = "all"
|
|
258
|
+
|
|
259
|
+
def __init__(self, tk_root: tk.Misc | None = None) -> None:
|
|
260
|
+
"""Inicializa o motor sem carregar nenhuma biblioteca de mídia.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
tk_root: Janela raiz do Tkinter para agendamento de callbacks.
|
|
264
|
+
Se ``None``, tenta detectar automaticamente.
|
|
265
|
+
"""
|
|
266
|
+
self._tk_root: tk.Misc | None = tk_root
|
|
267
|
+
self._playlist: list[dict[str, str]] = []
|
|
268
|
+
self._play_order: list[int] = []
|
|
269
|
+
self._order_idx: int = 0
|
|
270
|
+
self._idx: int = 0
|
|
271
|
+
self._playing: bool = False
|
|
272
|
+
self._paused: bool = False
|
|
273
|
+
self._loading: bool = False
|
|
274
|
+
self._duration: float = 0.0
|
|
275
|
+
self._position: float = 0.0
|
|
276
|
+
self._volume: int = 70
|
|
277
|
+
self._player_instance: Any = None
|
|
278
|
+
self._player_type: str | None = None
|
|
279
|
+
self._stop_ev: threading.Event = threading.Event()
|
|
280
|
+
self._listeners: dict[str, dict[Any, Callable]] = {
|
|
281
|
+
"change": {}, "progress": {}, "state": {},
|
|
282
|
+
}
|
|
283
|
+
self._on_change_cb: Callable | None = lambda: self._fanout("change")
|
|
284
|
+
self._on_progress_cb: Callable | None = (
|
|
285
|
+
lambda pos, dur: self._fanout("progress", pos, dur)
|
|
286
|
+
)
|
|
287
|
+
self._on_state_cb: Callable | None = (
|
|
288
|
+
lambda playing, paused, loading: self._fanout(
|
|
289
|
+
"state", playing, paused, loading)
|
|
290
|
+
)
|
|
291
|
+
self._shuffle: bool = False
|
|
292
|
+
self._repeat: str = self.REPEAT_OFF
|
|
293
|
+
self._gen: int = 0
|
|
294
|
+
self._ytdlp: bool = (
|
|
295
|
+
shutil.which(
|
|
296
|
+
"yt-dlp") is not None or shutil.which("youtube-dl") is not None
|
|
297
|
+
)
|
|
298
|
+
self._available: bool = MPV_AVAILABLE or VLC_AVAILABLE
|
|
299
|
+
self._video_wid: int | None = None
|
|
300
|
+
self._active_video_wid: int | None = None
|
|
301
|
+
self._video_job: str | None = None
|
|
302
|
+
self._eq_gains: list[float] = clamp_gains(None)
|
|
303
|
+
self._eq_enabled: bool = True
|
|
304
|
+
self._state_lock = threading.Lock()
|
|
305
|
+
self._backend_lock = threading.Lock()
|
|
306
|
+
self._ctl_lock = threading.Lock()
|
|
307
|
+
self._isolated: bool = os.environ.get("CODIS_MEDIA_INPROC") != "1"
|
|
308
|
+
self._host: MediaHostClient | None = None
|
|
309
|
+
self._host_lock = threading.Lock()
|
|
310
|
+
self._seeked_at: float = 0.0
|
|
311
|
+
self._retired: list[_Retired] = []
|
|
312
|
+
self._poll_thread: threading.Thread | None = None
|
|
313
|
+
self._instance_wid: int | None = None
|
|
314
|
+
self._pending_ops: int = 0
|
|
315
|
+
self._surface_lock = threading.Lock()
|
|
316
|
+
self._surface_busy: dict[int, int] = {}
|
|
317
|
+
self._surface_waiters: dict[int, list[Callable[[], None]]] = {}
|
|
318
|
+
|
|
319
|
+
@classmethod
|
|
320
|
+
def is_video_url(cls, url: str) -> bool:
|
|
321
|
+
"""Indica se *url* aponta para um vídeo (extensão conhecida ou YouTube)."""
|
|
322
|
+
if not url:
|
|
323
|
+
return False
|
|
324
|
+
if _is_youtube(url):
|
|
325
|
+
return True
|
|
326
|
+
path = urlparse(url).path if "://" in url else url
|
|
327
|
+
return Path(path).suffix.lower() in cls.VIDEO_EXTENSIONS
|
|
328
|
+
|
|
329
|
+
@property
|
|
330
|
+
def current_is_video(self) -> bool:
|
|
331
|
+
"""``True`` se a faixa selecionada é um vídeo."""
|
|
332
|
+
return self.is_video_url(self.current_url)
|
|
333
|
+
|
|
334
|
+
@property
|
|
335
|
+
def video_surface(self) -> int | None:
|
|
336
|
+
"""Id nativo da superfície onde o vídeo é desenhado, se houver."""
|
|
337
|
+
return self._video_wid
|
|
338
|
+
|
|
339
|
+
def set_video_surface(self, wid: int | None) -> None:
|
|
340
|
+
"""Define a janela nativa (``winfo_id`` de um ``tk.Frame``) que recebe o vídeo.
|
|
341
|
+
|
|
342
|
+
Com ``None`` os vídeos tocam só o áudio. Se a faixa em reprodução precisa
|
|
343
|
+
de outra saída, ela é reiniciada na posição atual (ver :meth:`_sync_video`).
|
|
344
|
+
"""
|
|
345
|
+
if wid == self._video_wid:
|
|
346
|
+
return
|
|
347
|
+
self._video_wid = wid
|
|
348
|
+
self._schedule_video_sync()
|
|
349
|
+
|
|
350
|
+
def release_video_surface(
|
|
351
|
+
self, wid: int | None, on_released: Callable[[], None] | None = None
|
|
352
|
+
) -> None:
|
|
353
|
+
"""Remove a superfície *wid*; ignora se outra já a substituiu.
|
|
354
|
+
|
|
355
|
+
Args:
|
|
356
|
+
wid: Superfície que deixa de existir para o motor.
|
|
357
|
+
on_released: Chamado na thread da interface quando nenhum backend
|
|
358
|
+
desenha mais em *wid* (na hora, se já for o caso). É o
|
|
359
|
+
momento seguro de destruir a janela nativa.
|
|
360
|
+
"""
|
|
361
|
+
if wid is not None and wid == self._video_wid:
|
|
362
|
+
self.set_video_surface(None)
|
|
363
|
+
if on_released is None:
|
|
364
|
+
return
|
|
365
|
+
if wid is not None:
|
|
366
|
+
with self._surface_lock:
|
|
367
|
+
if self._surface_busy.get(wid, 0) > 0:
|
|
368
|
+
self._surface_waiters.setdefault(wid, []).append(on_released)
|
|
369
|
+
return
|
|
370
|
+
on_released()
|
|
371
|
+
|
|
372
|
+
def _surface_add(self, wid: int | None) -> None:
|
|
373
|
+
"""Marca *wid* como em uso por mais um backend (criado ou em criação)."""
|
|
374
|
+
if wid is None:
|
|
375
|
+
return
|
|
376
|
+
with self._surface_lock:
|
|
377
|
+
self._surface_busy[wid] = self._surface_busy.get(wid, 0) + 1
|
|
378
|
+
|
|
379
|
+
def _surface_done(self, wid: int | None) -> None:
|
|
380
|
+
"""Libera um uso de *wid*; ao zerar, avisa quem espera para destruí-la."""
|
|
381
|
+
if wid is None:
|
|
382
|
+
return
|
|
383
|
+
with self._surface_lock:
|
|
384
|
+
left = self._surface_busy.get(wid, 0) - 1
|
|
385
|
+
if left > 0:
|
|
386
|
+
self._surface_busy[wid] = left
|
|
387
|
+
return
|
|
388
|
+
self._surface_busy.pop(wid, None)
|
|
389
|
+
waiters = self._surface_waiters.pop(wid, [])
|
|
390
|
+
for callback in waiters:
|
|
391
|
+
try:
|
|
392
|
+
self._schedule(callback)
|
|
393
|
+
except Exception:
|
|
394
|
+
logger.exception("não foi possível agendar a liberação da superfície")
|
|
395
|
+
|
|
396
|
+
def _video_orphaned(self) -> bool:
|
|
397
|
+
"""``True`` se a instância ativa desenha numa superfície que já foi trocada.
|
|
398
|
+
|
|
399
|
+
Nesse caso o backend pode encerrar sozinho ao perder a janela, e esse
|
|
400
|
+
encerramento não deve ser tratado como fim de faixa.
|
|
401
|
+
"""
|
|
402
|
+
active = self._active_video_wid
|
|
403
|
+
return active is not None and active != self._video_wid
|
|
404
|
+
|
|
405
|
+
def _schedule_video_sync(self) -> None:
|
|
406
|
+
"""Agrupa mudanças seguidas de superfície (ex.: encaixar/destacar) em uma só."""
|
|
407
|
+
root = self._get_tk_root()
|
|
408
|
+
if root is None:
|
|
409
|
+
self._sync_video()
|
|
410
|
+
return
|
|
411
|
+
if self._video_job is not None:
|
|
412
|
+
with contextlib.suppress(tk.TclError, ValueError):
|
|
413
|
+
root.after_cancel(self._video_job)
|
|
414
|
+
try:
|
|
415
|
+
self._video_job = root.after(120, self._sync_video)
|
|
416
|
+
except tk.TclError:
|
|
417
|
+
self._video_job = None
|
|
418
|
+
|
|
419
|
+
def _sync_video(self) -> None:
|
|
420
|
+
"""Reinicia a faixa atual se a saída de vídeo em uso não é a desejada."""
|
|
421
|
+
self._video_job = None
|
|
422
|
+
if not self._playing or not self._playlist:
|
|
423
|
+
return
|
|
424
|
+
wanted = self._video_wid if self.is_video_url(self.current_url) else None
|
|
425
|
+
if wanted == self._active_video_wid:
|
|
426
|
+
return
|
|
427
|
+
self.play(start=self._position, paused=self._paused)
|
|
428
|
+
|
|
429
|
+
def set_equalizer(
|
|
430
|
+
self, gains: list[float] | None = None, enabled: bool | None = None
|
|
431
|
+
) -> None:
|
|
432
|
+
"""Define ganhos (±12 dB, 10 bandas) e/ou liga/desliga o equalizador.
|
|
433
|
+
|
|
434
|
+
A mudança é aplicada imediatamente à faixa em reprodução e reaplicada
|
|
435
|
+
automaticamente a cada nova faixa.
|
|
436
|
+
"""
|
|
437
|
+
if gains is not None:
|
|
438
|
+
self._eq_gains = clamp_gains(gains)
|
|
439
|
+
if enabled is not None:
|
|
440
|
+
self._eq_enabled = bool(enabled)
|
|
441
|
+
with self._live_backend() as (instance, kind):
|
|
442
|
+
self._apply_eq_to(instance, kind)
|
|
443
|
+
|
|
444
|
+
@property
|
|
445
|
+
def eq_gains(self) -> list[float]:
|
|
446
|
+
"""Ganhos atuais do equalizador (cópia)."""
|
|
447
|
+
return list(self._eq_gains)
|
|
448
|
+
|
|
449
|
+
@property
|
|
450
|
+
def eq_enabled(self) -> bool:
|
|
451
|
+
"""Se o equalizador está ativo."""
|
|
452
|
+
return self._eq_enabled
|
|
453
|
+
|
|
454
|
+
def _apply_eq_to(self, instance: Any, kind: str | None) -> None:
|
|
455
|
+
"""Aplica o equalizador a uma instância mpv/VLC (falhas são ignoradas)."""
|
|
456
|
+
if instance is None or kind is None:
|
|
457
|
+
return
|
|
458
|
+
if kind == "mpv":
|
|
459
|
+
chain = mpv_af_string(self._eq_gains) if self._eq_enabled else ""
|
|
460
|
+
try:
|
|
461
|
+
instance.af = chain
|
|
462
|
+
except (AttributeError, RuntimeError, TypeError, OSError, SystemError) as exc:
|
|
463
|
+
logger.debug("mpv af: %s", exc)
|
|
464
|
+
elif kind == "remote":
|
|
465
|
+
instance.equalizer(self._eq_gains, self._eq_enabled)
|
|
466
|
+
elif kind == "vlc":
|
|
467
|
+
apply_vlc_equalizer(instance, self._eq_gains, self._eq_enabled)
|
|
468
|
+
|
|
469
|
+
def set_playlist(self, playlist: list) -> None:
|
|
470
|
+
"""Define a playlist completa, substituindo a anterior.
|
|
471
|
+
|
|
472
|
+
Args:
|
|
473
|
+
playlist: Lista de entradas aceitas por :func:`_parse_entry`.
|
|
474
|
+
"""
|
|
475
|
+
self._playlist = [_parse_entry(e) for e in playlist if e]
|
|
476
|
+
self._idx = 0
|
|
477
|
+
self._rebuild_order()
|
|
478
|
+
self._notify_change()
|
|
479
|
+
|
|
480
|
+
def add_track(self, name: str, url: str) -> None:
|
|
481
|
+
"""Adiciona uma faixa ao final da playlist.
|
|
482
|
+
|
|
483
|
+
Args:
|
|
484
|
+
name: Nome exibido na interface.
|
|
485
|
+
url: Caminho local ou URL da faixa.
|
|
486
|
+
"""
|
|
487
|
+
self._playlist.append({"name": name, "url": url})
|
|
488
|
+
self._rebuild_order()
|
|
489
|
+
self._notify_change()
|
|
490
|
+
|
|
491
|
+
def remove_track(self, idx: int) -> None:
|
|
492
|
+
"""Remove a faixa no índice *idx* da playlist.
|
|
493
|
+
|
|
494
|
+
Args:
|
|
495
|
+
idx: Índice (base 0) da faixa a remover.
|
|
496
|
+
"""
|
|
497
|
+
if 0 <= idx < len(self._playlist):
|
|
498
|
+
self._playlist.pop(idx)
|
|
499
|
+
self._idx = max(0, min(self._idx, len(self._playlist) - 1))
|
|
500
|
+
self._rebuild_order()
|
|
501
|
+
self._notify_change()
|
|
502
|
+
|
|
503
|
+
def load_folder(self, folder_path: str) -> None:
|
|
504
|
+
"""Adiciona à playlist os arquivos de mídia de uma pasta (recursivo).
|
|
505
|
+
|
|
506
|
+
Somente extensões em :attr:`AUDIO_EXTENSIONS` são incluídas.
|
|
507
|
+
Os arquivos são ordenados alfabeticamente.
|
|
508
|
+
|
|
509
|
+
Args:
|
|
510
|
+
folder_path: Caminho absoluto da pasta raiz.
|
|
511
|
+
"""
|
|
512
|
+
arquivos: list[str] = []
|
|
513
|
+
for root, _dirs, fnames in os.walk(folder_path):
|
|
514
|
+
for f in fnames:
|
|
515
|
+
if Path(f).suffix.lower() in self.AUDIO_EXTENSIONS:
|
|
516
|
+
arquivos.append(os.path.join(root, f))
|
|
517
|
+
arquivos.sort()
|
|
518
|
+
if not arquivos:
|
|
519
|
+
return
|
|
520
|
+
for f in arquivos:
|
|
521
|
+
self._playlist.append(
|
|
522
|
+
{
|
|
523
|
+
"name": os.path.relpath(f, folder_path),
|
|
524
|
+
"url": f,
|
|
525
|
+
}
|
|
526
|
+
)
|
|
527
|
+
self._rebuild_order()
|
|
528
|
+
self._notify_change()
|
|
529
|
+
|
|
530
|
+
def _rebuild_order(self) -> None:
|
|
531
|
+
"""Reconstrói a ordem de reprodução conforme o modo shuffle.
|
|
532
|
+
|
|
533
|
+
No modo shuffle a faixa atual fica como primeiro item da nova ordem.
|
|
534
|
+
"""
|
|
535
|
+
n = len(self._playlist)
|
|
536
|
+
if n == 0:
|
|
537
|
+
self._play_order = []
|
|
538
|
+
self._order_idx = 0
|
|
539
|
+
return
|
|
540
|
+
if self._shuffle:
|
|
541
|
+
indices = list(range(n))
|
|
542
|
+
if self._idx in indices:
|
|
543
|
+
indices.remove(self._idx)
|
|
544
|
+
random.shuffle(indices)
|
|
545
|
+
self._play_order = [self._idx] + indices
|
|
546
|
+
else:
|
|
547
|
+
random.shuffle(indices)
|
|
548
|
+
self._play_order = indices
|
|
549
|
+
else:
|
|
550
|
+
self._play_order = list(range(n))
|
|
551
|
+
with contextlib.suppress(ValueError):
|
|
552
|
+
self._order_idx = self._play_order.index(self._idx)
|
|
553
|
+
|
|
554
|
+
def play(self, start: float = 0.0, paused: bool = False) -> None:
|
|
555
|
+
"""Inicia a reprodução da faixa atual sem bloquear a interface.
|
|
556
|
+
|
|
557
|
+
O backend anterior é encerrado e o novo criado numa thread worker.
|
|
558
|
+
|
|
559
|
+
Args:
|
|
560
|
+
start: Posição inicial em segundos (usada ao reiniciar a faixa
|
|
561
|
+
para trocar a saída de vídeo).
|
|
562
|
+
paused: Se ``True``, a faixa começa pausada.
|
|
563
|
+
"""
|
|
564
|
+
if not self._playlist:
|
|
565
|
+
return
|
|
566
|
+
if not self._available:
|
|
567
|
+
self._playing = False
|
|
568
|
+
self._loading = False
|
|
569
|
+
self._notify_state()
|
|
570
|
+
self._notify_change()
|
|
571
|
+
return
|
|
572
|
+
|
|
573
|
+
with self._state_lock:
|
|
574
|
+
self._gen += 1
|
|
575
|
+
gen = self._gen
|
|
576
|
+
|
|
577
|
+
entry = self._playlist[self._idx]
|
|
578
|
+
url = entry["url"]
|
|
579
|
+
if not url:
|
|
580
|
+
return
|
|
581
|
+
|
|
582
|
+
self._playing = True
|
|
583
|
+
self._paused = paused
|
|
584
|
+
self._loading = True
|
|
585
|
+
self._position = start
|
|
586
|
+
self._duration = 0.0
|
|
587
|
+
self._notify_state()
|
|
588
|
+
self._notify_change()
|
|
589
|
+
|
|
590
|
+
# Lido depois de notificar: a interface registra a superfície ao reagir
|
|
591
|
+
# à troca de faixa.
|
|
592
|
+
video_wid = self._video_wid if self.is_video_url(url) else None
|
|
593
|
+
self._active_video_wid = video_wid
|
|
594
|
+
self._surface_add(video_wid)
|
|
595
|
+
|
|
596
|
+
with self._state_lock:
|
|
597
|
+
self._retire_current()
|
|
598
|
+
stop_ev = self._stop_ev
|
|
599
|
+
|
|
600
|
+
def _worker() -> None:
|
|
601
|
+
with self._backend_lock:
|
|
602
|
+
self._drain_retired()
|
|
603
|
+
if gen != self._gen:
|
|
604
|
+
self._surface_done(video_wid)
|
|
605
|
+
return
|
|
606
|
+
if self._isolated:
|
|
607
|
+
self._spawn_remote(url, gen, video_wid, start, paused)
|
|
608
|
+
elif MPV_AVAILABLE:
|
|
609
|
+
self._spawn_mpv(url, gen, video_wid, start, paused, stop_ev)
|
|
610
|
+
elif VLC_AVAILABLE:
|
|
611
|
+
self._spawn_vlc(url, gen, video_wid, start, paused, stop_ev)
|
|
612
|
+
else:
|
|
613
|
+
self._surface_done(video_wid)
|
|
614
|
+
self._schedule_if(gen, self._cleanup_player)
|
|
615
|
+
|
|
616
|
+
self._start_backend_thread(_worker, "CodisMediaWorker")
|
|
617
|
+
|
|
618
|
+
def stop(self) -> None:
|
|
619
|
+
"""Para a reprodução completamente de forma não-bloqueante."""
|
|
620
|
+
with self._state_lock:
|
|
621
|
+
self._gen += 1
|
|
622
|
+
retired = self._retire_current()
|
|
623
|
+
self._playing = False
|
|
624
|
+
self._paused = False
|
|
625
|
+
self._loading = False
|
|
626
|
+
self._position = 0.0
|
|
627
|
+
self._active_video_wid = None
|
|
628
|
+
|
|
629
|
+
if retired:
|
|
630
|
+
self._start_backend_thread(self._drain_locked, "CodisMediaStop")
|
|
631
|
+
|
|
632
|
+
self._notify_change()
|
|
633
|
+
self._notify_state()
|
|
634
|
+
|
|
635
|
+
def shutdown(self, timeout: float = 3.0) -> None:
|
|
636
|
+
"""Para a reprodução e espera o backend terminar, para encerrar o app.
|
|
637
|
+
|
|
638
|
+
Diferente de :meth:`stop`, só volta depois de o backend largar a janela
|
|
639
|
+
de vídeo, que o app destrói em seguida. A espera acontece com o laço do
|
|
640
|
+
Tk girando: o VLC cria a janela de vídeo como filha da superfície e pode
|
|
641
|
+
precisar que a thread principal atenda mensagens enquanto para.
|
|
642
|
+
|
|
643
|
+
Args:
|
|
644
|
+
timeout: Tempo máximo de espera, em segundos.
|
|
645
|
+
"""
|
|
646
|
+
self.stop()
|
|
647
|
+
root = self._get_tk_root()
|
|
648
|
+
deadline = time.monotonic() + timeout
|
|
649
|
+
try:
|
|
650
|
+
while self._pending_ops > 0:
|
|
651
|
+
if time.monotonic() >= deadline:
|
|
652
|
+
logger.warning("o backend de mídia não parou em %.1fs", timeout)
|
|
653
|
+
return
|
|
654
|
+
if root is not None:
|
|
655
|
+
with contextlib.suppress(tk.TclError):
|
|
656
|
+
root.update()
|
|
657
|
+
time.sleep(0.01)
|
|
658
|
+
finally:
|
|
659
|
+
self._close_host()
|
|
660
|
+
|
|
661
|
+
def _start_backend_thread(self, target: Callable[[], None], name: str) -> None:
|
|
662
|
+
"""Roda *target* numa thread daemon contada em ``_pending_ops``."""
|
|
663
|
+
with self._state_lock:
|
|
664
|
+
self._pending_ops += 1
|
|
665
|
+
|
|
666
|
+
def _run() -> None:
|
|
667
|
+
try:
|
|
668
|
+
target()
|
|
669
|
+
except Exception:
|
|
670
|
+
logger.exception("operação de backend falhou")
|
|
671
|
+
finally:
|
|
672
|
+
with self._state_lock:
|
|
673
|
+
self._pending_ops -= 1
|
|
674
|
+
|
|
675
|
+
threading.Thread(target=_run, daemon=True, name=name).start()
|
|
676
|
+
|
|
677
|
+
def _retire_current(self) -> bool:
|
|
678
|
+
"""Desanexa o backend ativo para ser encerrado (``_state_lock`` tomado).
|
|
679
|
+
|
|
680
|
+
Returns:
|
|
681
|
+
``True`` se havia um backend criado; um ainda em criação se
|
|
682
|
+
descarta sozinho ao ver que a geração mudou.
|
|
683
|
+
"""
|
|
684
|
+
had_instance = self._player_instance is not None
|
|
685
|
+
if had_instance:
|
|
686
|
+
self._retired.append(
|
|
687
|
+
_Retired(
|
|
688
|
+
self._player_instance,
|
|
689
|
+
self._player_type,
|
|
690
|
+
self._stop_ev,
|
|
691
|
+
self._poll_thread,
|
|
692
|
+
self._instance_wid,
|
|
693
|
+
self._seeked_at,
|
|
694
|
+
)
|
|
695
|
+
)
|
|
696
|
+
self._player_instance = None
|
|
697
|
+
self._player_type = None
|
|
698
|
+
self._poll_thread = None
|
|
699
|
+
self._instance_wid = None
|
|
700
|
+
self._stop_ev = threading.Event()
|
|
701
|
+
return had_instance
|
|
702
|
+
|
|
703
|
+
def _drain_retired(self) -> None:
|
|
704
|
+
"""Encerra os backends desanexados, um por vez (``_backend_lock`` tomado)."""
|
|
705
|
+
while True:
|
|
706
|
+
with self._state_lock:
|
|
707
|
+
if not self._retired:
|
|
708
|
+
return
|
|
709
|
+
item = self._retired.pop(0)
|
|
710
|
+
try:
|
|
711
|
+
with self._ctl_lock:
|
|
712
|
+
_stop_instance_bg(
|
|
713
|
+
item.instance,
|
|
714
|
+
item.kind,
|
|
715
|
+
item.stop_ev,
|
|
716
|
+
item.poll,
|
|
717
|
+
seeked_at=item.seeked_at,
|
|
718
|
+
)
|
|
719
|
+
finally:
|
|
720
|
+
self._surface_done(item.wid)
|
|
721
|
+
|
|
722
|
+
@contextlib.contextmanager
|
|
723
|
+
def _live_backend(self):
|
|
724
|
+
"""Dá acesso exclusivo ao backend ativo para um comando de controle.
|
|
725
|
+
|
|
726
|
+
O encerramento de um backend desanexado toma o mesmo ``_ctl_lock``, então
|
|
727
|
+
busca, pausa e volume nunca correm junto com ``stop``/``release`` do
|
|
728
|
+
libvlc, que derrubam o processo quando se cruzam. Se o encerramento
|
|
729
|
+
estiver em curso, o comando é descartado: o backend já foi retirado.
|
|
730
|
+
|
|
731
|
+
Yields:
|
|
732
|
+
Tupla ``(instância, tipo)``; ``(None, None)`` sem backend utilizável.
|
|
733
|
+
"""
|
|
734
|
+
if not self._ctl_lock.acquire(blocking=False):
|
|
735
|
+
yield None, None
|
|
736
|
+
return
|
|
737
|
+
try:
|
|
738
|
+
with self._state_lock:
|
|
739
|
+
current = (self._player_instance, self._player_type)
|
|
740
|
+
yield current
|
|
741
|
+
finally:
|
|
742
|
+
self._ctl_lock.release()
|
|
743
|
+
|
|
744
|
+
def _drain_locked(self) -> None:
|
|
745
|
+
with self._backend_lock:
|
|
746
|
+
self._drain_retired()
|
|
747
|
+
|
|
748
|
+
def _adopt(
|
|
749
|
+
self,
|
|
750
|
+
gen: int,
|
|
751
|
+
player: Any,
|
|
752
|
+
kind: str,
|
|
753
|
+
wid: int | None,
|
|
754
|
+
poll: threading.Thread | None = None,
|
|
755
|
+
) -> bool:
|
|
756
|
+
"""Torna *player* o backend ativo, se a geração ainda for *gen*.
|
|
757
|
+
|
|
758
|
+
Returns:
|
|
759
|
+
``False`` se outra faixa já assumiu; quem chamou deve encerrar o player.
|
|
760
|
+
"""
|
|
761
|
+
with self._state_lock:
|
|
762
|
+
if gen != self._gen:
|
|
763
|
+
return False
|
|
764
|
+
self._player_instance = player
|
|
765
|
+
self._player_type = kind
|
|
766
|
+
self._instance_wid = wid
|
|
767
|
+
self._poll_thread = poll
|
|
768
|
+
self._seeked_at = 0.0
|
|
769
|
+
self._loading = False
|
|
770
|
+
return True
|
|
771
|
+
|
|
772
|
+
def toggle_pause(self) -> None:
|
|
773
|
+
"""Alterna entre pause e play.
|
|
774
|
+
|
|
775
|
+
Se o player não estiver tocando, inicia a reprodução da faixa atual.
|
|
776
|
+
"""
|
|
777
|
+
if not self._playing:
|
|
778
|
+
self.play()
|
|
779
|
+
return
|
|
780
|
+
with self._live_backend() as (instance, kind):
|
|
781
|
+
if instance is None:
|
|
782
|
+
return
|
|
783
|
+
self._paused = not self._paused
|
|
784
|
+
if kind == "mpv":
|
|
785
|
+
with contextlib.suppress(tk.TclError):
|
|
786
|
+
instance.pause = self._paused
|
|
787
|
+
elif kind == "remote":
|
|
788
|
+
instance.pause(self._paused)
|
|
789
|
+
elif kind == "vlc":
|
|
790
|
+
with contextlib.suppress(tk.TclError):
|
|
791
|
+
if self._paused:
|
|
792
|
+
instance.pause()
|
|
793
|
+
else:
|
|
794
|
+
instance.play()
|
|
795
|
+
self._notify_state()
|
|
796
|
+
self._notify_change()
|
|
797
|
+
|
|
798
|
+
def play_index(self, idx: int) -> None:
|
|
799
|
+
"""Salta diretamente para a faixa no índice absoluto *idx*.
|
|
800
|
+
|
|
801
|
+
Args:
|
|
802
|
+
idx: Índice (base 0) na playlist original.
|
|
803
|
+
"""
|
|
804
|
+
if not (0 <= idx < len(self._playlist)):
|
|
805
|
+
return
|
|
806
|
+
self._idx = idx
|
|
807
|
+
with contextlib.suppress(ValueError):
|
|
808
|
+
self._order_idx = self._play_order.index(idx)
|
|
809
|
+
self.play()
|
|
810
|
+
|
|
811
|
+
def next(self) -> None:
|
|
812
|
+
"""Avança para a próxima faixa na ordem de reprodução.
|
|
813
|
+
|
|
814
|
+
``REPEAT_ONE`` reinicia a faixa atual; ``REPEAT_OFF`` para ao final.
|
|
815
|
+
"""
|
|
816
|
+
if not self._playlist:
|
|
817
|
+
return
|
|
818
|
+
if self._repeat == self.REPEAT_ONE:
|
|
819
|
+
if self._playing:
|
|
820
|
+
self.play()
|
|
821
|
+
return
|
|
822
|
+
n = len(self._play_order)
|
|
823
|
+
if n == 0:
|
|
824
|
+
return
|
|
825
|
+
self._order_idx = (self._order_idx + 1) % n
|
|
826
|
+
if self._order_idx == 0 and self._repeat == self.REPEAT_OFF and n > 1:
|
|
827
|
+
self.stop()
|
|
828
|
+
return
|
|
829
|
+
self._idx = self._play_order[self._order_idx]
|
|
830
|
+
if self._playing:
|
|
831
|
+
self.play()
|
|
832
|
+
else:
|
|
833
|
+
self._notify_change()
|
|
834
|
+
|
|
835
|
+
def prev(self) -> None:
|
|
836
|
+
"""Volta para a faixa anterior.
|
|
837
|
+
|
|
838
|
+
Se a posição atual for maior que 3 s, reinicia a faixa atual.
|
|
839
|
+
"""
|
|
840
|
+
if not self._playlist:
|
|
841
|
+
return
|
|
842
|
+
if self._position > 3.0:
|
|
843
|
+
self.seek(0.0)
|
|
844
|
+
return
|
|
845
|
+
n = len(self._play_order)
|
|
846
|
+
if n == 0:
|
|
847
|
+
return
|
|
848
|
+
self._order_idx = (self._order_idx - 1) % n
|
|
849
|
+
self._idx = self._play_order[self._order_idx]
|
|
850
|
+
if self._playing:
|
|
851
|
+
self.play()
|
|
852
|
+
else:
|
|
853
|
+
self._notify_change()
|
|
854
|
+
|
|
855
|
+
def seek(self, position: float) -> None:
|
|
856
|
+
"""Busca a posição *position* (em segundos) na faixa atual.
|
|
857
|
+
|
|
858
|
+
Args:
|
|
859
|
+
position: Posição destino em segundos.
|
|
860
|
+
"""
|
|
861
|
+
with self._live_backend() as (instance, kind):
|
|
862
|
+
if instance is None:
|
|
863
|
+
return
|
|
864
|
+
with contextlib.suppress(tk.TclError):
|
|
865
|
+
if kind == "mpv":
|
|
866
|
+
instance.seek(position, reference="absolute")
|
|
867
|
+
elif kind == "remote":
|
|
868
|
+
instance.seek(position)
|
|
869
|
+
elif kind == "vlc":
|
|
870
|
+
if _vlc_is_opening(instance):
|
|
871
|
+
return
|
|
872
|
+
self._seeked_at = time.monotonic()
|
|
873
|
+
instance.set_time(int(position * 1000))
|
|
874
|
+
self._position = position
|
|
875
|
+
|
|
876
|
+
def set_volume(self, volume: int) -> None:
|
|
877
|
+
"""Define o volume de reprodução (0-100).
|
|
878
|
+
|
|
879
|
+
Args:
|
|
880
|
+
volume: Novo volume.
|
|
881
|
+
"""
|
|
882
|
+
self._volume = int(_clamp(volume, 0, 100))
|
|
883
|
+
with self._live_backend() as (instance, kind):
|
|
884
|
+
if instance is None:
|
|
885
|
+
return
|
|
886
|
+
with contextlib.suppress(tk.TclError):
|
|
887
|
+
if kind == "mpv":
|
|
888
|
+
instance.volume = self._volume
|
|
889
|
+
elif kind == "remote":
|
|
890
|
+
instance.volume(self._volume)
|
|
891
|
+
elif kind == "vlc":
|
|
892
|
+
instance.audio_set_volume(self._volume)
|
|
893
|
+
|
|
894
|
+
def set_shuffle(self, enabled: bool) -> None:
|
|
895
|
+
"""Ativa ou desativa o modo aleatório.
|
|
896
|
+
|
|
897
|
+
Args:
|
|
898
|
+
enabled: ``True`` para ativar.
|
|
899
|
+
"""
|
|
900
|
+
self._shuffle = enabled
|
|
901
|
+
self._rebuild_order()
|
|
902
|
+
self._notify_change()
|
|
903
|
+
|
|
904
|
+
def set_repeat(self, mode: str) -> None:
|
|
905
|
+
"""Define o modo de repetição.
|
|
906
|
+
|
|
907
|
+
Args:
|
|
908
|
+
mode: Um de :attr:`REPEAT_OFF`, :attr:`REPEAT_ONE` ou :attr:`REPEAT_ALL`.
|
|
909
|
+
"""
|
|
910
|
+
if mode in (self.REPEAT_OFF, self.REPEAT_ONE, self.REPEAT_ALL):
|
|
911
|
+
self._repeat = mode
|
|
912
|
+
|
|
913
|
+
def on_change(self, cb: Callable) -> None:
|
|
914
|
+
"""Registra callback chamado quando a faixa atual muda (sem args).
|
|
915
|
+
|
|
916
|
+
Args:
|
|
917
|
+
cb: Função chamável sem argumentos.
|
|
918
|
+
"""
|
|
919
|
+
self._listeners["change"][self._owner_key(cb)] = cb
|
|
920
|
+
|
|
921
|
+
def on_progress(self, cb: Callable) -> None:
|
|
922
|
+
"""Registra callback de progresso: ``cb(posicao: float, duracao: float)``.
|
|
923
|
+
|
|
924
|
+
Args:
|
|
925
|
+
cb: Função chamável com dois floats.
|
|
926
|
+
"""
|
|
927
|
+
self._listeners["progress"][self._owner_key(cb)] = cb
|
|
928
|
+
|
|
929
|
+
def on_state(self, cb: Callable) -> None:
|
|
930
|
+
"""Registra callback de estado: ``cb(tocando, pausado, carregando)``.
|
|
931
|
+
|
|
932
|
+
Args:
|
|
933
|
+
cb: Função chamável com três booleanos.
|
|
934
|
+
"""
|
|
935
|
+
self._listeners["state"][self._owner_key(cb)] = cb
|
|
936
|
+
|
|
937
|
+
@staticmethod
|
|
938
|
+
def _owner_key(cb: Callable) -> Any:
|
|
939
|
+
"""Chave do ouvinte: o objeto dono do método (ou o próprio callable)."""
|
|
940
|
+
return id(getattr(cb, "__self__", cb))
|
|
941
|
+
|
|
942
|
+
def add_listener(
|
|
943
|
+
self,
|
|
944
|
+
owner: object,
|
|
945
|
+
change: Callable | None = None,
|
|
946
|
+
progress: Callable | None = None,
|
|
947
|
+
state: Callable | None = None,
|
|
948
|
+
) -> None:
|
|
949
|
+
"""Registra ouvintes de ``owner`` (substitui os anteriores do mesmo dono)."""
|
|
950
|
+
key = id(owner)
|
|
951
|
+
for kind, cb in (("change", change), ("progress", progress), ("state", state)):
|
|
952
|
+
if cb is not None:
|
|
953
|
+
self._listeners[kind][key] = cb
|
|
954
|
+
|
|
955
|
+
def remove_listener(self, owner: object) -> None:
|
|
956
|
+
"""Remove todos os ouvintes registrados por ``owner``."""
|
|
957
|
+
key = id(owner)
|
|
958
|
+
for table in self._listeners.values():
|
|
959
|
+
table.pop(key, None)
|
|
960
|
+
|
|
961
|
+
def _fanout(self, kind: str, *args: Any) -> None:
|
|
962
|
+
"""Chama todos os ouvintes de ``kind`` isolando falhas individuais."""
|
|
963
|
+
for cb in list(self._listeners[kind].values()):
|
|
964
|
+
try:
|
|
965
|
+
cb(*args)
|
|
966
|
+
except tk.TclError:
|
|
967
|
+
continue
|
|
968
|
+
except Exception:
|
|
969
|
+
logger.exception("ouvinte de %s falhou", kind)
|
|
970
|
+
|
|
971
|
+
def _ensure_host(self) -> MediaHostClient | None:
|
|
972
|
+
"""Devolve o processo de mídia, subindo um novo se não houver um vivo."""
|
|
973
|
+
with self._host_lock:
|
|
974
|
+
host = self._host
|
|
975
|
+
if host is not None and host.alive:
|
|
976
|
+
return host
|
|
977
|
+
host = MediaHostClient(self._on_host_event, self._on_host_exit)
|
|
978
|
+
if not host.start():
|
|
979
|
+
return None
|
|
980
|
+
self._host = host
|
|
981
|
+
return host
|
|
982
|
+
|
|
983
|
+
def _close_host(self) -> None:
|
|
984
|
+
"""Encerra o processo de mídia, se houver.
|
|
985
|
+
|
|
986
|
+
O laço do Tk continua girando durante a espera: a janela de vídeo do
|
|
987
|
+
filho é filha da superfície do Codis e pode precisar de mensagens da
|
|
988
|
+
thread principal ao fechar.
|
|
989
|
+
"""
|
|
990
|
+
with self._host_lock:
|
|
991
|
+
host, self._host = self._host, None
|
|
992
|
+
if host is None:
|
|
993
|
+
return
|
|
994
|
+
closer = threading.Thread(target=host.close, daemon=True, name="CodisMediaClose")
|
|
995
|
+
closer.start()
|
|
996
|
+
root = self._get_tk_root()
|
|
997
|
+
deadline = time.monotonic() + HOST_QUIT_WAIT + 1.0
|
|
998
|
+
while closer.is_alive() and time.monotonic() < deadline:
|
|
999
|
+
if root is not None:
|
|
1000
|
+
with contextlib.suppress(tk.TclError):
|
|
1001
|
+
root.update()
|
|
1002
|
+
time.sleep(0.01)
|
|
1003
|
+
|
|
1004
|
+
def _spawn_remote(
|
|
1005
|
+
self,
|
|
1006
|
+
url: str,
|
|
1007
|
+
gen: int,
|
|
1008
|
+
video_wid: int | None,
|
|
1009
|
+
start: float,
|
|
1010
|
+
paused: bool,
|
|
1011
|
+
) -> None:
|
|
1012
|
+
"""Pede ao processo de mídia que toque *url* (``_backend_lock`` tomado).
|
|
1013
|
+
|
|
1014
|
+
Args:
|
|
1015
|
+
url: URL ou caminho local a reproduzir.
|
|
1016
|
+
gen: Geração de reprodução no momento do início.
|
|
1017
|
+
video_wid: Superfície que recebe o vídeo; ``None`` toca só o áudio.
|
|
1018
|
+
start: Posição inicial em segundos.
|
|
1019
|
+
paused: Se ``True``, começa pausado.
|
|
1020
|
+
"""
|
|
1021
|
+
remote: RemotePlayback | None = None
|
|
1022
|
+
sent = False
|
|
1023
|
+
adopted = False
|
|
1024
|
+
try:
|
|
1025
|
+
host = self._ensure_host()
|
|
1026
|
+
if host is None:
|
|
1027
|
+
raise RuntimeError("o processo de mídia não iniciou")
|
|
1028
|
+
if gen != self._gen:
|
|
1029
|
+
return
|
|
1030
|
+
remote = RemotePlayback(host, gen)
|
|
1031
|
+
sent = host.send(
|
|
1032
|
+
cmd="play",
|
|
1033
|
+
id=gen,
|
|
1034
|
+
url=url,
|
|
1035
|
+
wid=video_wid,
|
|
1036
|
+
start=start,
|
|
1037
|
+
paused=paused,
|
|
1038
|
+
volume=self._volume,
|
|
1039
|
+
gains=self._eq_gains,
|
|
1040
|
+
enabled=self._eq_enabled,
|
|
1041
|
+
ytdlp=self._ytdlp,
|
|
1042
|
+
)
|
|
1043
|
+
if not sent:
|
|
1044
|
+
raise RuntimeError("o processo de mídia não aceitou o comando")
|
|
1045
|
+
adopted = self._adopt(gen, remote, "remote", video_wid)
|
|
1046
|
+
if adopted:
|
|
1047
|
+
if not host.alive:
|
|
1048
|
+
self._on_host_exit(host, None)
|
|
1049
|
+
else:
|
|
1050
|
+
self._schedule(self._notify_state)
|
|
1051
|
+
except Exception as exc:
|
|
1052
|
+
logger.error("reprodução falhou: %s", exc)
|
|
1053
|
+
if gen == self._gen:
|
|
1054
|
+
self._schedule(self._cleanup_player)
|
|
1055
|
+
finally:
|
|
1056
|
+
if not adopted:
|
|
1057
|
+
if sent and remote is not None:
|
|
1058
|
+
remote.stop()
|
|
1059
|
+
self._surface_done(video_wid)
|
|
1060
|
+
|
|
1061
|
+
def _on_host_event(self, event: dict[str, Any]) -> None:
|
|
1062
|
+
"""Trata um evento do processo de mídia (thread leitora do canal)."""
|
|
1063
|
+
play_id = event.get("id")
|
|
1064
|
+
if play_id != self._gen:
|
|
1065
|
+
return
|
|
1066
|
+
kind = event.get("ev")
|
|
1067
|
+
if kind == "pos":
|
|
1068
|
+
position = float(event.get("pos") or 0.0)
|
|
1069
|
+
duration = float(event.get("dur") or 0.0)
|
|
1070
|
+
if position > 0:
|
|
1071
|
+
self._position = position
|
|
1072
|
+
if duration > 0:
|
|
1073
|
+
self._duration = duration
|
|
1074
|
+
if self._on_progress_cb and position > 0:
|
|
1075
|
+
self._schedule(self._on_progress_cb, self._position, self._duration)
|
|
1076
|
+
elif kind == "paused":
|
|
1077
|
+
self._paused = bool(event.get("value"))
|
|
1078
|
+
self._schedule(self._notify_state)
|
|
1079
|
+
elif kind == "ended":
|
|
1080
|
+
if self._playing and not self._video_orphaned():
|
|
1081
|
+
self._schedule(self.next)
|
|
1082
|
+
elif kind == "error":
|
|
1083
|
+
logger.error("o processo de mídia não tocou a faixa: %s", event.get("msg"))
|
|
1084
|
+
self._schedule_if(play_id, self._cleanup_player)
|
|
1085
|
+
|
|
1086
|
+
def _on_host_exit(self, host: MediaHostClient, _code: int | None) -> None:
|
|
1087
|
+
"""O processo de mídia caiu: a reprodução ativa nele é dada por encerrada.
|
|
1088
|
+
|
|
1089
|
+
Se a queda aconteceu durante o encerramento de uma faixa antiga, o worker
|
|
1090
|
+
segue e sobe um processo novo para a faixa pedida; nada muda aqui.
|
|
1091
|
+
"""
|
|
1092
|
+
with self._state_lock:
|
|
1093
|
+
current = self._player_instance
|
|
1094
|
+
mine = isinstance(current, RemotePlayback) and current.host is host
|
|
1095
|
+
if mine:
|
|
1096
|
+
self._gen += 1
|
|
1097
|
+
self._retire_current()
|
|
1098
|
+
self._playing = False
|
|
1099
|
+
self._paused = False
|
|
1100
|
+
self._loading = False
|
|
1101
|
+
self._position = 0.0
|
|
1102
|
+
self._active_video_wid = None
|
|
1103
|
+
if not mine:
|
|
1104
|
+
return
|
|
1105
|
+
self._start_backend_thread(self._drain_locked, "CodisMediaStop")
|
|
1106
|
+
self._schedule(self._notify_state)
|
|
1107
|
+
self._schedule(self._notify_change)
|
|
1108
|
+
|
|
1109
|
+
def _spawn_mpv(
|
|
1110
|
+
self,
|
|
1111
|
+
url: str,
|
|
1112
|
+
gen: int,
|
|
1113
|
+
video_wid: int | None,
|
|
1114
|
+
start: float,
|
|
1115
|
+
paused: bool,
|
|
1116
|
+
stop_ev: threading.Event,
|
|
1117
|
+
) -> None:
|
|
1118
|
+
"""Cria o player do python-mpv e começa a tocar (``_backend_lock`` tomado).
|
|
1119
|
+
|
|
1120
|
+
Callbacks de gerações antigas são descartados silenciosamente.
|
|
1121
|
+
|
|
1122
|
+
Args:
|
|
1123
|
+
url: URL ou caminho local a reproduzir.
|
|
1124
|
+
gen: Geração de reprodução no momento do início.
|
|
1125
|
+
video_wid: Superfície que recebe o vídeo; ``None`` toca só o áudio.
|
|
1126
|
+
start: Posição inicial em segundos.
|
|
1127
|
+
paused: Se ``True``, começa pausado.
|
|
1128
|
+
stop_ev: Evento sinalizado quando este player for encerrado.
|
|
1129
|
+
"""
|
|
1130
|
+
player = None
|
|
1131
|
+
adopted = False
|
|
1132
|
+
try:
|
|
1133
|
+
import locale
|
|
1134
|
+
|
|
1135
|
+
with contextlib.suppress(tk.TclError):
|
|
1136
|
+
locale.setlocale(locale.LC_NUMERIC, "C")
|
|
1137
|
+
use_video = "auto" if video_wid is not None else "no"
|
|
1138
|
+
mpv_kwargs: dict = {
|
|
1139
|
+
"ytdl": self._ytdlp,
|
|
1140
|
+
"video": use_video,
|
|
1141
|
+
"input_default_bindings": False,
|
|
1142
|
+
"input_vo_keyboard": False,
|
|
1143
|
+
"osc": False,
|
|
1144
|
+
"log_handler": lambda lv, c, m: logger.debug("[mpv/%s] %s", c, m),
|
|
1145
|
+
"loglevel": "error",
|
|
1146
|
+
}
|
|
1147
|
+
if video_wid is not None:
|
|
1148
|
+
mpv_kwargs["wid"] = str(video_wid)
|
|
1149
|
+
if self._ytdlp and _is_youtube(url):
|
|
1150
|
+
mpv_kwargs["ytdl_format"] = "bestvideo[height<=?1080]+bestaudio/best"
|
|
1151
|
+
forced_ao = os.environ.get("CODIS_MEDIA_AO")
|
|
1152
|
+
if forced_ao:
|
|
1153
|
+
mpv_kwargs["ao"] = forced_ao
|
|
1154
|
+
player = mpv.MPV(**mpv_kwargs)
|
|
1155
|
+
|
|
1156
|
+
@player.property_observer("time-pos")
|
|
1157
|
+
def _tp(_n, v):
|
|
1158
|
+
if v is not None and gen == self._gen:
|
|
1159
|
+
self._position = v
|
|
1160
|
+
if self._on_progress_cb:
|
|
1161
|
+
self._schedule(
|
|
1162
|
+
self._on_progress_cb, self._position, self._duration
|
|
1163
|
+
)
|
|
1164
|
+
|
|
1165
|
+
@player.property_observer("duration")
|
|
1166
|
+
def _dur(_n, v):
|
|
1167
|
+
if v is not None and gen == self._gen:
|
|
1168
|
+
self._duration = v
|
|
1169
|
+
if self._on_progress_cb:
|
|
1170
|
+
self._schedule(
|
|
1171
|
+
self._on_progress_cb, self._position, self._duration
|
|
1172
|
+
)
|
|
1173
|
+
|
|
1174
|
+
@player.property_observer("pause")
|
|
1175
|
+
def _pse(_n, v):
|
|
1176
|
+
if v is not None and gen == self._gen:
|
|
1177
|
+
self._paused = bool(v)
|
|
1178
|
+
self._schedule(self._notify_state)
|
|
1179
|
+
|
|
1180
|
+
@player.event_callback("end-file")
|
|
1181
|
+
def _eof(_ev):
|
|
1182
|
+
if (
|
|
1183
|
+
gen == self._gen
|
|
1184
|
+
and self._playing
|
|
1185
|
+
and not stop_ev.is_set()
|
|
1186
|
+
and not self._video_orphaned()
|
|
1187
|
+
):
|
|
1188
|
+
self._schedule(self.next)
|
|
1189
|
+
|
|
1190
|
+
if gen != self._gen:
|
|
1191
|
+
return
|
|
1192
|
+
|
|
1193
|
+
with contextlib.suppress(tk.TclError):
|
|
1194
|
+
player.volume = self._volume
|
|
1195
|
+
self._apply_eq_to(player, "mpv")
|
|
1196
|
+
if start > 0:
|
|
1197
|
+
with contextlib.suppress(AttributeError, RuntimeError, TypeError, OSError):
|
|
1198
|
+
player.start = f"{start:.3f}"
|
|
1199
|
+
if paused:
|
|
1200
|
+
with contextlib.suppress(AttributeError, RuntimeError, TypeError, OSError):
|
|
1201
|
+
player.pause = True
|
|
1202
|
+
player.play(url)
|
|
1203
|
+
adopted = self._adopt(gen, player, "mpv", video_wid)
|
|
1204
|
+
if adopted:
|
|
1205
|
+
self._schedule(self._notify_state)
|
|
1206
|
+
except Exception as exc:
|
|
1207
|
+
logger.exception("mpv falhou: %s", exc)
|
|
1208
|
+
if gen == self._gen:
|
|
1209
|
+
self._schedule(self._cleanup_player)
|
|
1210
|
+
finally:
|
|
1211
|
+
if not adopted:
|
|
1212
|
+
if player is not None:
|
|
1213
|
+
_stop_instance_bg(player, "mpv", stop_ev)
|
|
1214
|
+
self._surface_done(video_wid)
|
|
1215
|
+
|
|
1216
|
+
def _spawn_vlc(
|
|
1217
|
+
self,
|
|
1218
|
+
url: str,
|
|
1219
|
+
gen: int,
|
|
1220
|
+
video_wid: int | None,
|
|
1221
|
+
start: float,
|
|
1222
|
+
paused: bool,
|
|
1223
|
+
stop_ev: threading.Event,
|
|
1224
|
+
) -> None:
|
|
1225
|
+
"""Cria o player do python-vlc e começa a tocar (``_backend_lock`` tomado).
|
|
1226
|
+
|
|
1227
|
+
Uma thread de polling acompanha posição e fim da faixa e só dispara
|
|
1228
|
+
callbacks enquanto a geração for a mesma.
|
|
1229
|
+
|
|
1230
|
+
Args:
|
|
1231
|
+
url: URL ou caminho local a reproduzir.
|
|
1232
|
+
gen: Geração de reprodução no momento do início.
|
|
1233
|
+
video_wid: Superfície que recebe o vídeo; ``None`` toca só o áudio.
|
|
1234
|
+
start: Posição inicial em segundos.
|
|
1235
|
+
paused: Se ``True``, começa pausado.
|
|
1236
|
+
stop_ev: Evento sinalizado quando este player for encerrado.
|
|
1237
|
+
"""
|
|
1238
|
+
player = None
|
|
1239
|
+
started = False
|
|
1240
|
+
adopted = False
|
|
1241
|
+
try:
|
|
1242
|
+
vlc_flags = ["--quiet"]
|
|
1243
|
+
if video_wid is None:
|
|
1244
|
+
vlc_flags += ["--no-video", "--no-xlib"]
|
|
1245
|
+
instancia = vlc.Instance(*vlc_flags) # pylint: disable=no-member
|
|
1246
|
+
player = instancia.media_player_new()
|
|
1247
|
+
if video_wid is not None:
|
|
1248
|
+
with contextlib.suppress(AttributeError, RuntimeError):
|
|
1249
|
+
if sys.platform == "win32":
|
|
1250
|
+
player.set_hwnd(video_wid)
|
|
1251
|
+
elif sys.platform == "darwin":
|
|
1252
|
+
player.set_nsobject(video_wid)
|
|
1253
|
+
else:
|
|
1254
|
+
player.set_xwindow(video_wid)
|
|
1255
|
+
media = instancia.media_new(url)
|
|
1256
|
+
if _is_youtube(url):
|
|
1257
|
+
media.add_option(":network-caching=1500")
|
|
1258
|
+
if start > 0:
|
|
1259
|
+
media.add_option(f":start-time={start:.3f}")
|
|
1260
|
+
player.set_media(media)
|
|
1261
|
+
with contextlib.suppress(AttributeError, RuntimeError):
|
|
1262
|
+
media.release()
|
|
1263
|
+
with contextlib.suppress(AttributeError, RuntimeError):
|
|
1264
|
+
player.audio_set_volume(self._volume)
|
|
1265
|
+
self._apply_eq_to(player, "vlc")
|
|
1266
|
+
|
|
1267
|
+
if gen != self._gen:
|
|
1268
|
+
return
|
|
1269
|
+
player.play()
|
|
1270
|
+
started = True
|
|
1271
|
+
if paused:
|
|
1272
|
+
with contextlib.suppress(AttributeError, RuntimeError):
|
|
1273
|
+
player.set_pause(1)
|
|
1274
|
+
|
|
1275
|
+
poll = threading.Thread(
|
|
1276
|
+
target=self._vlc_poll_loop,
|
|
1277
|
+
args=(gen, player, stop_ev),
|
|
1278
|
+
daemon=True,
|
|
1279
|
+
name="CodisVLCPoll",
|
|
1280
|
+
)
|
|
1281
|
+
adopted = self._adopt(gen, player, "vlc", video_wid, poll)
|
|
1282
|
+
if adopted:
|
|
1283
|
+
poll.start()
|
|
1284
|
+
self._schedule(self._notify_state)
|
|
1285
|
+
except Exception as exc:
|
|
1286
|
+
logger.exception("VLC falhou: %s", exc)
|
|
1287
|
+
if gen == self._gen:
|
|
1288
|
+
self._schedule(self._cleanup_player)
|
|
1289
|
+
finally:
|
|
1290
|
+
if not adopted:
|
|
1291
|
+
if player is not None:
|
|
1292
|
+
_stop_instance_bg(player, "vlc", stop_ev, settle=started)
|
|
1293
|
+
self._surface_done(video_wid)
|
|
1294
|
+
|
|
1295
|
+
def _vlc_poll_loop(
|
|
1296
|
+
self, gen: int, player: Any, stop_ev: threading.Event
|
|
1297
|
+
) -> None:
|
|
1298
|
+
"""Acompanha posição, duração e fim da faixa do VLC em segundo plano.
|
|
1299
|
+
|
|
1300
|
+
Termina quando *stop_ev* é sinalizado ou a geração muda. O encerramento
|
|
1301
|
+
do player espera esta thread acabar antes de liberá-lo.
|
|
1302
|
+
|
|
1303
|
+
Args:
|
|
1304
|
+
gen: Geração de reprodução que originou este loop.
|
|
1305
|
+
player: ``MediaPlayer`` do VLC a consultar.
|
|
1306
|
+
stop_ev: Evento sinalizado ao encerrar este player.
|
|
1307
|
+
"""
|
|
1308
|
+
while not stop_ev.wait(0.4):
|
|
1309
|
+
if gen != self._gen:
|
|
1310
|
+
break
|
|
1311
|
+
with contextlib.suppress(tk.TclError):
|
|
1312
|
+
pos = player.get_time() / 1000.0
|
|
1313
|
+
dur = player.get_length() / 1000.0
|
|
1314
|
+
if pos > 0:
|
|
1315
|
+
self._position = pos
|
|
1316
|
+
if dur > 0:
|
|
1317
|
+
self._duration = dur
|
|
1318
|
+
if self._on_progress_cb and pos > 0 and gen == self._gen:
|
|
1319
|
+
self._schedule(self._on_progress_cb,
|
|
1320
|
+
self._position, self._duration)
|
|
1321
|
+
if player.get_state() in (
|
|
1322
|
+
vlc.State.Ended,
|
|
1323
|
+
vlc.State.Error,
|
|
1324
|
+
): # pylint: disable=no-member
|
|
1325
|
+
if (
|
|
1326
|
+
gen == self._gen
|
|
1327
|
+
and self._playing
|
|
1328
|
+
and not stop_ev.is_set()
|
|
1329
|
+
and not self._video_orphaned()
|
|
1330
|
+
):
|
|
1331
|
+
self._schedule(self.next)
|
|
1332
|
+
break
|
|
1333
|
+
|
|
1334
|
+
def _schedule(self, callback: Callable, *args) -> None:
|
|
1335
|
+
"""Agenda *callback* na thread principal do Tkinter via ``after(0)``.
|
|
1336
|
+
|
|
1337
|
+
Args:
|
|
1338
|
+
callback: Função a agendar.
|
|
1339
|
+
*args: Argumentos posicionais passados ao callback.
|
|
1340
|
+
"""
|
|
1341
|
+
root = self._get_tk_root()
|
|
1342
|
+
if root is not None:
|
|
1343
|
+
with contextlib.suppress(tk.TclError):
|
|
1344
|
+
root.after(0, lambda: callback(*args))
|
|
1345
|
+
return
|
|
1346
|
+
with contextlib.suppress(tk.TclError):
|
|
1347
|
+
callback(*args)
|
|
1348
|
+
|
|
1349
|
+
def _schedule_if(self, gen: int, callback: Callable, *args) -> None:
|
|
1350
|
+
"""Agenda *callback* somente se a geração atual ainda for *gen*.
|
|
1351
|
+
|
|
1352
|
+
Args:
|
|
1353
|
+
gen: Geração esperada.
|
|
1354
|
+
callback: Função a agendar.
|
|
1355
|
+
*args: Argumentos posicionais.
|
|
1356
|
+
"""
|
|
1357
|
+
|
|
1358
|
+
def _guarded():
|
|
1359
|
+
if gen == self._gen:
|
|
1360
|
+
callback(*args)
|
|
1361
|
+
|
|
1362
|
+
root = self._get_tk_root()
|
|
1363
|
+
if root is not None:
|
|
1364
|
+
with contextlib.suppress(tk.TclError):
|
|
1365
|
+
root.after(0, _guarded)
|
|
1366
|
+
return
|
|
1367
|
+
with contextlib.suppress(tk.TclError):
|
|
1368
|
+
_guarded()
|
|
1369
|
+
|
|
1370
|
+
def _get_tk_root(self) -> tk.Misc | None:
|
|
1371
|
+
"""Retorna a janela raiz do Tkinter ou ``None``."""
|
|
1372
|
+
if self._tk_root is not None:
|
|
1373
|
+
return self._tk_root
|
|
1374
|
+
return getattr(tk, "_default_root", None)
|
|
1375
|
+
|
|
1376
|
+
def _cleanup_player(self) -> None:
|
|
1377
|
+
"""Limpa o estado após erro de inicialização do backend."""
|
|
1378
|
+
self._loading = False
|
|
1379
|
+
self._playing = False
|
|
1380
|
+
self._paused = False
|
|
1381
|
+
self._player_instance = None
|
|
1382
|
+
self._active_video_wid = None
|
|
1383
|
+
self._notify_state()
|
|
1384
|
+
self._notify_change()
|
|
1385
|
+
|
|
1386
|
+
def _notify_change(self) -> None:
|
|
1387
|
+
"""Dispara o callback de mudança de faixa, se registrado."""
|
|
1388
|
+
if self._on_change_cb:
|
|
1389
|
+
with contextlib.suppress(tk.TclError):
|
|
1390
|
+
self._on_change_cb()
|
|
1391
|
+
|
|
1392
|
+
def _notify_state(self) -> None:
|
|
1393
|
+
"""Dispara o callback de estado, se registrado."""
|
|
1394
|
+
if self._on_state_cb:
|
|
1395
|
+
with contextlib.suppress(tk.TclError):
|
|
1396
|
+
self._on_state_cb(self._playing, self._paused, self._loading)
|
|
1397
|
+
|
|
1398
|
+
@property
|
|
1399
|
+
def current_track(self) -> str:
|
|
1400
|
+
"""Nome da faixa atualmente selecionada, ou ``"Sem playlist"``."""
|
|
1401
|
+
return self._playlist[self._idx]["name"] if self._playlist else "Sem playlist"
|
|
1402
|
+
|
|
1403
|
+
@property
|
|
1404
|
+
def current_url(self) -> str:
|
|
1405
|
+
"""URL/caminho da faixa atualmente selecionada."""
|
|
1406
|
+
return self._playlist[self._idx]["url"] if self._playlist else ""
|
|
1407
|
+
|
|
1408
|
+
@property
|
|
1409
|
+
def playlist(self) -> list[dict[str, str]]:
|
|
1410
|
+
"""Cópia da lista de entradas da playlist (somente leitura)."""
|
|
1411
|
+
return list(self._playlist)
|
|
1412
|
+
|
|
1413
|
+
@property
|
|
1414
|
+
def is_playing(self) -> bool:
|
|
1415
|
+
"""``True`` se o player estiver em modo de reprodução ativa."""
|
|
1416
|
+
return self._playing
|
|
1417
|
+
|
|
1418
|
+
@property
|
|
1419
|
+
def is_paused(self) -> bool:
|
|
1420
|
+
"""``True`` se a reprodução estiver pausada."""
|
|
1421
|
+
return self._paused
|
|
1422
|
+
|
|
1423
|
+
@property
|
|
1424
|
+
def is_loading(self) -> bool:
|
|
1425
|
+
"""``True`` se o backend ainda estiver carregando a mídia."""
|
|
1426
|
+
return self._loading
|
|
1427
|
+
|
|
1428
|
+
@property
|
|
1429
|
+
def track_count(self) -> int:
|
|
1430
|
+
"""Número de faixas na playlist."""
|
|
1431
|
+
return len(self._playlist)
|
|
1432
|
+
|
|
1433
|
+
@property
|
|
1434
|
+
def current_index(self) -> int:
|
|
1435
|
+
"""Índice (base 0) da faixa atualmente selecionada."""
|
|
1436
|
+
return self._idx
|
|
1437
|
+
|
|
1438
|
+
@property
|
|
1439
|
+
def position(self) -> float:
|
|
1440
|
+
"""Posição atual de reprodução em segundos."""
|
|
1441
|
+
return self._position
|
|
1442
|
+
|
|
1443
|
+
@property
|
|
1444
|
+
def duration(self) -> float:
|
|
1445
|
+
"""Duração total da faixa atual em segundos (0 enquanto carrega)."""
|
|
1446
|
+
return self._duration
|
|
1447
|
+
|
|
1448
|
+
@property
|
|
1449
|
+
def volume(self) -> int:
|
|
1450
|
+
"""Volume atual (0-100)."""
|
|
1451
|
+
return self._volume
|
|
1452
|
+
|
|
1453
|
+
@property
|
|
1454
|
+
def shuffle(self) -> bool:
|
|
1455
|
+
"""``True`` se o modo aleatório estiver ativado."""
|
|
1456
|
+
return self._shuffle
|
|
1457
|
+
|
|
1458
|
+
@property
|
|
1459
|
+
def repeat(self) -> str:
|
|
1460
|
+
"""Modo de repetição: ``"off"``, ``"one"`` ou ``"all"``."""
|
|
1461
|
+
return self._repeat
|
|
1462
|
+
|
|
1463
|
+
@property
|
|
1464
|
+
def has_player(self) -> bool:
|
|
1465
|
+
"""``True`` se pelo menos um backend (mpv ou vlc) estiver disponível."""
|
|
1466
|
+
return self._available
|
|
1467
|
+
|
|
1468
|
+
|
|
1469
|
+
def _stop_instance_bg(
|
|
1470
|
+
instance: Any,
|
|
1471
|
+
player_type: str | None,
|
|
1472
|
+
stop_ev: threading.Event,
|
|
1473
|
+
poll: threading.Thread | None = None,
|
|
1474
|
+
settle: bool = True,
|
|
1475
|
+
seeked_at: float = 0.0,
|
|
1476
|
+
) -> None:
|
|
1477
|
+
"""Encerra uma instância de backend; chamada fora da thread da interface.
|
|
1478
|
+
|
|
1479
|
+
Sinaliza *stop_ev* (que encerra o polling do VLC) e então para o backend.
|
|
1480
|
+
|
|
1481
|
+
Args:
|
|
1482
|
+
instance: Instância MPV ou VLC a encerrar (pode ser ``None``).
|
|
1483
|
+
player_type: ``"mpv"`` ou ``"vlc"`` (pode ser ``None``).
|
|
1484
|
+
stop_ev: Evento de parada associado ao backend.
|
|
1485
|
+
poll: Thread de polling do VLC, esperada antes de liberar o player.
|
|
1486
|
+
settle: No VLC, espera a mídia terminar de abrir antes de parar.
|
|
1487
|
+
seeked_at: Instante (``time.monotonic``) da última busca no VLC; o
|
|
1488
|
+
encerramento espera esse trabalho assentar.
|
|
1489
|
+
"""
|
|
1490
|
+
stop_ev.set()
|
|
1491
|
+
if instance is None:
|
|
1492
|
+
return
|
|
1493
|
+
if player_type == "mpv":
|
|
1494
|
+
with contextlib.suppress(tk.TclError, OSError, RuntimeError):
|
|
1495
|
+
instance.terminate()
|
|
1496
|
+
elif player_type == "remote":
|
|
1497
|
+
instance.stop()
|
|
1498
|
+
elif player_type == "vlc":
|
|
1499
|
+
_stop_vlc(instance, poll, settle, seeked_at)
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
def _vlc_opening_states() -> set:
|
|
1503
|
+
"""Estados do VLC em que a mídia ainda abre ou o buffer se refaz."""
|
|
1504
|
+
return {
|
|
1505
|
+
getattr(vlc.State, name, None) # pylint: disable=no-member
|
|
1506
|
+
for name in ("NothingSpecial", "Opening", "Buffering")
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def _vlc_is_opening(player: Any) -> bool:
|
|
1511
|
+
"""``True`` se o *player* ainda abre a mídia (busca e parada ficam inseguras)."""
|
|
1512
|
+
try:
|
|
1513
|
+
return player.get_state() in _vlc_opening_states()
|
|
1514
|
+
except (AttributeError, OSError, RuntimeError):
|
|
1515
|
+
return False
|
|
1516
|
+
|
|
1517
|
+
|
|
1518
|
+
def _stop_vlc(
|
|
1519
|
+
player: Any,
|
|
1520
|
+
poll: threading.Thread | None,
|
|
1521
|
+
settle: bool,
|
|
1522
|
+
seeked_at: float = 0.0,
|
|
1523
|
+
) -> None:
|
|
1524
|
+
"""Para e libera um ``MediaPlayer`` do VLC.
|
|
1525
|
+
|
|
1526
|
+
Parar o player enquanto a mídia abre, o buffer se refaz ou uma busca ainda
|
|
1527
|
+
está em andamento derruba o libvlc no Windows (violação de acesso dentro de
|
|
1528
|
+
``libvlc_media_player_stop``). Por isso espera-se a saída desses estados e
|
|
1529
|
+
um intervalo mínimo desde a última busca (*seeked_at*). A
|
|
1530
|
+
thread de polling precisa terminar por completo antes de parar/liberar o
|
|
1531
|
+
player; um timeout permitiria que ela ainda estivesse dentro de uma chamada
|
|
1532
|
+
nativa quando o objeto fosse destruído.
|
|
1533
|
+
"""
|
|
1534
|
+
if poll is not None and poll is not threading.current_thread():
|
|
1535
|
+
poll.join()
|
|
1536
|
+
if settle:
|
|
1537
|
+
opening = _vlc_opening_states()
|
|
1538
|
+
state = None
|
|
1539
|
+
deadline = time.monotonic() + _VLC_OPEN_WAIT
|
|
1540
|
+
while time.monotonic() < deadline:
|
|
1541
|
+
try:
|
|
1542
|
+
state = player.get_state()
|
|
1543
|
+
except (AttributeError, OSError, RuntimeError):
|
|
1544
|
+
break
|
|
1545
|
+
seek_pending = time.monotonic() - seeked_at < _VLC_SEEK_SETTLE
|
|
1546
|
+
if state not in opening and not seek_pending:
|
|
1547
|
+
break
|
|
1548
|
+
time.sleep(0.05)
|
|
1549
|
+
else:
|
|
1550
|
+
logger.warning("VLC parado sem assentar (estado: %s)", state)
|
|
1551
|
+
with contextlib.suppress(AttributeError, OSError, RuntimeError):
|
|
1552
|
+
player.stop()
|
|
1553
|
+
owner = None
|
|
1554
|
+
with contextlib.suppress(AttributeError, OSError, RuntimeError):
|
|
1555
|
+
owner = player.get_instance()
|
|
1556
|
+
with contextlib.suppress(AttributeError, OSError, RuntimeError):
|
|
1557
|
+
player.release()
|
|
1558
|
+
if owner is not None:
|
|
1559
|
+
with contextlib.suppress(AttributeError, OSError, RuntimeError):
|
|
1560
|
+
owner.release()
|
|
1561
|
+
|
|
1562
|
+
|
|
1563
|
+
class ZenPlaylistPopup:
|
|
1564
|
+
"""Popup leve exibido ao clicar ☰ no HUD para listar e selecionar faixas.
|
|
1565
|
+
|
|
1566
|
+
É um ``tk.Toplevel`` filho do HUD, sem decoração de janela.
|
|
1567
|
+
A faixa atual aparece destacada; clique em qualquer faixa a reproduz.
|
|
1568
|
+
Fecha com Escape ou clicando fora da lista.
|
|
1569
|
+
|
|
1570
|
+
Args:
|
|
1571
|
+
anchor: Widget âncora (botão ☰) para posicionamento.
|
|
1572
|
+
player: Instância de :class:`ZenMediaPlayer` a controlar.
|
|
1573
|
+
bg: Cor de fundo.
|
|
1574
|
+
fg: Cor do texto.
|
|
1575
|
+
fg_dim: Cor do texto secundário.
|
|
1576
|
+
accent: Cor de destaque para a faixa atual.
|
|
1577
|
+
"""
|
|
1578
|
+
|
|
1579
|
+
_MAX_VISIBLE = 12
|
|
1580
|
+
|
|
1581
|
+
def __init__(
|
|
1582
|
+
self,
|
|
1583
|
+
anchor: tk.Widget,
|
|
1584
|
+
player: ZenMediaPlayer,
|
|
1585
|
+
bg: str,
|
|
1586
|
+
fg: str,
|
|
1587
|
+
fg_dim: str,
|
|
1588
|
+
accent: str,
|
|
1589
|
+
) -> None:
|
|
1590
|
+
self._player = player
|
|
1591
|
+
self._destroyed = False
|
|
1592
|
+
|
|
1593
|
+
root = anchor.winfo_toplevel()
|
|
1594
|
+
self._win = tk.Toplevel(root)
|
|
1595
|
+
self._win.overrideredirect(True)
|
|
1596
|
+
self._win.configure(bg=accent)
|
|
1597
|
+
self._win.attributes("-topmost", True)
|
|
1598
|
+
|
|
1599
|
+
self._bg = bg
|
|
1600
|
+
self._fg = fg
|
|
1601
|
+
self._fg_dim = fg_dim
|
|
1602
|
+
self._accent = accent
|
|
1603
|
+
|
|
1604
|
+
self._build(anchor)
|
|
1605
|
+
self._win.bind("<Escape>", lambda _: self._fechar())
|
|
1606
|
+
self._win.bind("<FocusOut>", self._on_focus_out)
|
|
1607
|
+
self._win.focus_set()
|
|
1608
|
+
|
|
1609
|
+
def _build(self, anchor: tk.Widget) -> None:
|
|
1610
|
+
"""Constrói a lista e posiciona acima do botão âncora.
|
|
1611
|
+
|
|
1612
|
+
Args:
|
|
1613
|
+
anchor: Widget de referência para o posicionamento.
|
|
1614
|
+
"""
|
|
1615
|
+
inner = tk.Frame(self._win, bg=self._bg)
|
|
1616
|
+
inner.pack(fill="both", expand=True, padx=1, pady=1)
|
|
1617
|
+
|
|
1618
|
+
cab = tk.Frame(inner, bg=self._bg)
|
|
1619
|
+
cab.pack(fill="x", padx=6, pady=(5, 3))
|
|
1620
|
+
tk.Label(
|
|
1621
|
+
cab,
|
|
1622
|
+
text=_t("hc.zen_media.playlist"),
|
|
1623
|
+
bg=self._bg,
|
|
1624
|
+
fg=self._fg,
|
|
1625
|
+
font=("Segoe UI", 9, "bold"),
|
|
1626
|
+
).pack(side="left")
|
|
1627
|
+
tk.Button(
|
|
1628
|
+
cab,
|
|
1629
|
+
text="✕",
|
|
1630
|
+
bg=self._bg,
|
|
1631
|
+
fg=self._fg_dim,
|
|
1632
|
+
relief="flat",
|
|
1633
|
+
bd=0,
|
|
1634
|
+
font=("Segoe UI", 8),
|
|
1635
|
+
cursor="hand2",
|
|
1636
|
+
command=self._fechar,
|
|
1637
|
+
).pack(side="right")
|
|
1638
|
+
|
|
1639
|
+
n_vis = min(len(self._player._playlist), self._MAX_VISIBLE)
|
|
1640
|
+
frame_lista = tk.Frame(inner, bg=self._bg)
|
|
1641
|
+
frame_lista.pack(fill="both", expand=True, padx=4, pady=(0, 4))
|
|
1642
|
+
|
|
1643
|
+
sb = tk.Scrollbar(frame_lista, orient="vertical")
|
|
1644
|
+
self._lb = tk.Listbox(
|
|
1645
|
+
frame_lista,
|
|
1646
|
+
bg=self._bg,
|
|
1647
|
+
fg=self._fg,
|
|
1648
|
+
selectbackground=self._accent,
|
|
1649
|
+
selectforeground=self._bg,
|
|
1650
|
+
font=("Segoe UI", 9),
|
|
1651
|
+
relief="flat",
|
|
1652
|
+
bd=0,
|
|
1653
|
+
highlightthickness=0,
|
|
1654
|
+
activestyle="none",
|
|
1655
|
+
height=max(3, n_vis),
|
|
1656
|
+
yscrollcommand=sb.set,
|
|
1657
|
+
)
|
|
1658
|
+
sb.config(command=self._lb.yview)
|
|
1659
|
+
sb.pack(side="right", fill="y")
|
|
1660
|
+
self._lb.pack(side="left", fill="both", expand=True)
|
|
1661
|
+
|
|
1662
|
+
current = self._player.current_index
|
|
1663
|
+
for i, entry in enumerate(self._player._playlist):
|
|
1664
|
+
prefix = "▶ " if i == current else " "
|
|
1665
|
+
name = entry["name"]
|
|
1666
|
+
if len(name) > 40:
|
|
1667
|
+
name = name[:38] + "..."
|
|
1668
|
+
self._lb.insert("end", f"{prefix}{name}")
|
|
1669
|
+
if i == current:
|
|
1670
|
+
self._lb.itemconfig(i, fg=self._accent)
|
|
1671
|
+
|
|
1672
|
+
if 0 <= current < self._lb.size():
|
|
1673
|
+
self._lb.see(current)
|
|
1674
|
+
self._lb.selection_set(current)
|
|
1675
|
+
|
|
1676
|
+
self._lb.bind("<Button-1>", self._on_click)
|
|
1677
|
+
self._lb.bind("<Double-Button-1>", self._on_click)
|
|
1678
|
+
self._lb.bind("<Return>", self._on_enter)
|
|
1679
|
+
|
|
1680
|
+
self._win.update_idletasks()
|
|
1681
|
+
ax = anchor.winfo_rootx()
|
|
1682
|
+
ay = anchor.winfo_rooty()
|
|
1683
|
+
pw = self._win.winfo_reqwidth()
|
|
1684
|
+
ph = self._win.winfo_reqheight()
|
|
1685
|
+
sw = anchor.winfo_screenwidth()
|
|
1686
|
+
sh = anchor.winfo_screenheight()
|
|
1687
|
+
x = int(_clamp(ax, 0, sw - pw))
|
|
1688
|
+
y = int(_clamp(ay - ph - 4, 0, sh - ph))
|
|
1689
|
+
self._win.geometry(f"+{x}+{y}")
|
|
1690
|
+
|
|
1691
|
+
def _on_click(self, e: tk.Event) -> None:
|
|
1692
|
+
"""Reproduz a faixa clicada."""
|
|
1693
|
+
idx = self._lb.nearest(e.y)
|
|
1694
|
+
if 0 <= idx < len(self._player._playlist):
|
|
1695
|
+
self._player.play_index(idx)
|
|
1696
|
+
self._fechar()
|
|
1697
|
+
|
|
1698
|
+
def _on_enter(self, _e: tk.Event) -> None:
|
|
1699
|
+
"""Reproduz a faixa selecionada ao pressionar Enter."""
|
|
1700
|
+
sel = self._lb.curselection()
|
|
1701
|
+
if sel:
|
|
1702
|
+
self._player.play_index(sel[0])
|
|
1703
|
+
self._fechar()
|
|
1704
|
+
|
|
1705
|
+
def _on_focus_out(self, _e: tk.Event) -> None:
|
|
1706
|
+
"""Fecha o popup ao perder o foco."""
|
|
1707
|
+
if not self._destroyed:
|
|
1708
|
+
self._win.after(150, self._fechar_se_sem_foco)
|
|
1709
|
+
|
|
1710
|
+
def _fechar_se_sem_foco(self) -> None:
|
|
1711
|
+
"""Fecha somente se a janela realmente não tiver mais foco."""
|
|
1712
|
+
if self._destroyed:
|
|
1713
|
+
return
|
|
1714
|
+
with contextlib.suppress(tk.TclError):
|
|
1715
|
+
if not self._win.focus_displayof():
|
|
1716
|
+
self._fechar()
|
|
1717
|
+
|
|
1718
|
+
def _fechar(self) -> None:
|
|
1719
|
+
"""Fecha e destrói o popup."""
|
|
1720
|
+
if self._destroyed:
|
|
1721
|
+
return
|
|
1722
|
+
self._destroyed = True
|
|
1723
|
+
with contextlib.suppress(tk.TclError):
|
|
1724
|
+
self._win.destroy()
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
class ZenMiniOrb:
|
|
1728
|
+
"""Mini player flutuante: pílula arredondada com ícone animado,
|
|
1729
|
+
glow pulsante, nome da faixa truncado, barra de progresso e tempo.
|
|
1730
|
+
Clique único expande para o HUD completo; arrastar move pela tela.
|
|
1731
|
+
|
|
1732
|
+
Args:
|
|
1733
|
+
parent: Widget pai (janela raiz do Codis).
|
|
1734
|
+
player: Instância de :class:`ZenMediaPlayer` a monitorar.
|
|
1735
|
+
on_expand: Callback chamado quando o usuário clica para expandir.
|
|
1736
|
+
tmgr: Gerenciador de temas (opcional).
|
|
1737
|
+
"""
|
|
1738
|
+
|
|
1739
|
+
_PULSE_STEP = 0.08
|
|
1740
|
+
_PULSE_MS = 25
|
|
1741
|
+
_W = 210
|
|
1742
|
+
_H = 46
|
|
1743
|
+
_R = 23
|
|
1744
|
+
|
|
1745
|
+
def __init__(
|
|
1746
|
+
self,
|
|
1747
|
+
parent: tk.Widget,
|
|
1748
|
+
player: ZenMediaPlayer,
|
|
1749
|
+
on_expand: Callable | None = None,
|
|
1750
|
+
tmgr=None,
|
|
1751
|
+
) -> None:
|
|
1752
|
+
t = tmgr.theme if tmgr else None
|
|
1753
|
+
accent = getattr(t, "accent", "#7c4dff") if t else "#7c4dff"
|
|
1754
|
+
bg = getattr(t, "floating_bg", "#111127") if t else "#111127"
|
|
1755
|
+
fg = getattr(t, "fg", "#e8eaf6") if t else "#e8eaf6"
|
|
1756
|
+
fg_dim = getattr(t, "fg_muted", "#546e7a") if t else "#546e7a"
|
|
1757
|
+
|
|
1758
|
+
self._player = player
|
|
1759
|
+
self._accent = accent
|
|
1760
|
+
self._bg = bg
|
|
1761
|
+
self._fg = fg
|
|
1762
|
+
self._fg_dim = fg_dim
|
|
1763
|
+
self._on_expand = on_expand
|
|
1764
|
+
self._destroyed = False
|
|
1765
|
+
self._phase = 0.0
|
|
1766
|
+
self._anim_job: str | None = None
|
|
1767
|
+
self._drag_x = 0
|
|
1768
|
+
self._drag_y = 0
|
|
1769
|
+
self._drag_moved = False
|
|
1770
|
+
self._hovered = False
|
|
1771
|
+
|
|
1772
|
+
W, H = self._W, self._H
|
|
1773
|
+
|
|
1774
|
+
self._win = tk.Toplevel(parent)
|
|
1775
|
+
self._win.overrideredirect(True)
|
|
1776
|
+
self._win.attributes("-topmost", True)
|
|
1777
|
+
self._win.configure(bg=bg)
|
|
1778
|
+
self._win.geometry(f"{W}x{H}")
|
|
1779
|
+
self._win.resizable(False, False)
|
|
1780
|
+
with contextlib.suppress(tk.TclError):
|
|
1781
|
+
self._win.attributes("-alpha", 0.93)
|
|
1782
|
+
|
|
1783
|
+
self._canvas = tk.Canvas(
|
|
1784
|
+
self._win,
|
|
1785
|
+
width=W,
|
|
1786
|
+
height=H,
|
|
1787
|
+
bg=bg,
|
|
1788
|
+
highlightthickness=0,
|
|
1789
|
+
cursor="hand2",
|
|
1790
|
+
)
|
|
1791
|
+
self._canvas.pack()
|
|
1792
|
+
|
|
1793
|
+
for ev, cb in [
|
|
1794
|
+
("<ButtonPress-1>", self._drag_start),
|
|
1795
|
+
("<B1-Motion>", self._drag_move),
|
|
1796
|
+
("<ButtonRelease-1>", self._drag_end),
|
|
1797
|
+
("<Enter>", self._on_hover_enter),
|
|
1798
|
+
("<Leave>", self._on_hover_leave),
|
|
1799
|
+
]:
|
|
1800
|
+
self._canvas.bind(ev, cb)
|
|
1801
|
+
|
|
1802
|
+
player.on_change(self._on_player_change)
|
|
1803
|
+
player.on_state(self._on_player_state)
|
|
1804
|
+
|
|
1805
|
+
self._draw()
|
|
1806
|
+
self._start_anim()
|
|
1807
|
+
|
|
1808
|
+
def _fill_pill(self, x0: int, y0: int, x1: int, y1: int, r: int, fill: str) -> None:
|
|
1809
|
+
"""Preenche um retângulo com cantos completamente arredondados."""
|
|
1810
|
+
c = self._canvas
|
|
1811
|
+
d = r * 2
|
|
1812
|
+
c.create_arc(x0, y0, x0 + d, y0 + d, start=90,
|
|
1813
|
+
extent=90, fill=fill, outline="")
|
|
1814
|
+
c.create_arc(x1 - d, y0, x1, y0 + d, start=0,
|
|
1815
|
+
extent=90, fill=fill, outline="")
|
|
1816
|
+
c.create_arc(
|
|
1817
|
+
x0, y1 - d, x0 + d, y1, start=180, extent=90, fill=fill, outline=""
|
|
1818
|
+
)
|
|
1819
|
+
c.create_arc(
|
|
1820
|
+
x1 - d, y1 - d, x1, y1, start=270, extent=90, fill=fill, outline=""
|
|
1821
|
+
)
|
|
1822
|
+
c.create_rectangle(x0 + r, y0, x1 - r, y1, fill=fill, outline="")
|
|
1823
|
+
c.create_rectangle(x0, y0 + r, x1, y1 - r, fill=fill, outline="")
|
|
1824
|
+
|
|
1825
|
+
def _draw(self) -> None:
|
|
1826
|
+
"""Redesenha a pílula com estado atual do player."""
|
|
1827
|
+
if self._destroyed:
|
|
1828
|
+
return
|
|
1829
|
+
c = self._canvas
|
|
1830
|
+
c.delete("all")
|
|
1831
|
+
W, H = self._W, self._H
|
|
1832
|
+
R = self._R
|
|
1833
|
+
|
|
1834
|
+
playing = self._player.is_playing and not self._player.is_paused
|
|
1835
|
+
paused = self._player.is_paused
|
|
1836
|
+
|
|
1837
|
+
self._fill_pill(0, 0, W, H, R, self._bg)
|
|
1838
|
+
|
|
1839
|
+
border_col = self._accent if playing else (
|
|
1840
|
+
"#cc8800" if paused else "#2a2a40")
|
|
1841
|
+
c.create_arc(
|
|
1842
|
+
0,
|
|
1843
|
+
0,
|
|
1844
|
+
2 * R,
|
|
1845
|
+
2 * R,
|
|
1846
|
+
start=90,
|
|
1847
|
+
extent=90,
|
|
1848
|
+
outline=border_col,
|
|
1849
|
+
style="arc",
|
|
1850
|
+
width=1,
|
|
1851
|
+
)
|
|
1852
|
+
c.create_arc(
|
|
1853
|
+
W - 2 * R,
|
|
1854
|
+
0,
|
|
1855
|
+
W,
|
|
1856
|
+
2 * R,
|
|
1857
|
+
start=0,
|
|
1858
|
+
extent=90,
|
|
1859
|
+
outline=border_col,
|
|
1860
|
+
style="arc",
|
|
1861
|
+
width=1,
|
|
1862
|
+
)
|
|
1863
|
+
c.create_arc(
|
|
1864
|
+
0,
|
|
1865
|
+
H - 2 * R,
|
|
1866
|
+
2 * R,
|
|
1867
|
+
H,
|
|
1868
|
+
start=180,
|
|
1869
|
+
extent=90,
|
|
1870
|
+
outline=border_col,
|
|
1871
|
+
style="arc",
|
|
1872
|
+
width=1,
|
|
1873
|
+
)
|
|
1874
|
+
c.create_arc(
|
|
1875
|
+
W - 2 * R,
|
|
1876
|
+
H - 2 * R,
|
|
1877
|
+
W,
|
|
1878
|
+
H,
|
|
1879
|
+
start=270,
|
|
1880
|
+
extent=90,
|
|
1881
|
+
outline=border_col,
|
|
1882
|
+
style="arc",
|
|
1883
|
+
width=1,
|
|
1884
|
+
)
|
|
1885
|
+
c.create_line(R, 0, W - R, 0, fill=border_col, width=1)
|
|
1886
|
+
c.create_line(R, H, W - R, H, fill=border_col, width=1)
|
|
1887
|
+
c.create_line(0, R, 0, H - R, fill=border_col, width=1)
|
|
1888
|
+
c.create_line(W, R, W, H - R, fill=border_col, width=1)
|
|
1889
|
+
|
|
1890
|
+
orb_cx = H // 2
|
|
1891
|
+
orb_cy = H // 2
|
|
1892
|
+
orb_r_base = H // 2 - 8
|
|
1893
|
+
|
|
1894
|
+
pulse = 0.78 + 0.22 * math.sin(self._phase) if playing else 1.0
|
|
1895
|
+
orb_r = max(4, int(orb_r_base * pulse))
|
|
1896
|
+
|
|
1897
|
+
if playing:
|
|
1898
|
+
gr = orb_r + 5
|
|
1899
|
+
c.create_oval(
|
|
1900
|
+
orb_cx - gr,
|
|
1901
|
+
orb_cy - gr,
|
|
1902
|
+
orb_cx + gr,
|
|
1903
|
+
orb_cy + gr,
|
|
1904
|
+
fill=_alpha_blend_hex(self._accent, self._bg, 0.2),
|
|
1905
|
+
outline="",
|
|
1906
|
+
)
|
|
1907
|
+
|
|
1908
|
+
orb_col = self._accent if playing else (
|
|
1909
|
+
"#cc8800" if paused else "#1e1e38")
|
|
1910
|
+
c.create_oval(
|
|
1911
|
+
orb_cx - orb_r,
|
|
1912
|
+
orb_cy - orb_r,
|
|
1913
|
+
orb_cx + orb_r,
|
|
1914
|
+
orb_cy + orb_r,
|
|
1915
|
+
fill=orb_col,
|
|
1916
|
+
outline="",
|
|
1917
|
+
)
|
|
1918
|
+
|
|
1919
|
+
icon = "▶" if playing else ("⏸" if paused else "♪")
|
|
1920
|
+
icon_fg = "#ffffff" if (playing or paused) else self._fg_dim
|
|
1921
|
+
c.create_text(
|
|
1922
|
+
orb_cx, orb_cy, text=icon, fill=icon_fg, font=(
|
|
1923
|
+
"Segoe UI", 9, "bold")
|
|
1924
|
+
)
|
|
1925
|
+
|
|
1926
|
+
if self._player.duration > 0:
|
|
1927
|
+
frac = _clamp(self._player.position /
|
|
1928
|
+
self._player.duration, 0.0, 1.0)
|
|
1929
|
+
arc_r = orb_r_base + 4
|
|
1930
|
+
c.create_arc(
|
|
1931
|
+
orb_cx - arc_r,
|
|
1932
|
+
orb_cy - arc_r,
|
|
1933
|
+
orb_cx + arc_r,
|
|
1934
|
+
orb_cy + arc_r,
|
|
1935
|
+
start=90,
|
|
1936
|
+
extent=-(frac * 360),
|
|
1937
|
+
outline=self._accent,
|
|
1938
|
+
width=2,
|
|
1939
|
+
style="arc",
|
|
1940
|
+
)
|
|
1941
|
+
|
|
1942
|
+
tx = H + 2
|
|
1943
|
+
tw = W - tx - 6
|
|
1944
|
+
track = self._player.current_track or (
|
|
1945
|
+
"Tocando..." if playing else "Zen Media")
|
|
1946
|
+
max_ch = max(6, tw // 6)
|
|
1947
|
+
label = track if len(track) <= max_ch else track[: max_ch - 1] + "..."
|
|
1948
|
+
c.create_text(
|
|
1949
|
+
tx,
|
|
1950
|
+
H // 2 - 6,
|
|
1951
|
+
text=label,
|
|
1952
|
+
anchor="w",
|
|
1953
|
+
fill=self._fg if (playing or paused) else self._fg_dim,
|
|
1954
|
+
font=("Segoe UI", 8, "bold"),
|
|
1955
|
+
)
|
|
1956
|
+
|
|
1957
|
+
if self._player.duration > 0:
|
|
1958
|
+
ts = f"{_fmt_time(self._player.position)} / {_fmt_time(self._player.duration)}"
|
|
1959
|
+
elif playing or paused:
|
|
1960
|
+
ts = _fmt_time(self._player.position)
|
|
1961
|
+
else:
|
|
1962
|
+
ts = "- : -"
|
|
1963
|
+
c.create_text(
|
|
1964
|
+
tx, H // 2 + 7, text=ts, anchor="w", fill=self._fg_dim, font=("Segoe UI", 7)
|
|
1965
|
+
)
|
|
1966
|
+
|
|
1967
|
+
if self._player.duration > 0:
|
|
1968
|
+
frac = _clamp(self._player.position /
|
|
1969
|
+
self._player.duration, 0.0, 1.0)
|
|
1970
|
+
bx0 = R
|
|
1971
|
+
bx1 = W - R
|
|
1972
|
+
by = H - 4
|
|
1973
|
+
bw = bx1 - bx0
|
|
1974
|
+
c.create_line(bx0, by, bx1, by, fill="#2a2a40",
|
|
1975
|
+
width=2, capstyle="round")
|
|
1976
|
+
filled = bx0 + int(bw * frac)
|
|
1977
|
+
if filled > bx0:
|
|
1978
|
+
c.create_line(
|
|
1979
|
+
bx0, by, filled, by, fill=self._accent, width=2, capstyle="round"
|
|
1980
|
+
)
|
|
1981
|
+
|
|
1982
|
+
def _start_anim(self) -> None:
|
|
1983
|
+
self._tick_anim()
|
|
1984
|
+
|
|
1985
|
+
def _tick_anim(self) -> None:
|
|
1986
|
+
if self._destroyed:
|
|
1987
|
+
return
|
|
1988
|
+
self._phase += self._PULSE_STEP
|
|
1989
|
+
self._draw()
|
|
1990
|
+
self._anim_job = self._win.after(self._PULSE_MS, self._tick_anim)
|
|
1991
|
+
|
|
1992
|
+
def _on_hover_enter(self, _e=None) -> None:
|
|
1993
|
+
self._hovered = True
|
|
1994
|
+
with contextlib.suppress(tk.TclError):
|
|
1995
|
+
self._win.attributes("-alpha", 1.0)
|
|
1996
|
+
|
|
1997
|
+
def _on_hover_leave(self, _e=None) -> None:
|
|
1998
|
+
self._hovered = False
|
|
1999
|
+
with contextlib.suppress(tk.TclError):
|
|
2000
|
+
self._win.attributes("-alpha", 0.93)
|
|
2001
|
+
|
|
2002
|
+
def _on_player_change(self) -> None:
|
|
2003
|
+
if not self._destroyed:
|
|
2004
|
+
with contextlib.suppress(tk.TclError):
|
|
2005
|
+
self._win.after(0, self._draw)
|
|
2006
|
+
|
|
2007
|
+
def _on_player_state(self, *_) -> None:
|
|
2008
|
+
if not self._destroyed:
|
|
2009
|
+
with contextlib.suppress(tk.TclError):
|
|
2010
|
+
self._win.after(0, self._draw)
|
|
2011
|
+
|
|
2012
|
+
def _drag_start(self, e: tk.Event) -> None:
|
|
2013
|
+
self._drag_x = e.x_root
|
|
2014
|
+
self._drag_y = e.y_root
|
|
2015
|
+
self._drag_moved = False
|
|
2016
|
+
|
|
2017
|
+
def _drag_move(self, e: tk.Event) -> None:
|
|
2018
|
+
dx = e.x_root - self._drag_x
|
|
2019
|
+
dy = e.y_root - self._drag_y
|
|
2020
|
+
if abs(dx) > 3 or abs(dy) > 3:
|
|
2021
|
+
self._drag_moved = True
|
|
2022
|
+
self._drag_x = e.x_root
|
|
2023
|
+
self._drag_y = e.y_root
|
|
2024
|
+
with contextlib.suppress(tk.TclError):
|
|
2025
|
+
self._win.geometry(
|
|
2026
|
+
f"+{self._win.winfo_x() + dx}+{self._win.winfo_y() + dy}"
|
|
2027
|
+
)
|
|
2028
|
+
|
|
2029
|
+
def _drag_end(self, _e: tk.Event) -> None:
|
|
2030
|
+
if not self._drag_moved and self._on_expand:
|
|
2031
|
+
with contextlib.suppress(tk.TclError):
|
|
2032
|
+
self._on_expand()
|
|
2033
|
+
self._drag_moved = False
|
|
2034
|
+
|
|
2035
|
+
def show(self) -> None:
|
|
2036
|
+
"""Exibe o mini orb na interface."""
|
|
2037
|
+
if self._destroyed:
|
|
2038
|
+
return
|
|
2039
|
+
with contextlib.suppress(tk.TclError):
|
|
2040
|
+
self._win.deiconify()
|
|
2041
|
+
self._win.lift()
|
|
2042
|
+
|
|
2043
|
+
def hide(self) -> None:
|
|
2044
|
+
"""Oculta o mini orb da interface."""
|
|
2045
|
+
if self._destroyed:
|
|
2046
|
+
return
|
|
2047
|
+
with contextlib.suppress(tk.TclError):
|
|
2048
|
+
self._win.withdraw()
|
|
2049
|
+
|
|
2050
|
+
def move_to(self, x: int, y: int) -> None:
|
|
2051
|
+
"""Move o mini orb para a posição (x, y)."""
|
|
2052
|
+
with contextlib.suppress(tk.TclError):
|
|
2053
|
+
self._win.geometry(f"+{x}+{y}")
|
|
2054
|
+
|
|
2055
|
+
def winfo_exists(self) -> bool:
|
|
2056
|
+
"""Retorna ``True`` se o orb ainda existe na interface."""
|
|
2057
|
+
try:
|
|
2058
|
+
return bool(self._win.winfo_exists())
|
|
2059
|
+
except tk.TclError:
|
|
2060
|
+
return False
|
|
2061
|
+
|
|
2062
|
+
def stop_orb(self) -> None:
|
|
2063
|
+
"""Para a animação de pulsação do orb."""
|
|
2064
|
+
self._destroyed = True
|
|
2065
|
+
if self._anim_job:
|
|
2066
|
+
with contextlib.suppress(tk.TclError):
|
|
2067
|
+
self._win.after_cancel(self._anim_job)
|
|
2068
|
+
self._anim_job = None
|
|
2069
|
+
|
|
2070
|
+
def destroy(self) -> None:
|
|
2071
|
+
"""Destrói o orb e para recursos associados."""
|
|
2072
|
+
self.stop_orb()
|
|
2073
|
+
with contextlib.suppress(tk.TclError):
|
|
2074
|
+
self._win.destroy()
|
|
2075
|
+
|
|
2076
|
+
|
|
2077
|
+
class ZenMediaDialog:
|
|
2078
|
+
"""Diálogo modal para configuração da playlist e opções de autoplay.
|
|
2079
|
+
|
|
2080
|
+
Permite colar URLs do YouTube/streams ou adicionar uma pasta local.
|
|
2081
|
+
Oferece botões de Salvar, Tocar Agora e Parar.
|
|
2082
|
+
|
|
2083
|
+
Args:
|
|
2084
|
+
parent: Widget pai (janela raiz do Codis).
|
|
2085
|
+
tmgr: Gerenciador de temas; se ``None`` usa paleta escura padrão.
|
|
2086
|
+
player: Instância de :class:`ZenMediaPlayer` a configurar.
|
|
2087
|
+
"""
|
|
2088
|
+
|
|
2089
|
+
def __init__(self, parent: tk.Widget, tmgr, player: ZenMediaPlayer, cfg) -> None:
|
|
2090
|
+
t = tmgr.theme if tmgr else None
|
|
2091
|
+
bg = getattr(t, "floating_bg", "#06061a") if t else "#06061a"
|
|
2092
|
+
borda = getattr(t, "accent", "#7c4dff") if t else "#7c4dff"
|
|
2093
|
+
fg = getattr(t, "fg", "#e8eaf6") if t else "#e8eaf6"
|
|
2094
|
+
fg_dim = getattr(t, "fg_muted", "#546e7a") if t else "#546e7a"
|
|
2095
|
+
|
|
2096
|
+
self._player = player
|
|
2097
|
+
self._cfg = cfg
|
|
2098
|
+
|
|
2099
|
+
self._dlg = tk.Toplevel(parent)
|
|
2100
|
+
self._dlg.title("🎵 Zen Media - Playlist")
|
|
2101
|
+
self._dlg.configure(bg=bg)
|
|
2102
|
+
self._dlg.transient(parent)
|
|
2103
|
+
safe_grab_set(self._dlg)
|
|
2104
|
+
self._dlg.geometry("540x520")
|
|
2105
|
+
self._dlg.minsize(520, 420)
|
|
2106
|
+
|
|
2107
|
+
tk.Frame(self._dlg, bg=borda, height=2).pack(fill="x")
|
|
2108
|
+
tk.Label(
|
|
2109
|
+
self._dlg,
|
|
2110
|
+
text=_t("hc.zen_media.zen_media_playlist"),
|
|
2111
|
+
bg=bg,
|
|
2112
|
+
fg=fg,
|
|
2113
|
+
font=("Segoe UI", 11, "bold"),
|
|
2114
|
+
pady=10,
|
|
2115
|
+
).pack(fill="x", padx=14)
|
|
2116
|
+
|
|
2117
|
+
partes = []
|
|
2118
|
+
if player.has_player:
|
|
2119
|
+
libs = []
|
|
2120
|
+
if MPV_AVAILABLE:
|
|
2121
|
+
libs.append("python-mpv")
|
|
2122
|
+
if VLC_AVAILABLE:
|
|
2123
|
+
libs.append("python-vlc")
|
|
2124
|
+
partes.append(f"Bibliotecas: {' + '.join(libs)}")
|
|
2125
|
+
else:
|
|
2126
|
+
partes.append("⚠ Nenhuma biblioteca instalada")
|
|
2127
|
+
partes.append(
|
|
2128
|
+
"yt-dlp: ok" if player._ytdlp else "yt-dlp: não encontrado")
|
|
2129
|
+
tk.Label(
|
|
2130
|
+
self._dlg,
|
|
2131
|
+
text=" ".join(partes),
|
|
2132
|
+
bg=bg,
|
|
2133
|
+
fg=fg_dim,
|
|
2134
|
+
font=("Segoe UI", 8),
|
|
2135
|
+
).pack(anchor="w", padx=14, pady=(0, 2))
|
|
2136
|
+
|
|
2137
|
+
tk.Label(
|
|
2138
|
+
self._dlg,
|
|
2139
|
+
text=_t("zen_media.url_hint"),
|
|
2140
|
+
bg=bg,
|
|
2141
|
+
fg=fg_dim,
|
|
2142
|
+
font=("Segoe UI", 8),
|
|
2143
|
+
justify="left",
|
|
2144
|
+
).pack(anchor="w", padx=14, pady=(0, 6))
|
|
2145
|
+
|
|
2146
|
+
tf = tk.Frame(self._dlg, bg=borda, padx=1, pady=1)
|
|
2147
|
+
tf.pack(fill="both", expand=True, padx=14)
|
|
2148
|
+
self._txt = tk.Text(
|
|
2149
|
+
tf,
|
|
2150
|
+
bg="#030312",
|
|
2151
|
+
fg=fg,
|
|
2152
|
+
insertbackground=borda,
|
|
2153
|
+
font=("Segoe UI", 9),
|
|
2154
|
+
relief="flat",
|
|
2155
|
+
bd=0,
|
|
2156
|
+
highlightthickness=0,
|
|
2157
|
+
)
|
|
2158
|
+
sb = tk.Scrollbar(tf, command=self._txt.yview)
|
|
2159
|
+
self._txt.config(yscrollcommand=sb.set)
|
|
2160
|
+
sb.pack(side="right", fill="y")
|
|
2161
|
+
self._txt.pack(fill="both", expand=True, padx=4, pady=4)
|
|
2162
|
+
|
|
2163
|
+
for e in player._playlist:
|
|
2164
|
+
self._txt.insert("end", e["url"] + "\n")
|
|
2165
|
+
|
|
2166
|
+
fr_opcoes = tk.Frame(self._dlg, bg=bg)
|
|
2167
|
+
fr_opcoes.pack(fill="x", padx=14, pady=(6, 0))
|
|
2168
|
+
|
|
2169
|
+
kw = {
|
|
2170
|
+
"bg": "#0d0d30",
|
|
2171
|
+
"fg": fg,
|
|
2172
|
+
"relief": "flat",
|
|
2173
|
+
"font": ("Segoe UI", 9),
|
|
2174
|
+
"padx": 12,
|
|
2175
|
+
"pady": 4,
|
|
2176
|
+
"cursor": "hand2",
|
|
2177
|
+
}
|
|
2178
|
+
|
|
2179
|
+
tk.Button(
|
|
2180
|
+
fr_opcoes,
|
|
2181
|
+
text=_t("hc.zen_media.adicionar_pasta"),
|
|
2182
|
+
command=self._choose_folder,
|
|
2183
|
+
**kw,
|
|
2184
|
+
).pack(side="left", padx=(0, 8))
|
|
2185
|
+
|
|
2186
|
+
self._autoplay_var = tk.BooleanVar(
|
|
2187
|
+
value=cfg.get("zen_media_autoplay", False))
|
|
2188
|
+
tk.Checkbutton(
|
|
2189
|
+
fr_opcoes,
|
|
2190
|
+
text=_t("hc.zen_media.auto_play_ao_entrar_no_zen_mod"),
|
|
2191
|
+
variable=self._autoplay_var,
|
|
2192
|
+
bg=bg,
|
|
2193
|
+
fg=fg_dim,
|
|
2194
|
+
selectcolor=bg,
|
|
2195
|
+
font=("Segoe UI", 8),
|
|
2196
|
+
activebackground=bg,
|
|
2197
|
+
activeforeground=fg,
|
|
2198
|
+
).pack(side="left", padx=10)
|
|
2199
|
+
|
|
2200
|
+
fr_rodape = tk.Frame(self._dlg, bg=bg)
|
|
2201
|
+
fr_rodape.pack(fill="x", padx=14, pady=(10, 12))
|
|
2202
|
+
|
|
2203
|
+
def _saveit():
|
|
2204
|
+
"""Salva a playlist e opções no objeto de configuração."""
|
|
2205
|
+
urls = [
|
|
2206
|
+
l_.strip()
|
|
2207
|
+
for l_ in self._txt.get("1.0", "end-1c").splitlines()
|
|
2208
|
+
if l_.strip()
|
|
2209
|
+
]
|
|
2210
|
+
player.set_playlist(urls)
|
|
2211
|
+
cfg.set("zen_media_playlist", urls)
|
|
2212
|
+
cfg.set("zen_media_autoplay", self._autoplay_var.get())
|
|
2213
|
+
with contextlib.suppress(tk.TclError):
|
|
2214
|
+
cfg.save()
|
|
2215
|
+
self._dlg.destroy()
|
|
2216
|
+
|
|
2217
|
+
def _play_now():
|
|
2218
|
+
"""Salva e inicia a reprodução imediatamente."""
|
|
2219
|
+
_saveit()
|
|
2220
|
+
player.play()
|
|
2221
|
+
|
|
2222
|
+
def _stopit():
|
|
2223
|
+
"""Para a reprodução e fecha o diálogo."""
|
|
2224
|
+
player.stop()
|
|
2225
|
+
self._dlg.destroy()
|
|
2226
|
+
|
|
2227
|
+
tk.Button(
|
|
2228
|
+
fr_rodape, text=_t("hc.zen_media.tocar_agora"), command=_play_now, **kw
|
|
2229
|
+
).pack(side="left", padx=(0, 4))
|
|
2230
|
+
tk.Button(
|
|
2231
|
+
fr_rodape,
|
|
2232
|
+
text=_t("hc.zen_media.parar"),
|
|
2233
|
+
command=_stopit,
|
|
2234
|
+
bg="#0d0d30",
|
|
2235
|
+
fg="#ff4081",
|
|
2236
|
+
relief="flat",
|
|
2237
|
+
font=("Segoe UI", 9),
|
|
2238
|
+
padx=12,
|
|
2239
|
+
pady=4,
|
|
2240
|
+
cursor="hand2",
|
|
2241
|
+
).pack(side="left", padx=(0, 4))
|
|
2242
|
+
tk.Button(
|
|
2243
|
+
fr_rodape, text=_t("hc.zen_media.salvar"), command=_saveit, **kw
|
|
2244
|
+
).pack(side="left", padx=(0, 4))
|
|
2245
|
+
tk.Button(
|
|
2246
|
+
fr_rodape, text=_t("hc.zen_media.cancelar"), command=self._dlg.destroy, **kw
|
|
2247
|
+
).pack(side="right")
|
|
2248
|
+
|
|
2249
|
+
tk.Label(
|
|
2250
|
+
self._dlg,
|
|
2251
|
+
text=_t("hc.zen_media.requer_python_vlc_ou_python_mp"),
|
|
2252
|
+
bg=bg,
|
|
2253
|
+
fg="#2d3080",
|
|
2254
|
+
font=("Segoe UI", 7),
|
|
2255
|
+
).pack(pady=(0, 4))
|
|
2256
|
+
|
|
2257
|
+
def _choose_folder(self) -> None:
|
|
2258
|
+
"""Abre o seletor de pasta e carrega os arquivos de mídia encontrados."""
|
|
2259
|
+
folder = filedialog.askdirectory(
|
|
2260
|
+
parent=self._dlg,
|
|
2261
|
+
title=_t("hc.zen_media.selecione_uma_pasta_com_m_sica"),
|
|
2262
|
+
)
|
|
2263
|
+
if folder:
|
|
2264
|
+
self._player.load_folder(folder)
|
|
2265
|
+
self._update_text()
|
|
2266
|
+
|
|
2267
|
+
def _update_text(self) -> None:
|
|
2268
|
+
"""Sincroniza a área de texto com a playlist atual do player."""
|
|
2269
|
+
self._txt.delete("1.0", tk.END)
|
|
2270
|
+
for e in self._player._playlist:
|
|
2271
|
+
self._txt.insert(tk.END, e["url"] + "\n")
|