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.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
@@ -0,0 +1,303 @@
1
+ """Codis - Cliente do processo de mídia do Zen Player.
2
+
3
+ O libvlc e o libmpv são código nativo: uma violação de acesso dentro deles
4
+ (``libvlc_media_player_stop`` ao trocar de faixa logo depois de uma busca, por
5
+ exemplo) mata o processo inteiro e nenhum ``try/except`` do Python a captura.
6
+ Por isso o motor de reprodução roda num processo filho
7
+ (:mod:`src.ui.zen_media_host`) e o Codis conversa com ele por linhas JSON:
8
+
9
+ * Codis -> host (stdin): ``play``, ``pause``, ``seek``, ``volume``, ``eq``,
10
+ ``stop`` e ``quit``.
11
+ * host -> Codis (stdout): ``hello``, ``started``, ``pos``, ``paused``,
12
+ ``ended``, ``error``, ``stopped`` e ``tick``.
13
+
14
+ Se o filho cai ou trava, só a reprodução é perdida: o Codis registra o motivo
15
+ e sobe um novo processo na próxima faixa. Este módulo não depende do Tkinter.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import collections
21
+ import contextlib
22
+ import itertools
23
+ import json
24
+ import logging
25
+ import os
26
+ import subprocess
27
+ import sys
28
+ import threading
29
+ import time
30
+ from collections.abc import Callable
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ logger = logging.getLogger("Codis.ZenMediaHost")
35
+
36
+ # Tempo máximo para o processo filho importar as bibliotecas e responder.
37
+ HOST_START_WAIT = 20.0
38
+ # Tempo máximo esperando a confirmação de um ``stop``; passado disso o filho é encerrado.
39
+ HOST_STOP_WAIT = 10.0
40
+ # Silêncio máximo do filho (ele emite sinais de vida mesmo parado) antes de ser encerrado.
41
+ HOST_HANG_LIMIT = 20.0
42
+ # Tempo dado ao filho para sair sozinho em ``quit`` antes de ser encerrado à força.
43
+ HOST_QUIT_WAIT = 2.0
44
+
45
+ _CREATE_NO_WINDOW = 0x08000000
46
+
47
+
48
+ def host_command() -> list[str]:
49
+ """Linha de comando do processo de mídia (também funciona no executável congelado)."""
50
+ return [sys.executable, "-m", "src.ui.zen_media_host"]
51
+
52
+
53
+ def _host_env() -> dict[str, str]:
54
+ env = dict(os.environ)
55
+ env.update(PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8", PYTHONUTF8="1")
56
+ return env
57
+
58
+
59
+ class MediaHostClient:
60
+ """Processo filho do motor de mídia e o canal de comunicação com ele.
61
+
62
+ Args:
63
+ on_event: Chamado na thread leitora com cada evento do host
64
+ (``dict`` com a chave ``ev``).
65
+ on_exit: Chamado na thread leitora quando o filho termina sem que o
66
+ encerramento tenha sido pedido: ``on_exit(cliente, código_de_saída)``.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ on_event: Callable[[dict[str, Any]], None],
72
+ on_exit: Callable[[MediaHostClient, int | None], None],
73
+ ) -> None:
74
+ self._on_event = on_event
75
+ self._on_exit = on_exit
76
+ self._proc: subprocess.Popen[bytes] | None = None
77
+ self._write_lock = threading.Lock()
78
+ self._ready = threading.Event()
79
+ self._dead = threading.Event()
80
+ self._closing = False
81
+ self._last_seen = time.monotonic()
82
+ self._acks: dict[int, threading.Event] = {}
83
+ self._ack_lock = threading.Lock()
84
+ self._seq = itertools.count(1)
85
+ self._stderr_thread: threading.Thread | None = None
86
+ self.caps: dict[str, bool] = {}
87
+ self.stderr_tail: collections.deque[str] = collections.deque(maxlen=60)
88
+
89
+ @property
90
+ def alive(self) -> bool:
91
+ """``True`` enquanto o processo filho existe e responde ao canal."""
92
+ return self._proc is not None and not self._dead.is_set()
93
+
94
+ def start(self) -> bool:
95
+ """Sobe o processo filho e espera o ``hello``. Retorna se ele ficou pronto."""
96
+ kwargs: dict[str, Any] = {}
97
+ if sys.platform == "win32":
98
+ kwargs["creationflags"] = _CREATE_NO_WINDOW
99
+ if not getattr(sys, "frozen", False):
100
+ kwargs["cwd"] = str(Path(__file__).resolve().parents[2])
101
+ try:
102
+ self._proc = subprocess.Popen( # noqa: S603 - comando montado só com sys.executable
103
+ host_command(),
104
+ stdin=subprocess.PIPE,
105
+ stdout=subprocess.PIPE,
106
+ stderr=subprocess.PIPE,
107
+ env=_host_env(),
108
+ **kwargs,
109
+ )
110
+ except OSError as exc:
111
+ logger.error("não foi possível iniciar o processo de mídia: %s", exc)
112
+ return False
113
+ self._last_seen = time.monotonic()
114
+ self._stderr_thread = threading.Thread(
115
+ target=self._stderr_loop, daemon=True, name="CodisMediaHostErr")
116
+ self._stderr_thread.start()
117
+ threading.Thread(target=self._read_loop, daemon=True, name="CodisMediaHostRead").start()
118
+ threading.Thread(target=self._watch_loop, daemon=True, name="CodisMediaHostWatch").start()
119
+ if not self._ready.wait(HOST_START_WAIT) or self._dead.is_set():
120
+ logger.error("o processo de mídia não respondeu ao iniciar")
121
+ self.kill()
122
+ return False
123
+ return True
124
+
125
+ def send(self, **message: Any) -> bool:
126
+ """Envia um comando ao host. ``False`` se o canal não está mais disponível."""
127
+ proc = self._proc
128
+ if proc is None or self._dead.is_set():
129
+ return False
130
+ data = (json.dumps(message, separators=(",", ":")) + "\n").encode("utf-8")
131
+ try:
132
+ with self._write_lock:
133
+ proc.stdin.write(data) # type: ignore[union-attr]
134
+ proc.stdin.flush() # type: ignore[union-attr]
135
+ except (OSError, ValueError):
136
+ return False
137
+ return True
138
+
139
+ def request_stop(self, timeout: float = HOST_STOP_WAIT) -> bool:
140
+ """Pede ao host que pare a reprodução e espera a confirmação.
141
+
142
+ Se o host não confirmar a tempo (travado dentro do libvlc/libmpv) ele é
143
+ encerrado à força: com o processo morto a superfície de vídeo fica livre.
144
+
145
+ Returns:
146
+ ``True`` se o host parou (ou já não existe); ``False`` se foi preciso matá-lo.
147
+ """
148
+ if not self.alive:
149
+ return True
150
+ seq = next(self._seq)
151
+ ack = threading.Event()
152
+ with self._ack_lock:
153
+ self._acks[seq] = ack
154
+ try:
155
+ if not self.send(cmd="stop", seq=seq):
156
+ return not self.alive
157
+ if ack.wait(timeout):
158
+ return True
159
+ logger.error("o processo de mídia não parou em %.0fs; encerrando", timeout)
160
+ self.kill()
161
+ return False
162
+ finally:
163
+ with self._ack_lock:
164
+ self._acks.pop(seq, None)
165
+
166
+ def kill(self) -> None:
167
+ """Encerra o processo filho imediatamente."""
168
+ proc = self._proc
169
+ if proc is not None:
170
+ with contextlib.suppress(OSError):
171
+ proc.kill()
172
+
173
+ def close(self) -> None:
174
+ """Encerramento ordenado: pede ``quit`` e mata o filho se ele não sair."""
175
+ self._closing = True
176
+ if self._proc is None:
177
+ return
178
+ self.send(cmd="quit")
179
+ if not self._dead.wait(HOST_QUIT_WAIT):
180
+ self.kill()
181
+
182
+ def _read_loop(self) -> None:
183
+ proc = self._proc
184
+ assert proc is not None and proc.stdout is not None
185
+ try:
186
+ for raw in proc.stdout:
187
+ self._last_seen = time.monotonic()
188
+ try:
189
+ message = json.loads(raw)
190
+ except ValueError:
191
+ continue
192
+ if not isinstance(message, dict):
193
+ continue
194
+ event = message.get("ev")
195
+ if event == "tick":
196
+ continue
197
+ if event == "hello":
198
+ self.caps = {"mpv": bool(message.get("mpv")), "vlc": bool(message.get("vlc"))}
199
+ self._ready.set()
200
+ continue
201
+ if event == "stopped":
202
+ with self._ack_lock:
203
+ ack = self._acks.get(message.get("seq", -1))
204
+ if ack is not None:
205
+ ack.set()
206
+ continue
207
+ try:
208
+ self._on_event(message)
209
+ except Exception:
210
+ logger.exception("falha ao tratar o evento %r do processo de mídia", event)
211
+ except (OSError, ValueError):
212
+ pass
213
+ finally:
214
+ code = self._reap(proc)
215
+ self._dead.set()
216
+ self._ready.set()
217
+ with self._ack_lock:
218
+ for ack in self._acks.values():
219
+ ack.set()
220
+ if not self._closing:
221
+ self._report_exit(code)
222
+ with contextlib.suppress(Exception):
223
+ self._on_exit(self, code)
224
+
225
+ @staticmethod
226
+ def _reap(proc: subprocess.Popen[bytes]) -> int | None:
227
+ try:
228
+ return proc.wait(timeout=2.0)
229
+ except subprocess.TimeoutExpired:
230
+ with contextlib.suppress(OSError):
231
+ proc.kill()
232
+ with contextlib.suppress(subprocess.TimeoutExpired):
233
+ return proc.wait(timeout=2.0)
234
+ return None
235
+
236
+ def _report_exit(self, code: int | None) -> None:
237
+ """Registra a queda do filho com o que ele escreveu em stderr (faulthandler)."""
238
+ thread = self._stderr_thread
239
+ if thread is not None:
240
+ thread.join(0.5)
241
+ shown: Any = code
242
+ if isinstance(code, int) and code < 0:
243
+ shown = f"sinal {-code}"
244
+ elif isinstance(code, int) and code > 255:
245
+ shown = hex(code)
246
+ logger.error(
247
+ "o processo de mídia terminou de forma inesperada (código %s); o Codis continua aberto",
248
+ shown,
249
+ )
250
+ if self.stderr_tail:
251
+ logger.error("saída do processo de mídia:\n%s", "\n".join(self.stderr_tail))
252
+
253
+ def _stderr_loop(self) -> None:
254
+ proc = self._proc
255
+ assert proc is not None and proc.stderr is not None
256
+ with contextlib.suppress(OSError, ValueError):
257
+ for raw in proc.stderr:
258
+ line = raw.decode("utf-8", "replace").rstrip()
259
+ if line:
260
+ self.stderr_tail.append(line)
261
+ logger.debug("[host] %s", line)
262
+
263
+ def _watch_loop(self) -> None:
264
+ while not self._dead.wait(1.0):
265
+ silent = time.monotonic() - self._last_seen
266
+ if silent > HOST_HANG_LIMIT:
267
+ logger.error("o processo de mídia ficou %.0fs sem responder; encerrando", silent)
268
+ self.kill()
269
+ return
270
+
271
+
272
+ class RemotePlayback:
273
+ """Uma reprodução no host, com a mesma superfície de controle de um player local.
274
+
275
+ Args:
276
+ host: Cliente do processo de mídia.
277
+ play_id: Identificador da reprodução (a geração do motor); comandos de
278
+ reproduções antigas são ignorados pelo host.
279
+ """
280
+
281
+ def __init__(self, host: MediaHostClient, play_id: int) -> None:
282
+ self.host = host
283
+ self.play_id = play_id
284
+
285
+ def pause(self, paused: bool) -> None:
286
+ """Pausa ou retoma."""
287
+ self.host.send(cmd="pause", id=self.play_id, paused=bool(paused))
288
+
289
+ def seek(self, position: float) -> None:
290
+ """Busca a posição *position*, em segundos."""
291
+ self.host.send(cmd="seek", id=self.play_id, pos=float(position))
292
+
293
+ def volume(self, value: int) -> None:
294
+ """Define o volume (0-100)."""
295
+ self.host.send(cmd="volume", id=self.play_id, value=int(value))
296
+
297
+ def equalizer(self, gains: list[float], enabled: bool) -> None:
298
+ """Aplica o equalizador."""
299
+ self.host.send(cmd="eq", id=self.play_id, gains=list(gains), enabled=bool(enabled))
300
+
301
+ def stop(self) -> None:
302
+ """Para a reprodução e espera o host confirmar."""
303
+ self.host.request_stop()
@@ -0,0 +1,329 @@
1
+ """Codis - Processo de mídia do Zen Player.
2
+
3
+ Executa o libmpv/libvlc fora do processo do Codis (ver
4
+ :mod:`src.ui.zen_media_client`). Se uma chamada nativa derrubar este processo,
5
+ o editor continua aberto e só a reprodução é interrompida.
6
+
7
+ Todos os comandos rodam numa única thread, um de cada vez, então o libvlc nunca
8
+ recebe chamadas concorrentes (busca, parada e consulta de estado).
9
+
10
+ Uso: ``python -m src.ui.zen_media_host`` (o Codis o inicia sozinho).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import faulthandler
17
+ import json
18
+ import logging
19
+ import os
20
+ import queue
21
+ import signal
22
+ import sys
23
+ import threading
24
+ import time
25
+ from typing import Any
26
+
27
+ _ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
28
+ if _ROOT not in sys.path:
29
+ sys.path.insert(0, _ROOT)
30
+
31
+ logger = logging.getLogger("Codis.ZenMediaHost")
32
+
33
+ _TICK = 0.3
34
+ _IDLE_SIGNAL = 1.0
35
+ _EOF = object()
36
+
37
+
38
+ class _Host:
39
+ """Estado do player ativo e tratamento dos comandos recebidos do Codis."""
40
+
41
+ def __init__(self, out: Any, media: Any) -> None:
42
+ self._out = out
43
+ self._media = media
44
+ self._out_lock = threading.Lock()
45
+ self._player: Any = None
46
+ self._kind: str | None = None
47
+ self._play_id = 0
48
+ self._stopping = False
49
+ self._ended_sent = False
50
+ self._seeked_at = 0.0
51
+ self._last_signal = 0.0
52
+
53
+ def emit(self, **message: Any) -> None:
54
+ """Envia um evento ao Codis; sem o Codis do outro lado o processo encerra."""
55
+ line = json.dumps(message, separators=(",", ":")) + "\n"
56
+ try:
57
+ with self._out_lock:
58
+ self._out.write(line)
59
+ self._out.flush()
60
+ except (OSError, ValueError):
61
+ os._exit(0)
62
+
63
+ def handle(self, message: dict[str, Any]) -> bool:
64
+ """Trata um comando. Retorna ``False`` quando o processo deve encerrar."""
65
+ cmd = message.get("cmd")
66
+ try:
67
+ if cmd == "play":
68
+ self._play(message)
69
+ elif cmd == "stop":
70
+ self._stop_current()
71
+ self.emit(ev="stopped", seq=message.get("seq"))
72
+ elif cmd == "quit":
73
+ self._stop_current()
74
+ return False
75
+ elif cmd in ("pause", "seek", "volume", "eq"):
76
+ self._control(cmd, message)
77
+ except Exception:
78
+ logger.exception("comando %r falhou", cmd)
79
+ return True
80
+
81
+ def tick(self) -> None:
82
+ """Informa posição e fim da faixa; parado, só emite um sinal de vida."""
83
+ now = time.monotonic()
84
+ player, kind, play_id = self._player, self._kind, self._play_id
85
+ if player is None:
86
+ if now - self._last_signal >= _IDLE_SIGNAL:
87
+ self._last_signal = now
88
+ self.emit(ev="tick")
89
+ return
90
+ self._last_signal = now
91
+ ended = False
92
+ try:
93
+ if kind == "vlc":
94
+ position = player.get_time() / 1000.0
95
+ duration = player.get_length() / 1000.0
96
+ vlc = self._media.vlc
97
+ ended = player.get_state() in (vlc.State.Ended, vlc.State.Error)
98
+ else:
99
+ position = player.time_pos or 0.0
100
+ duration = player.duration or 0.0
101
+ except Exception:
102
+ return
103
+ self.emit(ev="pos", id=play_id, pos=position, dur=duration)
104
+ if ended and not self._ended_sent:
105
+ self._ended_sent = True
106
+ self.emit(ev="ended", id=play_id)
107
+
108
+ def _play(self, message: dict[str, Any]) -> None:
109
+ self._stop_current()
110
+ play_id = int(message["id"])
111
+ self._play_id = play_id
112
+ self._stopping = False
113
+ self._ended_sent = False
114
+ self._seeked_at = 0.0
115
+ try:
116
+ if self._media.MPV_AVAILABLE:
117
+ self._play_mpv(message)
118
+ elif self._media.VLC_AVAILABLE:
119
+ self._play_vlc(message)
120
+ else:
121
+ raise RuntimeError("nenhum backend de mídia disponível")
122
+ except Exception as exc:
123
+ logger.exception("falha ao iniciar a reprodução")
124
+ self._stop_current()
125
+ self.emit(ev="error", id=play_id, msg=str(exc))
126
+ return
127
+ self.emit(ev="started", id=play_id, backend=self._kind)
128
+
129
+ def _play_mpv(self, message: dict[str, Any]) -> None:
130
+ media = self._media
131
+ url = message["url"]
132
+ wid = message.get("wid")
133
+ play_id = self._play_id
134
+ ytdlp = bool(message.get("ytdlp"))
135
+
136
+ import locale
137
+
138
+ with contextlib.suppress(Exception):
139
+ locale.setlocale(locale.LC_NUMERIC, "C")
140
+ kwargs: dict[str, Any] = {
141
+ "ytdl": ytdlp,
142
+ "video": "auto" if wid is not None else "no",
143
+ "input_default_bindings": False,
144
+ "input_vo_keyboard": False,
145
+ "osc": False,
146
+ "log_handler": lambda level, component, text: logger.debug(
147
+ "[mpv/%s] %s", component, text),
148
+ "loglevel": "error",
149
+ }
150
+ if wid is not None:
151
+ kwargs["wid"] = str(wid)
152
+ if ytdlp and media._is_youtube(url):
153
+ kwargs["ytdl_format"] = "bestvideo[height<=?1080]+bestaudio/best"
154
+ forced_ao = os.environ.get("CODIS_MEDIA_AO")
155
+ if forced_ao:
156
+ kwargs["ao"] = forced_ao
157
+ player = media.mpv.MPV(**kwargs)
158
+ self._player, self._kind = player, "mpv"
159
+
160
+ @player.property_observer("pause")
161
+ def _on_pause(_name: str, value: Any) -> None:
162
+ if value is not None and play_id == self._play_id and not self._stopping:
163
+ self.emit(ev="paused", id=play_id, value=bool(value))
164
+
165
+ @player.event_callback("end-file")
166
+ def _on_end(_event: Any) -> None:
167
+ if play_id == self._play_id and not self._stopping and not self._ended_sent:
168
+ self._ended_sent = True
169
+ self.emit(ev="ended", id=play_id)
170
+
171
+ with contextlib.suppress(Exception):
172
+ player.volume = int(message.get("volume", 70))
173
+ self._apply_eq(message.get("gains"), message.get("enabled"))
174
+ start = float(message.get("start") or 0.0)
175
+ if start > 0:
176
+ with contextlib.suppress(Exception):
177
+ player.start = f"{start:.3f}"
178
+ if message.get("paused"):
179
+ with contextlib.suppress(Exception):
180
+ player.pause = True
181
+ player.play(url)
182
+
183
+ def _play_vlc(self, message: dict[str, Any]) -> None:
184
+ media = self._media
185
+ vlc = media.vlc
186
+ url = message["url"]
187
+ wid = message.get("wid")
188
+ flags = ["--quiet"]
189
+ if wid is None:
190
+ flags += ["--no-video", "--no-xlib"]
191
+ instance = vlc.Instance(*flags)
192
+ player = instance.media_player_new()
193
+ self._player, self._kind = player, "vlc"
194
+ if wid is not None:
195
+ with contextlib.suppress(AttributeError, RuntimeError):
196
+ if sys.platform == "win32":
197
+ player.set_hwnd(wid)
198
+ elif sys.platform == "darwin":
199
+ player.set_nsobject(wid)
200
+ else:
201
+ player.set_xwindow(wid)
202
+ item = instance.media_new(url)
203
+ if media._is_youtube(url):
204
+ item.add_option(":network-caching=1500")
205
+ start = float(message.get("start") or 0.0)
206
+ if start > 0:
207
+ item.add_option(f":start-time={start:.3f}")
208
+ player.set_media(item)
209
+ with contextlib.suppress(AttributeError, RuntimeError):
210
+ item.release()
211
+ with contextlib.suppress(AttributeError, RuntimeError):
212
+ player.audio_set_volume(int(message.get("volume", 70)))
213
+ self._apply_eq(message.get("gains"), message.get("enabled"))
214
+ player.play()
215
+ if message.get("paused"):
216
+ with contextlib.suppress(AttributeError, RuntimeError):
217
+ player.set_pause(1)
218
+
219
+ def _control(self, cmd: str, message: dict[str, Any]) -> None:
220
+ player, kind = self._player, self._kind
221
+ if player is None or message.get("id") != self._play_id:
222
+ return
223
+ if cmd == "pause":
224
+ paused = bool(message.get("paused"))
225
+ if kind == "mpv":
226
+ player.pause = paused
227
+ else:
228
+ player.set_pause(1 if paused else 0)
229
+ elif cmd == "seek":
230
+ position = float(message.get("pos", 0.0))
231
+ if kind == "mpv":
232
+ player.seek(position, reference="absolute")
233
+ elif not self._media._vlc_is_opening(player):
234
+ self._seeked_at = time.monotonic()
235
+ player.set_time(int(position * 1000))
236
+ elif cmd == "volume":
237
+ value = int(message.get("value", 70))
238
+ if kind == "mpv":
239
+ player.volume = value
240
+ else:
241
+ player.audio_set_volume(value)
242
+ elif cmd == "eq":
243
+ self._apply_eq(message.get("gains"), message.get("enabled"))
244
+
245
+ def _apply_eq(self, gains: Any, enabled: Any) -> None:
246
+ from src.ui.zen_audio import apply_vlc_equalizer, clamp_gains, mpv_af_string
247
+
248
+ player = self._player
249
+ if player is None:
250
+ return
251
+ values = clamp_gains(gains)
252
+ on = bool(enabled)
253
+ if self._kind == "mpv":
254
+ with contextlib.suppress(Exception):
255
+ player.af = mpv_af_string(values) if on else ""
256
+ elif self._kind == "vlc":
257
+ apply_vlc_equalizer(player, values, on)
258
+
259
+ def _stop_current(self) -> None:
260
+ player, kind = self._player, self._kind
261
+ self._player = None
262
+ self._kind = None
263
+ self._stopping = True
264
+ if player is None:
265
+ return
266
+ try:
267
+ if kind == "mpv":
268
+ with contextlib.suppress(Exception):
269
+ player.terminate()
270
+ else:
271
+ self._media._stop_vlc(player, None, True, self._seeked_at)
272
+ except Exception:
273
+ logger.exception("falha ao encerrar o player")
274
+ self._seeked_at = 0.0
275
+
276
+
277
+ def _read_commands(commands: queue.Queue) -> None:
278
+ """Lê comandos JSON da entrada padrão; o fim da entrada significa Codis encerrado."""
279
+ try:
280
+ for raw in sys.stdin.buffer:
281
+ try:
282
+ message = json.loads(raw)
283
+ except ValueError:
284
+ continue
285
+ if isinstance(message, dict):
286
+ commands.put(message)
287
+ except (OSError, ValueError):
288
+ pass
289
+ commands.put(_EOF)
290
+
291
+
292
+ def main() -> int:
293
+ """Laço do processo de mídia. Retorna o código de saída."""
294
+ # O protocolo usa uma cópia do stdout original; qualquer escrita das
295
+ # bibliotecas nativas no stdout vai para o stderr.
296
+ out = os.fdopen(os.dup(1), "w", encoding="utf-8", buffering=1, newline="\n")
297
+ os.dup2(2, 1)
298
+ sys.stdout = sys.stderr
299
+ logging.basicConfig(
300
+ level=logging.WARNING, stream=sys.stderr,
301
+ format="%(levelname)s %(name)s - %(message)s")
302
+ with contextlib.suppress(OSError, ValueError, AttributeError, RuntimeError):
303
+ faulthandler.enable(file=sys.stderr, all_threads=True)
304
+ with contextlib.suppress(ValueError, OSError):
305
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
306
+
307
+ from src.ui import zen_media
308
+
309
+ host = _Host(out, zen_media)
310
+ host.emit(
311
+ ev="hello", pid=os.getpid(),
312
+ mpv=zen_media.MPV_AVAILABLE, vlc=zen_media.VLC_AVAILABLE)
313
+
314
+ commands: queue.Queue = queue.Queue()
315
+ threading.Thread(target=_read_commands, args=(commands,), daemon=True).start()
316
+ while True:
317
+ try:
318
+ message = commands.get(timeout=_TICK)
319
+ except queue.Empty:
320
+ host.tick()
321
+ continue
322
+ if message is _EOF:
323
+ os._exit(0)
324
+ if not host.handle(message):
325
+ return 0
326
+
327
+
328
+ if __name__ == "__main__":
329
+ sys.exit(main())