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
src/ui/window_embed.py ADDED
@@ -0,0 +1,1500 @@
1
+ """Codis - incorporação (reparentamento) de janelas nativas de outros processos.
2
+
3
+ Este módulo permite hospedar, dentro de um ``tk.Frame``, a janela *nativa* de
4
+ um aplicativo externo (ex.: um motor de DOOM), como se ela fosse um widget do
5
+ editor:
6
+
7
+ * **Windows** - a janela top-level do processo filho é localizada por PID
8
+ (``EnumWindows``), convertida em ``WS_CHILD`` (sem moldura/legenda) e
9
+ reparentada com ``SetParent`` ao HWND do frame hospedeiro.
10
+ * **Linux/BSD (X11)** - a janela do cliente é localizada por ``_NET_WM_PID`` e
11
+ reparentada com ``XReparentWindow`` ao XID do frame hospedeiro.
12
+ * **Outras plataformas / Wayland puro** - :func:`get_backend` retorna ``None``
13
+ e o chamador deve cair para uma janela externa.
14
+
15
+ Arquitetura::
16
+
17
+ EmbeddedAppPanel (tk.Frame) ── usa ──▶ WindowBackend (Protocol)
18
+ │ ciclo de vida do processo ├─ Win32Backend ──▶ Win32Calls (ctypes)
19
+ │ polling não-bloqueante (after) └─ X11Backend ──▶ libX11 (ctypes)
20
+ └─ barra de ferramentas + console de boot
21
+
22
+ Toda a interação com Tk acontece na thread principal (nenhuma thread auxiliar
23
+ chama ``after``); o acompanhamento do processo é feito por *polling* via
24
+ ``after``.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import ctypes
31
+ import ctypes.util
32
+ import logging
33
+ import os
34
+ import subprocess
35
+ import sys
36
+ import time
37
+ import tkinter as tk
38
+ from collections.abc import Callable, Iterator, Sequence
39
+ from dataclasses import dataclass
40
+ from pathlib import Path
41
+ from typing import IO, Any, Protocol
42
+
43
+ logger = logging.getLogger("Codis.Embed")
44
+
45
+ __all__ = [
46
+ "WindowInfo",
47
+ "EmbedError",
48
+ "EmbedLabels",
49
+ "EmbedTheme",
50
+ "EmbeddedAppPanel",
51
+ "WindowBackend",
52
+ "Win32Backend",
53
+ "X11Backend",
54
+ "get_backend",
55
+ "EXIT_HOTKEY_TEXT",
56
+ ]
57
+
58
+ EXIT_HOTKEY_TEXT = "Ctrl+Shift+F12"
59
+
60
+ _MIN_WINDOW_W = 200
61
+ _MIN_WINDOW_H = 150
62
+
63
+ _TICK_MS = 80
64
+
65
+
66
+ class EmbedError(RuntimeError):
67
+ """Falha ao localizar, reparentar ou controlar a janela de um processo."""
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class WindowInfo:
72
+ """Janela top-level de outro programa, candidata a ser incorporada."""
73
+
74
+ handle: int
75
+ pid: int
76
+ title: str
77
+ exe: str
78
+ size: tuple[int, int] = (0, 0)
79
+
80
+
81
+ class WindowBackend(Protocol):
82
+ """Operações de janela nativa necessárias ao :class:`EmbeddedAppPanel`.
83
+
84
+ ``handle`` é um HWND (Windows) ou XID (X11); ``host`` é o identificador
85
+ nativo do widget Tk que receberá a janela (``widget.winfo_id()``).
86
+ """
87
+
88
+ name: str
89
+
90
+ def find_window(self, pid: int) -> int | None:
91
+ """Retorna a janela principal do processo ``pid`` (ou ``None``)."""
92
+
93
+ def find_window_in(self, pids: Sequence[int]) -> int | None:
94
+ """Como :meth:`find_window`, mas aceita vários PIDs (árvore de processos)."""
95
+
96
+ def list_windows(self) -> list[WindowInfo]:
97
+ """Lista janelas top-level visíveis e incorporáveis (para o seletor)."""
98
+
99
+ def is_alive(self, handle: int) -> bool:
100
+ """Indica se a janela ainda existe."""
101
+
102
+ def is_embedded(self, handle: int, host: int) -> bool:
103
+ """Indica se a janela ainda é filha de ``host``."""
104
+
105
+ def embed(self, handle: int, host: int, width: int, height: int) -> None:
106
+ """Reparenta a janela em ``host`` com o tamanho dado."""
107
+
108
+ def resize(self, handle: int, width: int, height: int) -> None:
109
+ """Redimensiona a janela embutida."""
110
+
111
+ def size_of(self, handle: int) -> tuple[int, int] | None:
112
+ """Tamanho atual (largura, altura) da janela embutida."""
113
+
114
+ def focus(self, handle: int) -> None:
115
+ """Dá o foco de teclado à janela embutida."""
116
+
117
+ def detach(self, handle: int, *, restore: bool = False) -> None:
118
+ """Devolve a janela ao desktop (desfaz o reparentamento).
119
+
120
+ ``restore=True`` (programas adotados, que continuam rodando) mantém a
121
+ janela visível e na posição/tamanho originais; sem isso ela é escondida.
122
+ """
123
+
124
+ def request_close(self, handle: int) -> None:
125
+ """Pede educadamente que o aplicativo feche (WM_CLOSE)."""
126
+
127
+ def release_pointer(self) -> None:
128
+ """Libera qualquer captura/confinamento do ponteiro do mouse."""
129
+
130
+ def exit_hotkey_down(self, pids: Sequence[int]) -> bool:
131
+ """Indica se o atalho global de saída está pressionado."""
132
+
133
+ def close(self) -> None:
134
+ """Libera recursos do backend."""
135
+
136
+
137
+ _GWL_STYLE = -16
138
+ _GWL_EXSTYLE = -20
139
+ _WS_POPUP = 0x80000000
140
+ _WS_CHILD = 0x40000000
141
+ _WS_MINIMIZE = 0x20000000
142
+ _WS_VISIBLE = 0x10000000
143
+ _WS_CLIPSIBLINGS = 0x04000000
144
+ _WS_CLIPCHILDREN = 0x02000000
145
+ _WS_MAXIMIZE = 0x01000000
146
+ _WS_BORDER = 0x00800000
147
+ _WS_DLGFRAME = 0x00400000
148
+ _WS_SYSMENU = 0x00080000
149
+ _WS_THICKFRAME = 0x00040000
150
+ _WS_MINIMIZEBOX = 0x00020000
151
+ _WS_MAXIMIZEBOX = 0x00010000
152
+
153
+ _WS_EX_DLGMODALFRAME = 0x00000001
154
+ _WS_EX_TOPMOST = 0x00000008
155
+ _WS_EX_TOOLWINDOW = 0x00000080
156
+ _WS_EX_WINDOWEDGE = 0x00000100
157
+ _WS_EX_CLIENTEDGE = 0x00000200
158
+ _WS_EX_STATICEDGE = 0x00020000
159
+ _WS_EX_APPWINDOW = 0x00040000
160
+
161
+ _STRIP_STYLE = (
162
+ _WS_POPUP
163
+ | _WS_MINIMIZE
164
+ | _WS_MAXIMIZE
165
+ | _WS_BORDER
166
+ | _WS_DLGFRAME
167
+ | _WS_SYSMENU
168
+ | _WS_THICKFRAME
169
+ | _WS_MINIMIZEBOX
170
+ | _WS_MAXIMIZEBOX
171
+ )
172
+ _ADD_STYLE = _WS_CHILD | _WS_VISIBLE | _WS_CLIPSIBLINGS | _WS_CLIPCHILDREN
173
+ _STRIP_EXSTYLE = (
174
+ _WS_EX_DLGMODALFRAME
175
+ | _WS_EX_TOPMOST
176
+ | _WS_EX_TOOLWINDOW
177
+ | _WS_EX_WINDOWEDGE
178
+ | _WS_EX_CLIENTEDGE
179
+ | _WS_EX_STATICEDGE
180
+ | _WS_EX_APPWINDOW
181
+ )
182
+
183
+ _SWP_NOZORDER = 0x0004
184
+ _SWP_NOACTIVATE = 0x0010
185
+ _SWP_FRAMECHANGED = 0x0020
186
+ _SWP_SHOWWINDOW = 0x0040
187
+ _SWP_HIDEWINDOW = 0x0080
188
+
189
+ _VK_SHIFT = 0x10
190
+ _VK_CONTROL = 0x11
191
+ _VK_F12 = 0x7B
192
+
193
+ _IGNORED_CLASSES = frozenset(
194
+ {
195
+ "IME",
196
+ "MSCTFIME UI",
197
+ "ConsoleWindowClass",
198
+ "CASCADIA_HOSTING_WINDOW_CLASS",
199
+ "GDI+ Hook Window Class",
200
+ "tooltips_class32",
201
+ "#32770_hidden",
202
+ }
203
+ )
204
+ _IGNORED_CLASS_PREFIXES = ("SDL_Helper", "SDL_HelperWindow")
205
+
206
+
207
+ def _to_long_ptr(value: int) -> int:
208
+ """Converte um inteiro sem sinal de 32 bits para LONG_PTR (com sinal) válido."""
209
+ bits = ctypes.sizeof(ctypes.c_void_p) * 8
210
+ value &= (1 << bits) - 1
211
+ if value >= 1 << (bits - 1):
212
+ value -= 1 << bits
213
+ return value
214
+
215
+
216
+ class Win32Calls:
217
+ """Camada fina sobre ``user32``/``kernel32`` com protótipos ctypes corretos.
218
+
219
+ Definir ``argtypes``/``restype`` é essencial: sem isso o ctypes assume
220
+ ``int`` de 32 bits como retorno e **trunca HWNDs de 64 bits**.
221
+ Instanciar apenas no Windows.
222
+ """
223
+
224
+ _GW_OWNER = 4
225
+ _WM_CLOSE = 0x0010
226
+ _DPI_HOSTING_BEHAVIOR_MIXED = 1
227
+
228
+ def __init__(self) -> None:
229
+ """Carrega user32/kernel32 e declara os protótipos das funções usadas."""
230
+ if os.name != "nt": # pragma: no cover
231
+ raise EmbedError("Win32Calls só está disponível no Windows")
232
+ from ctypes import wintypes as wt
233
+
234
+ self._wt = wt
235
+ win_dll: Any = ctypes.WinDLL # type: ignore[attr-defined,unused-ignore]
236
+ u = win_dll("user32", use_last_error=True)
237
+ k = win_dll("kernel32", use_last_error=True)
238
+ self._u, self._k = u, k
239
+ hwnd, lp, wp = ctypes.c_void_p, ctypes.c_ssize_t, ctypes.c_size_t
240
+
241
+ winfunctype: Any = ctypes.WINFUNCTYPE # type: ignore[attr-defined,unused-ignore]
242
+ self._enum_proc = winfunctype(wt.BOOL, hwnd, ctypes.c_ssize_t)
243
+ u.EnumWindows.argtypes = [self._enum_proc, ctypes.c_ssize_t]
244
+ u.EnumWindows.restype = wt.BOOL
245
+ u.IsWindow.argtypes = [hwnd]
246
+ u.IsWindow.restype = wt.BOOL
247
+ u.IsWindowVisible.argtypes = [hwnd]
248
+ u.IsWindowVisible.restype = wt.BOOL
249
+ u.GetWindow.argtypes = [hwnd, wt.UINT]
250
+ u.GetWindow.restype = hwnd
251
+ u.GetParent.argtypes = [hwnd]
252
+ u.GetParent.restype = hwnd
253
+ u.GetWindowThreadProcessId.argtypes = [hwnd, ctypes.POINTER(wt.DWORD)]
254
+ u.GetWindowThreadProcessId.restype = wt.DWORD
255
+ u.GetClassNameW.argtypes = [hwnd, wt.LPWSTR, ctypes.c_int]
256
+ u.GetClassNameW.restype = ctypes.c_int
257
+ u.GetWindowRect.argtypes = [hwnd, ctypes.POINTER(wt.RECT)]
258
+ u.GetWindowRect.restype = wt.BOOL
259
+ u.GetClientRect.argtypes = [hwnd, ctypes.POINTER(wt.RECT)]
260
+ u.GetClientRect.restype = wt.BOOL
261
+ u.GetWindowTextLengthW.argtypes = [hwnd]
262
+ u.GetWindowTextLengthW.restype = ctypes.c_int
263
+ u.GetWindowTextW.argtypes = [hwnd, wt.LPWSTR, ctypes.c_int]
264
+ u.GetWindowTextW.restype = ctypes.c_int
265
+ k.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD]
266
+ k.OpenProcess.restype = ctypes.c_void_p
267
+ k.CloseHandle.argtypes = [ctypes.c_void_p]
268
+ k.CloseHandle.restype = wt.BOOL
269
+ k.QueryFullProcessImageNameW.argtypes = [
270
+ ctypes.c_void_p, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD),
271
+ ]
272
+ k.QueryFullProcessImageNameW.restype = wt.BOOL
273
+ getter = getattr(u, "GetWindowLongPtrW", None) or u.GetWindowLongW
274
+ setter = getattr(u, "SetWindowLongPtrW", None) or u.SetWindowLongW
275
+ getter.argtypes = [hwnd, ctypes.c_int]
276
+ getter.restype = lp
277
+ setter.argtypes = [hwnd, ctypes.c_int, lp]
278
+ setter.restype = lp
279
+ self._get_long, self._set_long = getter, setter
280
+ u.SetParent.argtypes = [hwnd, hwnd]
281
+ u.SetParent.restype = hwnd
282
+ u.SetWindowPos.argtypes = [
283
+ hwnd, hwnd, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, wt.UINT,
284
+ ]
285
+ u.SetWindowPos.restype = wt.BOOL
286
+ u.SetFocus.argtypes = [hwnd]
287
+ u.SetFocus.restype = hwnd
288
+ u.AttachThreadInput.argtypes = [wt.DWORD, wt.DWORD, wt.BOOL]
289
+ u.AttachThreadInput.restype = wt.BOOL
290
+ u.PostMessageW.argtypes = [hwnd, wt.UINT, wp, lp]
291
+ u.PostMessageW.restype = wt.BOOL
292
+ u.ClipCursor.argtypes = [ctypes.POINTER(wt.RECT)]
293
+ u.ClipCursor.restype = wt.BOOL
294
+ u.GetAsyncKeyState.argtypes = [ctypes.c_int]
295
+ u.GetAsyncKeyState.restype = ctypes.c_short
296
+ u.GetForegroundWindow.argtypes = []
297
+ u.GetForegroundWindow.restype = hwnd
298
+ k.GetCurrentThreadId.argtypes = []
299
+ k.GetCurrentThreadId.restype = wt.DWORD
300
+ k.SetLastError.argtypes = [wt.DWORD]
301
+ k.SetLastError.restype = None
302
+
303
+ def top_level_windows(self) -> list[int]:
304
+ """Lista os HWNDs das janelas top-level da área de trabalho."""
305
+ found: list[int] = []
306
+
307
+ def _cb(hwnd: int | None, _lparam: int) -> bool:
308
+ if hwnd:
309
+ found.append(int(hwnd))
310
+ return True
311
+
312
+ cb = self._enum_proc(_cb)
313
+ self._u.EnumWindows(cb, 0)
314
+ return found
315
+
316
+ def is_window(self, hwnd: int) -> bool:
317
+ """True se ``hwnd`` ainda é uma janela válida."""
318
+ return bool(self._u.IsWindow(hwnd))
319
+
320
+ def is_visible(self, hwnd: int) -> bool:
321
+ """True se a janela tem o estilo WS_VISIBLE."""
322
+ return bool(self._u.IsWindowVisible(hwnd))
323
+
324
+ def owner(self, hwnd: int) -> int:
325
+ """HWND do proprietário (0 se não houver)."""
326
+ return int(self._u.GetWindow(hwnd, self._GW_OWNER) or 0)
327
+
328
+ def parent(self, hwnd: int) -> int:
329
+ """HWND do pai (0 para janelas top-level)."""
330
+ return int(self._u.GetParent(hwnd) or 0)
331
+
332
+ def pid_of(self, hwnd: int) -> int:
333
+ """PID do processo dono da janela."""
334
+ pid = self._wt.DWORD(0)
335
+ self._u.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
336
+ return int(pid.value)
337
+
338
+ def class_name(self, hwnd: int) -> str:
339
+ """Nome da classe da janela."""
340
+ buf = ctypes.create_unicode_buffer(256)
341
+ self._u.GetClassNameW(hwnd, buf, 256)
342
+ return buf.value
343
+
344
+ def rect_size(self, hwnd: int) -> tuple[int, int]:
345
+ """(largura, altura) do retângulo externo da janela."""
346
+ r = self._wt.RECT()
347
+ self._u.GetWindowRect(hwnd, ctypes.byref(r))
348
+ return int(r.right - r.left), int(r.bottom - r.top)
349
+
350
+ def window_rect(self, hwnd: int) -> tuple[int, int, int, int]:
351
+ """(esquerda, topo, direita, base) em coordenadas de tela."""
352
+ r = self._wt.RECT()
353
+ self._u.GetWindowRect(hwnd, ctypes.byref(r))
354
+ return int(r.left), int(r.top), int(r.right), int(r.bottom)
355
+
356
+ def window_title(self, hwnd: int) -> str:
357
+ """Título (legenda) da janela."""
358
+ n = int(self._u.GetWindowTextLengthW(hwnd))
359
+ if n <= 0:
360
+ return ""
361
+ buf = ctypes.create_unicode_buffer(n + 1)
362
+ self._u.GetWindowTextW(hwnd, buf, n + 1)
363
+ return buf.value
364
+
365
+ def process_image(self, pid: int) -> str:
366
+ """Caminho completo do executável do processo (vazio se sem acesso)."""
367
+ h = self._k.OpenProcess(0x1000, False, pid)
368
+ if not h:
369
+ return ""
370
+ try:
371
+ size = self._wt.DWORD(1024)
372
+ buf = ctypes.create_unicode_buffer(1024)
373
+ ok = self._k.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(size))
374
+ return buf.value if ok else ""
375
+ finally:
376
+ self._k.CloseHandle(h)
377
+
378
+ def is_cloaked(self, hwnd: int) -> bool:
379
+ """True para janelas UWP/virtual-desktop "escondidas" (DWM cloaked)."""
380
+ try:
381
+ dwm = ctypes.WinDLL("dwmapi") # type: ignore[attr-defined]
382
+ val = ctypes.c_int(0)
383
+ dwm.DwmGetWindowAttribute(
384
+ ctypes.c_void_p(hwnd), 14, ctypes.byref(val), ctypes.sizeof(val)
385
+ )
386
+ return bool(val.value)
387
+ except (OSError, AttributeError):
388
+ return False
389
+
390
+ def get_style(self, hwnd: int) -> int:
391
+ """Estilo (WS_*) da janela, como inteiro sem sinal de 32 bits."""
392
+ return int(self._get_long(hwnd, _GWL_STYLE)) & 0xFFFFFFFF
393
+
394
+ def set_style(self, hwnd: int, value: int) -> None:
395
+ """Define o estilo (WS_*) da janela."""
396
+ self._set_long(hwnd, _GWL_STYLE, _to_long_ptr(value))
397
+
398
+ def get_exstyle(self, hwnd: int) -> int:
399
+ """Estilo estendido (WS_EX_*) da janela."""
400
+ return int(self._get_long(hwnd, _GWL_EXSTYLE)) & 0xFFFFFFFF
401
+
402
+ def set_exstyle(self, hwnd: int, value: int) -> None:
403
+ """Define o estilo estendido (WS_EX_*) da janela."""
404
+ self._set_long(hwnd, _GWL_EXSTYLE, _to_long_ptr(value))
405
+
406
+ def set_parent(self, hwnd: int, parent: int) -> None:
407
+ """Chama ``SetParent`` zerando o último erro antes (checar via ``last_error``)."""
408
+ self._k.SetLastError(0)
409
+ self._u.SetParent(hwnd, parent or None)
410
+
411
+ def last_error(self) -> int:
412
+ """Último código de erro Win32 da thread."""
413
+ return int(getattr(ctypes, "get_last_error", lambda: 0)())
414
+
415
+ @staticmethod
416
+ def format_error(code: int) -> str:
417
+ """Mensagem legível para um código de erro Win32."""
418
+ fmt: Any = ctypes.FormatError # type: ignore[attr-defined,unused-ignore]
419
+ return str(fmt(code)).strip()
420
+
421
+ def set_pos(self, hwnd: int, x: int, y: int, w: int, h: int, flags: int) -> None:
422
+ """``SetWindowPos`` sem alterar a ordem Z."""
423
+ self._u.SetWindowPos(hwnd, None, x, y, w, h, flags)
424
+
425
+ def set_focus(self, hwnd: int) -> bool:
426
+ """Dá foco à janela; usa ``AttachThreadInput`` como último recurso."""
427
+ if self._u.SetFocus(hwnd):
428
+ return True
429
+ target = self._u.GetWindowThreadProcessId(hwnd, None)
430
+ me = self._k.GetCurrentThreadId()
431
+ if not target or target == me:
432
+ return False
433
+ self._u.AttachThreadInput(me, target, True)
434
+ try:
435
+ return bool(self._u.SetFocus(hwnd))
436
+ finally:
437
+ self._u.AttachThreadInput(me, target, False)
438
+
439
+ def post_close(self, hwnd: int) -> None:
440
+ """Posta ``WM_CLOSE`` (fechamento gracioso)."""
441
+ self._u.PostMessageW(hwnd, self._WM_CLOSE, 0, 0)
442
+
443
+ def release_cursor_clip(self) -> None:
444
+ """Remove qualquer ``ClipCursor`` ativo (jogos costumam confinar o mouse)."""
445
+ self._u.ClipCursor(None)
446
+
447
+ def key_down(self, vk: int) -> bool:
448
+ """True se a tecla virtual ``vk`` está pressionada agora (global)."""
449
+ return bool(self._u.GetAsyncKeyState(vk) & 0x8000)
450
+
451
+ def foreground_pid(self) -> int:
452
+ """PID do processo dono da janela em primeiro plano."""
453
+ fg = self._u.GetForegroundWindow()
454
+ return self.pid_of(int(fg)) if fg else 0
455
+
456
+ def enable_mixed_dpi_hosting(self) -> None:
457
+ """Permite hospedar janelas de outro DPI-awareness (Windows 10 1803+)."""
458
+ fn = getattr(self._u, "SetThreadDpiHostingBehavior", None)
459
+ if fn is None:
460
+ return
461
+ fn.argtypes = [ctypes.c_int]
462
+ fn.restype = ctypes.c_int
463
+ fn(self._DPI_HOSTING_BEHAVIOR_MIXED)
464
+
465
+
466
+ @dataclass
467
+ class _SavedWin32State:
468
+ """Estado original de uma janela, para restaurar ao desanexar."""
469
+
470
+ style: int
471
+ exstyle: int
472
+ rect: tuple[int, int, int, int] | None = None
473
+
474
+
475
+ class Win32Backend:
476
+ """Backend de reparentamento para Windows (``SetParent`` + ``WS_CHILD``).
477
+
478
+ Args:
479
+ calls: Implementação de :class:`Win32Calls` (injetável em testes).
480
+ """
481
+
482
+ name = "win32"
483
+
484
+ def __init__(self, calls: Any | None = None) -> None:
485
+ """Cria o backend; ``calls`` default usa ``user32`` real."""
486
+ self._c = calls if calls is not None else Win32Calls()
487
+ self._saved: dict[int, _SavedWin32State] = {}
488
+
489
+ def find_window(self, pid: int) -> int | None:
490
+ """Escolhe a melhor janela top-level do processo ``pid``.
491
+
492
+ Critérios: mesmo PID, sem proprietário, não ``TOOLWINDOW``, classe fora
493
+ da lista de auxiliares e tamanho mínimo; prefere janelas visíveis e,
494
+ entre elas, a de maior área.
495
+ """
496
+ c = self._c
497
+ best: int | None = None
498
+ best_score = (-1, -1)
499
+ for hwnd in c.top_level_windows():
500
+ if c.pid_of(hwnd) != pid or c.owner(hwnd):
501
+ continue
502
+ cls = c.class_name(hwnd)
503
+ if cls in _IGNORED_CLASSES or cls.startswith(_IGNORED_CLASS_PREFIXES):
504
+ continue
505
+ if c.get_exstyle(hwnd) & _WS_EX_TOOLWINDOW:
506
+ continue
507
+ w, h = c.rect_size(hwnd)
508
+ if w < _MIN_WINDOW_W or h < _MIN_WINDOW_H:
509
+ continue
510
+ score = (1 if c.is_visible(hwnd) else 0, w * h)
511
+ if score > best_score:
512
+ best, best_score = hwnd, score
513
+ return best
514
+
515
+ def _usable(self, hwnd: int) -> tuple[int, int] | None:
516
+ """Tamanho da janela se ela é "principal" e incorporável; senão ``None``."""
517
+ c = self._c
518
+ if c.owner(hwnd):
519
+ return None
520
+ cls = c.class_name(hwnd)
521
+ if cls in _IGNORED_CLASSES or cls.startswith(_IGNORED_CLASS_PREFIXES):
522
+ return None
523
+ if c.get_exstyle(hwnd) & _WS_EX_TOOLWINDOW:
524
+ return None
525
+ w, h = c.rect_size(hwnd)
526
+ if w < _MIN_WINDOW_W or h < _MIN_WINDOW_H:
527
+ return None
528
+ return w, h
529
+
530
+ def find_window_in(self, pids: Sequence[int]) -> int | None:
531
+ """Melhor janela entre as de qualquer um dos ``pids`` (visível, maior área)."""
532
+ wanted = set(pids)
533
+ best: int | None = None
534
+ best_score = (-1, -1)
535
+ for hwnd in self._c.top_level_windows():
536
+ if self._c.pid_of(hwnd) not in wanted:
537
+ continue
538
+ size = self._usable(hwnd)
539
+ if size is None:
540
+ continue
541
+ score = (1 if self._c.is_visible(hwnd) else 0, size[0] * size[1])
542
+ if score > best_score:
543
+ best, best_score = hwnd, score
544
+ return best
545
+
546
+ def list_windows(self) -> list[WindowInfo]:
547
+ """Janelas visíveis com título, para o seletor "adotar janela"."""
548
+ c, out = self._c, []
549
+ for hwnd in c.top_level_windows():
550
+ if not c.is_visible(hwnd):
551
+ continue
552
+ size = self._usable(hwnd)
553
+ if size is None:
554
+ continue
555
+ title = c.window_title(hwnd) if hasattr(c, "window_title") else ""
556
+ if not title:
557
+ continue
558
+ if hasattr(c, "is_cloaked") and c.is_cloaked(hwnd):
559
+ continue
560
+ pid = c.pid_of(hwnd)
561
+ image = c.process_image(pid) if hasattr(c, "process_image") else ""
562
+ out.append(WindowInfo(hwnd, pid, title, image.replace("\\", "/").rsplit("/", 1)[-1], size))
563
+ return out
564
+
565
+ def is_alive(self, handle: int) -> bool:
566
+ """Indica se o HWND ainda existe."""
567
+ return bool(self._c.is_window(handle))
568
+
569
+ def is_embedded(self, handle: int, host: int) -> bool:
570
+ """Indica se ``handle`` ainda é filho direto de ``host``."""
571
+ return self._c.parent(handle) == host
572
+
573
+ def embed(self, handle: int, host: int, width: int, height: int) -> None:
574
+ """Transforma ``handle`` em filho de ``host``.
575
+
576
+ Ordem exigida pela documentação do ``SetParent``: primeiro limpar
577
+ ``WS_POPUP``/moldura e definir ``WS_CHILD``, **depois** reparentar.
578
+ O sucesso é verificado com ``GetParent`` (o valor de retorno do
579
+ ``SetParent`` é ambíguo para janelas top-level).
580
+ """
581
+ c = self._c
582
+ style = c.get_style(handle)
583
+ exstyle = c.get_exstyle(handle)
584
+ rect_fn = getattr(c, "window_rect", None)
585
+ rect = rect_fn(handle) if rect_fn is not None else None
586
+ self._saved.setdefault(handle, _SavedWin32State(style, exstyle, rect))
587
+
588
+ c.set_style(handle, (style & ~_STRIP_STYLE) | _ADD_STYLE)
589
+ c.set_exstyle(handle, exstyle & ~_STRIP_EXSTYLE)
590
+
591
+ with contextlib.suppress(AttributeError, OSError):
592
+ c.enable_mixed_dpi_hosting()
593
+
594
+ c.set_parent(handle, host)
595
+ if c.parent(handle) != host:
596
+ code = c.last_error()
597
+ c.set_style(handle, style)
598
+ c.set_exstyle(handle, exstyle)
599
+ self._saved.pop(handle, None)
600
+ detail = c.format_error(code) if code else "sem código de erro"
601
+ raise EmbedError(f"SetParent falhou ({detail}, erro {code})")
602
+
603
+ c.set_pos(
604
+ handle, 0, 0, max(1, width), max(1, height),
605
+ _SWP_NOZORDER | _SWP_NOACTIVATE | _SWP_FRAMECHANGED | _SWP_SHOWWINDOW,
606
+ )
607
+
608
+ def resize(self, handle: int, width: int, height: int) -> None:
609
+ """Ajusta a janela filha ao tamanho do hospedeiro."""
610
+ self._c.set_pos(
611
+ handle, 0, 0, max(1, width), max(1, height),
612
+ _SWP_NOZORDER | _SWP_NOACTIVATE,
613
+ )
614
+
615
+ def size_of(self, handle: int) -> tuple[int, int] | None:
616
+ """Tamanho atual da janela (ou ``None`` se ela já não existe)."""
617
+ if not self._c.is_window(handle):
618
+ return None
619
+ return self._c.rect_size(handle)
620
+
621
+ def focus(self, handle: int) -> None:
622
+ """Foca a janela embutida (melhor esforço)."""
623
+ with contextlib.suppress(OSError):
624
+ self._c.set_focus(handle)
625
+
626
+ def detach(self, handle: int, *, restore: bool = False) -> None:
627
+ """Devolve a janela ao desktop e restaura os estilos originais.
628
+
629
+ Sem ``restore`` a janela é escondida (o processo será encerrado). Com
630
+ ``restore=True`` (programa adotado) ela volta visível ao tamanho e à
631
+ posição de antes. Deve ser chamado antes de destruir o widget
632
+ hospedeiro: destruir o pai derrubaria a janela de outro processo.
633
+ """
634
+ c = self._c
635
+ saved = self._saved.pop(handle, None)
636
+ if not c.is_window(handle):
637
+ return
638
+ if restore:
639
+ c.set_parent(handle, 0)
640
+ if saved is not None:
641
+ c.set_style(handle, saved.style)
642
+ c.set_exstyle(handle, saved.exstyle)
643
+ left, t, r, b = saved.rect if saved and saved.rect else (100, 100, 900, 700)
644
+ c.set_pos(
645
+ handle, left, t, max(_MIN_WINDOW_W, r - left), max(_MIN_WINDOW_H, b - t),
646
+ _SWP_FRAMECHANGED | _SWP_NOACTIVATE | _SWP_NOZORDER | _SWP_SHOWWINDOW,
647
+ )
648
+ return
649
+ c.set_pos(handle, 0, 0, 0, 0, _SWP_HIDEWINDOW | _SWP_NOACTIVATE | _SWP_NOZORDER)
650
+ c.set_parent(handle, 0)
651
+ if saved is not None:
652
+ c.set_style(handle, saved.style)
653
+ c.set_exstyle(handle, saved.exstyle)
654
+ c.set_pos(
655
+ handle, 0, 0, 0, 0,
656
+ _SWP_FRAMECHANGED | _SWP_NOACTIVATE | _SWP_NOZORDER | _SWP_HIDEWINDOW,
657
+ )
658
+
659
+ def request_close(self, handle: int) -> None:
660
+ """Posta ``WM_CLOSE`` para encerramento gracioso."""
661
+ if self._c.is_window(handle):
662
+ self._c.post_close(handle)
663
+
664
+ def release_pointer(self) -> None:
665
+ """Libera ``ClipCursor`` deixado por jogos que confinam o mouse."""
666
+ with contextlib.suppress(OSError):
667
+ self._c.release_cursor_clip()
668
+
669
+ def exit_hotkey_down(self, pids: Sequence[int]) -> bool:
670
+ """Ctrl+Shift+F12, apenas se o Codis ou o processo embutido está em foco."""
671
+ c = self._c
672
+ if not (c.key_down(_VK_CONTROL) and c.key_down(_VK_SHIFT) and c.key_down(_VK_F12)):
673
+ return False
674
+ return c.foreground_pid() in set(pids)
675
+
676
+ def close(self) -> None:
677
+ """Sem recursos persistentes a liberar."""
678
+ self._saved.clear()
679
+
680
+
681
+ _XA_CARDINAL = 6
682
+ _XK_SHIFT_L, _XK_SHIFT_R = 0xFFE1, 0xFFE2
683
+ _XK_CONTROL_L, _XK_CONTROL_R = 0xFFE3, 0xFFE4
684
+ _XK_F12 = 0xFFC9
685
+
686
+
687
+ class X11Backend:
688
+ """Backend de reparentamento para X11 (``XReparentWindow``).
689
+
690
+ Abre uma conexão própria ao display (``DISPLAY``). O handler de erros do
691
+ Xlib é **global ao processo**; por isso ele só é substituído durante cada
692
+ operação (e restaurado em seguida), preservando o handler do próprio Tk.
693
+ """
694
+
695
+ name = "x11"
696
+
697
+ def __init__(self) -> None:
698
+ """Abre o display e declara os protótipos Xlib usados."""
699
+ lib_name = ctypes.util.find_library("X11")
700
+ if not lib_name:
701
+ raise EmbedError("libX11 não encontrada")
702
+ x = ctypes.CDLL(lib_name)
703
+ c_ulong, c_int, c_uint, c_void = ctypes.c_ulong, ctypes.c_int, ctypes.c_uint, ctypes.c_void_p
704
+ x.XOpenDisplay.argtypes = [ctypes.c_char_p]
705
+ x.XOpenDisplay.restype = c_void
706
+ x.XCloseDisplay.argtypes = [c_void]
707
+ x.XDefaultRootWindow.argtypes = [c_void]
708
+ x.XDefaultRootWindow.restype = c_ulong
709
+ x.XInternAtom.argtypes = [c_void, ctypes.c_char_p, c_int]
710
+ x.XInternAtom.restype = c_ulong
711
+ x.XQueryTree.argtypes = [
712
+ c_void, c_ulong, ctypes.POINTER(c_ulong), ctypes.POINTER(c_ulong),
713
+ ctypes.POINTER(ctypes.POINTER(c_ulong)), ctypes.POINTER(c_uint),
714
+ ]
715
+ x.XQueryTree.restype = c_int
716
+ x.XFree.argtypes = [c_void]
717
+ x.XGetWindowProperty.argtypes = [
718
+ c_void, c_ulong, c_ulong, ctypes.c_long, ctypes.c_long, c_int, c_ulong,
719
+ ctypes.POINTER(c_ulong), ctypes.POINTER(c_int), ctypes.POINTER(c_ulong),
720
+ ctypes.POINTER(c_ulong), ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)),
721
+ ]
722
+ x.XGetWindowProperty.restype = c_int
723
+ x.XReparentWindow.argtypes = [c_void, c_ulong, c_ulong, c_int, c_int]
724
+ x.XMoveResizeWindow.argtypes = [c_void, c_ulong, c_int, c_int, c_uint, c_uint]
725
+ x.XMapWindow.argtypes = [c_void, c_ulong]
726
+ x.XUnmapWindow.argtypes = [c_void, c_ulong]
727
+ x.XSync.argtypes = [c_void, c_int]
728
+ x.XFlush.argtypes = [c_void]
729
+ x.XGetGeometry.argtypes = [
730
+ c_void, c_ulong, ctypes.POINTER(c_ulong), ctypes.POINTER(c_int),
731
+ ctypes.POINTER(c_int), ctypes.POINTER(c_uint), ctypes.POINTER(c_uint),
732
+ ctypes.POINTER(c_uint), ctypes.POINTER(c_uint),
733
+ ]
734
+ x.XGetGeometry.restype = c_int
735
+ x.XSetInputFocus.argtypes = [c_void, c_ulong, c_int, c_ulong]
736
+ x.XQueryKeymap.argtypes = [c_void, ctypes.c_char * 32]
737
+ x.XKeysymToKeycode.argtypes = [c_void, c_ulong]
738
+ x.XKeysymToKeycode.restype = ctypes.c_ubyte
739
+ self._err_t = ctypes.CFUNCTYPE(c_int, c_void, c_void)
740
+ x.XSetErrorHandler.argtypes = [self._err_t]
741
+ x.XSetErrorHandler.restype = self._err_t
742
+ self._x = x
743
+
744
+ self._dpy = x.XOpenDisplay(None)
745
+ if not self._dpy:
746
+ raise EmbedError("não foi possível abrir o display X11")
747
+ self._root = x.XDefaultRootWindow(self._dpy)
748
+ self._pid_atom = x.XInternAtom(self._dpy, b"_NET_WM_PID", 0)
749
+ self._name_atom = x.XInternAtom(self._dpy, b"_NET_WM_NAME", 0)
750
+ self._utf8_atom = x.XInternAtom(self._dpy, b"UTF8_STRING", 0)
751
+ self._x_error = False
752
+
753
+ def _on_error(_dpy: int, _ev: int) -> int:
754
+ self._x_error = True
755
+ return 0
756
+
757
+ self._on_error = self._err_t(_on_error)
758
+
759
+ @contextlib.contextmanager
760
+ def _guard(self) -> Iterator[None]:
761
+ """Instala o handler de erros só durante a operação e sincroniza o servidor."""
762
+ self._x_error = False
763
+ previous = self._x.XSetErrorHandler(self._on_error)
764
+ try:
765
+ yield
766
+ self._x.XSync(self._dpy, 0)
767
+ finally:
768
+ self._x.XSetErrorHandler(previous)
769
+
770
+ def _geometry(self, win: int) -> tuple[int, int] | None:
771
+ if not getattr(self, '_dpy', None):
772
+ return None
773
+ root, x, y = ctypes.c_ulong(), ctypes.c_int(), ctypes.c_int()
774
+ w, h, bw, depth = (ctypes.c_uint() for _ in range(4))
775
+ with self._guard():
776
+ ok = self._x.XGetGeometry(
777
+ self._dpy, win, ctypes.byref(root), ctypes.byref(x), ctypes.byref(y),
778
+ ctypes.byref(w), ctypes.byref(h), ctypes.byref(bw), ctypes.byref(depth),
779
+ )
780
+ if not ok or self._x_error:
781
+ return None
782
+ return int(w.value), int(h.value)
783
+
784
+ def _tree(self, win: int) -> tuple[int, list[int]] | None:
785
+ """Retorna (pai, filhos) de ``win`` ou ``None`` se a janela sumiu."""
786
+ if not getattr(self, '_dpy', None):
787
+ return None
788
+ root, parent = ctypes.c_ulong(), ctypes.c_ulong()
789
+ kids = ctypes.POINTER(ctypes.c_ulong)()
790
+ n = ctypes.c_uint()
791
+ with self._guard():
792
+ ok = self._x.XQueryTree(
793
+ self._dpy, win, ctypes.byref(root), ctypes.byref(parent),
794
+ ctypes.byref(kids), ctypes.byref(n),
795
+ )
796
+ if not ok or self._x_error:
797
+ return None
798
+ children = [int(kids[i]) for i in range(n.value)] if kids else []
799
+ if kids:
800
+ self._x.XFree(ctypes.cast(kids, ctypes.c_void_p))
801
+ return int(parent.value), children
802
+
803
+ def _pid_of(self, win: int) -> int | None:
804
+ if not getattr(self, '_dpy', None):
805
+ return None
806
+ atype, nitems, after = ctypes.c_ulong(), ctypes.c_ulong(), ctypes.c_ulong()
807
+ fmt = ctypes.c_int()
808
+ data = ctypes.POINTER(ctypes.c_ubyte)()
809
+ with self._guard():
810
+ status = self._x.XGetWindowProperty(
811
+ self._dpy, win, self._pid_atom, 0, 1, 0, _XA_CARDINAL,
812
+ ctypes.byref(atype), ctypes.byref(fmt), ctypes.byref(nitems),
813
+ ctypes.byref(after), ctypes.byref(data),
814
+ )
815
+ pid: int | None = None
816
+ if status == 0 and not self._x_error and data and nitems.value >= 1 and fmt.value == 32:
817
+ pid = int(ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong))[0])
818
+ if data:
819
+ self._x.XFree(ctypes.cast(data, ctypes.c_void_p))
820
+ return pid
821
+
822
+ def _title_of(self, win: int) -> str:
823
+ """Título via ``_NET_WM_NAME`` (UTF-8); vazio se ausente."""
824
+ if not getattr(self, '_dpy', None):
825
+ return ''
826
+ atype, nitems, after = ctypes.c_ulong(), ctypes.c_ulong(), ctypes.c_ulong()
827
+ fmt = ctypes.c_int()
828
+ data = ctypes.POINTER(ctypes.c_ubyte)()
829
+ with self._guard():
830
+ status = self._x.XGetWindowProperty(
831
+ self._dpy, win, self._name_atom, 0, 256, 0, self._utf8_atom,
832
+ ctypes.byref(atype), ctypes.byref(fmt), ctypes.byref(nitems),
833
+ ctypes.byref(after), ctypes.byref(data),
834
+ )
835
+ text = ""
836
+ if status == 0 and not self._x_error and data and fmt.value == 8:
837
+ text = bytes(data[: nitems.value]).decode("utf-8", "replace")
838
+ if data:
839
+ self._x.XFree(ctypes.cast(data, ctypes.c_void_p))
840
+ return text or self._wm_name_of(win)
841
+
842
+ def _wm_name_of(self, win: int) -> str:
843
+ """Fallback: ``WM_NAME`` (STRING/Latin-1), usado por apps sem ``_NET_WM_NAME``."""
844
+ if not getattr(self, '_dpy', None):
845
+ return ''
846
+ atype, nitems, after = ctypes.c_ulong(), ctypes.c_ulong(), ctypes.c_ulong()
847
+ fmt = ctypes.c_int()
848
+ data = ctypes.POINTER(ctypes.c_ubyte)()
849
+ with self._guard():
850
+ status = self._x.XGetWindowProperty(
851
+ self._dpy, win, 39, 0, 256, 0, 0,
852
+ ctypes.byref(atype), ctypes.byref(fmt), ctypes.byref(nitems),
853
+ ctypes.byref(after), ctypes.byref(data),
854
+ )
855
+ text = ""
856
+ if status == 0 and not self._x_error and data and fmt.value == 8:
857
+ text = bytes(data[: nitems.value]).decode("latin-1", "replace")
858
+ if data:
859
+ self._x.XFree(ctypes.cast(data, ctypes.c_void_p))
860
+ return text
861
+
862
+ @staticmethod
863
+ def _exe_of(pid: int) -> str:
864
+ try:
865
+ return os.path.basename(os.readlink(f"/proc/{pid}/exe"))
866
+ except OSError:
867
+ try:
868
+ with open(f"/proc/{pid}/comm", encoding="utf-8") as fh:
869
+ return fh.read().strip()
870
+ except OSError:
871
+ return ""
872
+
873
+ def find_window_in(self, pids: Sequence[int]) -> int | None:
874
+ """Maior janela (até 3 níveis) pertencente a qualquer um dos ``pids``."""
875
+ wanted = set(pids)
876
+ best, best_area = None, 0
877
+ for win in self._walk(self._root, 3):
878
+ if self._pid_of(win) not in wanted:
879
+ continue
880
+ geo = self._geometry(win)
881
+ if geo is None or geo[0] < _MIN_WINDOW_W or geo[1] < _MIN_WINDOW_H:
882
+ continue
883
+ if geo[0] * geo[1] > best_area:
884
+ best, best_area = win, geo[0] * geo[1]
885
+ return best
886
+
887
+ def list_windows(self) -> list[WindowInfo]:
888
+ """Janelas de clientes X11 com ``_NET_WM_PID`` e título."""
889
+ out: list[WindowInfo] = []
890
+ for win in self._walk(self._root, 3):
891
+ pid = self._pid_of(win)
892
+ if not pid:
893
+ continue
894
+ geo = self._geometry(win)
895
+ if geo is None or geo[0] < _MIN_WINDOW_W or geo[1] < _MIN_WINDOW_H:
896
+ continue
897
+ title = self._title_of(win)
898
+ if title:
899
+ out.append(WindowInfo(win, pid, title, self._exe_of(pid), geo))
900
+ return out
901
+
902
+ def _walk(self, win: int, depth: int) -> Iterator[int]:
903
+ info = self._tree(win)
904
+ if info is None:
905
+ return
906
+ for child in info[1]:
907
+ yield child
908
+ if depth > 1:
909
+ yield from self._walk(child, depth - 1)
910
+
911
+ def find_window(self, pid: int) -> int | None:
912
+ """Procura (até 3 níveis, por causa de molduras do WM) a maior janela do PID."""
913
+ best, best_area = None, 0
914
+ for win in self._walk(self._root, 3):
915
+ if self._pid_of(win) != pid:
916
+ continue
917
+ geo = self._geometry(win)
918
+ if geo is None or geo[0] < _MIN_WINDOW_W or geo[1] < _MIN_WINDOW_H:
919
+ continue
920
+ if geo[0] * geo[1] > best_area:
921
+ best, best_area = win, geo[0] * geo[1]
922
+ return best
923
+
924
+ def is_alive(self, handle: int) -> bool:
925
+ """True se a janela ainda existe no servidor X."""
926
+ return self._geometry(handle) is not None
927
+
928
+ def is_embedded(self, handle: int, host: int) -> bool:
929
+ """True se o pai atual de ``handle`` é ``host``."""
930
+ info = self._tree(handle)
931
+ return info is not None and info[0] == host
932
+
933
+ def embed(self, handle: int, host: int, width: int, height: int) -> None:
934
+ """Reparenta, dimensiona e mapeia a janela dentro de ``host``."""
935
+ with self._guard():
936
+ self._x.XReparentWindow(self._dpy, handle, host, 0, 0)
937
+ self._x.XMoveResizeWindow(
938
+ self._dpy, handle, 0, 0, max(1, width), max(1, height)
939
+ )
940
+ self._x.XMapWindow(self._dpy, handle)
941
+ if self._x_error:
942
+ raise EmbedError("XReparentWindow falhou (BadWindow/BadMatch)")
943
+
944
+ def resize(self, handle: int, width: int, height: int) -> None:
945
+ """Redimensiona a janela embutida."""
946
+ with self._guard():
947
+ self._x.XMoveResizeWindow(
948
+ self._dpy, handle, 0, 0, max(1, width), max(1, height)
949
+ )
950
+
951
+ def size_of(self, handle: int) -> tuple[int, int] | None:
952
+ """Tamanho atual da janela (ou ``None`` se ela já não existe)."""
953
+ return self._geometry(handle)
954
+
955
+ def focus(self, handle: int) -> None:
956
+ """Foca a janela embutida (RevertToParent, CurrentTime)."""
957
+ with self._guard():
958
+ self._x.XSetInputFocus(self._dpy, handle, 2, 0)
959
+
960
+ def detach(self, handle: int, *, restore: bool = False) -> None:
961
+ """Devolve a janela à raiz; ``restore`` a mantém visível (o WM a reenquadra)."""
962
+ with self._guard():
963
+ self._x.XUnmapWindow(self._dpy, handle)
964
+ self._x.XReparentWindow(self._dpy, handle, self._root, 0, 0)
965
+ if restore:
966
+ self._x.XMapWindow(self._dpy, handle)
967
+
968
+ def request_close(self, handle: int) -> None:
969
+ """No X11 o encerramento é feito por sinal ao processo (ver o painel)."""
970
+
971
+ def release_pointer(self) -> None:
972
+ """O servidor X libera grabs automaticamente quando o cliente termina."""
973
+
974
+ def exit_hotkey_down(self, pids: Sequence[int]) -> bool:
975
+ """Ctrl+Shift+F12 via ``XQueryKeymap`` (independe do foco)."""
976
+ keymap = (ctypes.c_char * 32)()
977
+ self._x.XQueryKeymap(self._dpy, keymap)
978
+ raw = bytes(keymap)
979
+
980
+ def pressed(*keysyms: int) -> bool:
981
+ for sym in keysyms:
982
+ kc = int(self._x.XKeysymToKeycode(self._dpy, sym))
983
+ if kc and raw[kc // 8] & (1 << (kc % 8)):
984
+ return True
985
+ return False
986
+
987
+ return (
988
+ pressed(_XK_CONTROL_L, _XK_CONTROL_R)
989
+ and pressed(_XK_SHIFT_L, _XK_SHIFT_R)
990
+ and pressed(_XK_F12)
991
+ )
992
+
993
+ def close(self) -> None:
994
+ """Fecha a conexão com o display."""
995
+ if getattr(self, "_dpy", None):
996
+ self._x.XCloseDisplay(self._dpy)
997
+ self._dpy = None
998
+
999
+
1000
+ def get_backend() -> WindowBackend | None:
1001
+ """Cria o backend adequado à plataforma, ou ``None`` se não houver suporte.
1002
+
1003
+ ``None`` indica que o chamador deve executar o aplicativo em janela externa.
1004
+ """
1005
+ try:
1006
+ if sys.platform == "win32":
1007
+ return Win32Backend()
1008
+ if sys.platform.startswith(("linux", "freebsd", "openbsd", "netbsd")):
1009
+ if not os.environ.get("DISPLAY"):
1010
+ return None
1011
+ return X11Backend()
1012
+ except (EmbedError, OSError, AttributeError) as exc:
1013
+ logger.warning("Backend de incorporação indisponível: %s", exc)
1014
+ return None
1015
+
1016
+
1017
+ _LIVE_PROCS: set[subprocess.Popen] = set()
1018
+
1019
+
1020
+ def _spawn(
1021
+ argv: Sequence[str],
1022
+ cwd: str | None,
1023
+ env: dict[str, str] | None,
1024
+ log: IO[bytes] | None,
1025
+ ) -> subprocess.Popen:
1026
+ """Inicia o processo sem janela de console, com saída redirecionada ao log.
1027
+
1028
+ Nunca usa ``PIPE`` sem consumidor: um pipe cheio travaria o motor do jogo.
1029
+ """
1030
+ kwargs: dict[str, Any] = {
1031
+ "cwd": cwd,
1032
+ "env": env,
1033
+ "stdin": subprocess.DEVNULL,
1034
+ "stdout": log if log is not None else subprocess.DEVNULL,
1035
+ "stderr": subprocess.STDOUT if log is not None else subprocess.DEVNULL,
1036
+ "close_fds": True,
1037
+ }
1038
+ if sys.platform == "win32":
1039
+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
1040
+ else:
1041
+ kwargs["start_new_session"] = True
1042
+ proc = subprocess.Popen(list(argv), **kwargs)
1043
+ _LIVE_PROCS.add(proc)
1044
+ return proc
1045
+
1046
+
1047
+ def _signal_process(proc: subprocess.Popen, *, force: bool) -> None:
1048
+ """Envia SIGTERM/SIGKILL ao grupo (POSIX) ou ``terminate``/``kill`` (Windows)."""
1049
+ try:
1050
+ if sys.platform != "win32":
1051
+ import signal
1052
+
1053
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL if force else signal.SIGTERM)
1054
+ elif force:
1055
+ proc.kill()
1056
+ else:
1057
+ proc.terminate()
1058
+ except (ProcessLookupError, PermissionError, OSError):
1059
+ with contextlib.suppress(Exception):
1060
+ if force:
1061
+ proc.kill()
1062
+ else:
1063
+ proc.terminate()
1064
+
1065
+
1066
+ @dataclass(frozen=True)
1067
+ class EmbedLabels:
1068
+ """Textos (já traduzidos) exibidos pelo painel."""
1069
+
1070
+ hint: str
1071
+ back: str
1072
+ focus: str
1073
+ loading: str
1074
+ embedded: str
1075
+ closed: str
1076
+ err_exited: str
1077
+ err_timeout: str
1078
+ err_launch: str
1079
+ embed_failed: str
1080
+
1081
+
1082
+ @dataclass(frozen=True)
1083
+ class EmbedTheme:
1084
+ """Cores do painel (padrão: estética DOOM)."""
1085
+
1086
+ bg: str = "#000000"
1087
+ bar_bg: str = "#1a0000"
1088
+ bar_fg: str = "#ff4400"
1089
+ btn_bg: str = "#550000"
1090
+ btn_fg: str = "#ff9900"
1091
+ boot_fg: str = "#ff3300"
1092
+ font: str = "Courier New"
1093
+
1094
+
1095
+ class EmbeddedAppPanel(tk.Frame):
1096
+ """Frame que executa um programa externo e embute sua janela nativa.
1097
+
1098
+ Ciclo de vida: ``booting`` (console animado enquanto o processo abre a
1099
+ janela) -> ``embedded`` (janela reparentada e redimensionada junto com o
1100
+ frame) -> ``closed``. Em caso de erro permanece em ``failed`` mostrando a
1101
+ mensagem no console até o usuário clicar em voltar.
1102
+
1103
+ Args:
1104
+ parent: Widget pai onde o painel será colocado (``place`` pelo chamador).
1105
+ argv: Linha de comando completa do processo.
1106
+ backend: Backend nativo (:func:`get_backend`).
1107
+ labels: Textos da interface.
1108
+ theme: Cores.
1109
+ cwd / env: Diretório de trabalho e ambiente do processo.
1110
+ log_path: Arquivo que recebe stdout/stderr do processo.
1111
+ boot_lines: Linhas do console animado.
1112
+ window_timeout: Segundos máximos esperando a janela aparecer.
1113
+ on_status: Callback para mensagens de status.
1114
+ on_close: Callback chamado uma vez quando o painel é encerrado.
1115
+ """
1116
+
1117
+ def __init__(
1118
+ self,
1119
+ parent: tk.Widget,
1120
+ argv: Sequence[str],
1121
+ *,
1122
+ backend: WindowBackend,
1123
+ labels: EmbedLabels,
1124
+ theme: EmbedTheme | None = None,
1125
+ cwd: str | None = None,
1126
+ env: dict[str, str] | None = None,
1127
+ log_path: Path | None = None,
1128
+ boot_lines: Sequence[str] = (),
1129
+ window_timeout: float = 25.0,
1130
+ on_status: Callable[[str], None] | None = None,
1131
+ on_close: Callable[[], None] | None = None,
1132
+ adopt_handle: int | None = None,
1133
+ adopt_pids: Callable[[], Sequence[int]] | None = None,
1134
+ show_bar: bool = True,
1135
+ ) -> None:
1136
+ """Monta a UI (barra + palco) sem iniciar o processo; chame :meth:`start`.
1137
+
1138
+ Modo *adotar* (``adopt_handle`` e/ou ``adopt_pids``): nada é iniciado;
1139
+ o painel incorpora uma janela de um programa **já em execução** e, ao
1140
+ fechar, apenas devolve a janela ao desktop (o programa continua vivo).
1141
+ ``adopt_pids`` é chamado a cada ciclo para reencontrar a janela pelo
1142
+ nome do executável caso o handle original desapareça.
1143
+ """
1144
+ self._theme = theme or EmbedTheme()
1145
+ super().__init__(parent, bg=self._theme.bg)
1146
+ self._argv = list(argv)
1147
+ self._backend = backend
1148
+ self._labels = labels
1149
+ self._cwd = cwd
1150
+ self._env = env
1151
+ self._log_path = log_path
1152
+ self._boot_lines = list(boot_lines)
1153
+ self._timeout = float(window_timeout)
1154
+ self._adopt_handle = adopt_handle
1155
+ self._adopt_pids = adopt_pids
1156
+ self._adopting = adopt_handle is not None or adopt_pids is not None
1157
+ self._show_bar = show_bar
1158
+ self._on_status = on_status
1159
+ self._on_close = on_close
1160
+
1161
+ self.phase = "idle"
1162
+ self._proc: subprocess.Popen | None = None
1163
+ self._log: IO[bytes] | None = None
1164
+ self._hwnd: int | None = None
1165
+ self._applied_size: tuple[int, int] | None = None
1166
+ self._started_at = 0.0
1167
+ self._tick_job: str | None = None
1168
+ self._boot_job: str | None = None
1169
+ self._resize_job: str | None = None
1170
+ self._hotkey_latched = False
1171
+ self._closing = False
1172
+ self._root_widget: tk.Misc | None = None
1173
+ self._hotkey_bind: str | None = None
1174
+
1175
+ self._build_ui()
1176
+ self.bind("<Destroy>", self._on_destroy, add="+")
1177
+
1178
+ def _build_ui(self) -> None:
1179
+ th = self._theme
1180
+ if self._show_bar:
1181
+ bar = tk.Frame(self, bg=th.bar_bg, height=26)
1182
+ bar.pack(fill="x", side="top")
1183
+ bar.pack_propagate(False)
1184
+ tk.Label(
1185
+ bar, text=self._labels.hint, bg=th.bar_bg, fg=th.bar_fg,
1186
+ font=(th.font, 9, "bold"),
1187
+ ).pack(side="left", padx=10)
1188
+ for text, cmd in ((self._labels.back, self.close), (self._labels.focus, self.focus_game)):
1189
+ tk.Button(
1190
+ bar, text=text, bg=th.btn_bg, fg=th.btn_fg, font=(th.font, 8, "bold"),
1191
+ relief="flat", cursor="hand2", command=cmd,
1192
+ activebackground=th.btn_bg, activeforeground=th.btn_fg,
1193
+ ).pack(side="right", padx=4, pady=2)
1194
+
1195
+ self._stage = tk.Frame(self, bg=th.bg)
1196
+ self._stage.pack(fill="both", expand=True)
1197
+ self._host = tk.Frame(self._stage, bg=th.bg, takefocus=True, highlightthickness=0)
1198
+ self._host.place(x=0, y=0, relwidth=1, relheight=1)
1199
+ self._boot = tk.Text(
1200
+ self._stage, bg=th.bg, fg=th.boot_fg, font=(th.font, 10), relief="flat",
1201
+ bd=0, highlightthickness=0, insertbackground=th.boot_fg, cursor="arrow",
1202
+ )
1203
+ self._boot.place(x=0, y=0, relwidth=1, relheight=1)
1204
+ self._host.bind("<Configure>", self._on_host_configure, add="+")
1205
+ self._host.bind("<FocusIn>", lambda _e: self.focus_game(), add="+")
1206
+
1207
+ def set_argv(self, argv: Sequence[str]) -> None:
1208
+ """Define a linha de comando (permitido apenas antes de :meth:`start`)."""
1209
+ if self.phase == "idle":
1210
+ self._argv = list(argv)
1211
+
1212
+ def start(self) -> None:
1213
+ """Inicia o processo e o acompanhamento da janela."""
1214
+ if self.phase != "idle":
1215
+ return
1216
+ self.update_idletasks()
1217
+ self._host.update_idletasks()
1218
+ self._root_widget = self.winfo_toplevel()
1219
+ self._hotkey_bind = self._root_widget.bind(
1220
+ "<Control-Shift-F12>", lambda _e: self.close(), add="+"
1221
+ )
1222
+ self._notify(self._labels.loading)
1223
+ if self._adopting:
1224
+ logger.info("Adotando janela existente (handle=%s)", self._adopt_handle)
1225
+ else:
1226
+ try:
1227
+ self._open_log()
1228
+ self._proc = _spawn(self._argv, self._cwd, self._env, self._log)
1229
+ except OSError as exc:
1230
+ logger.warning("Falha ao iniciar %s: %s", self._argv[:1], exc)
1231
+ self._fail(self._labels.err_launch.format(reason=exc))
1232
+ return
1233
+ logger.info("Processo embutido iniciado: PID %s (%s)", self._proc.pid, self._argv[0])
1234
+ self.phase = "booting"
1235
+ self._started_at = time.monotonic()
1236
+ self._type_boot(0)
1237
+ self._schedule_tick()
1238
+
1239
+ def focus_game(self) -> None:
1240
+ """Dá o foco de teclado à janela embutida."""
1241
+ if self.phase == "embedded" and self._hwnd is not None:
1242
+ self._backend.focus(self._hwnd)
1243
+
1244
+ def close(self) -> None:
1245
+ """Encerra o jogo e remove o painel (idempotente)."""
1246
+ if self._closing:
1247
+ return
1248
+ self._closing = True
1249
+ self._shutdown(destroy=True)
1250
+
1251
+ def _schedule_tick(self) -> None:
1252
+ if not self._closing:
1253
+ self._tick_job = self.after(_TICK_MS, self._tick)
1254
+
1255
+ def _tick(self) -> None:
1256
+ """Um passo do acompanhamento: processo vivo? janela? tamanho? atalho?"""
1257
+ self._tick_job = None
1258
+ if self._closing:
1259
+ return
1260
+ proc = self._proc
1261
+ if proc is None and not self._adopting:
1262
+ return
1263
+ if proc is not None:
1264
+ code = proc.poll()
1265
+ if code is not None:
1266
+ self._on_process_exit(code)
1267
+ return
1268
+ elif self.phase == "embedded" and self._hwnd is not None and not self._backend.is_alive(self._hwnd):
1269
+ self.close()
1270
+ return
1271
+
1272
+ if self.phase in ("booting", "embedded"):
1273
+ self._ensure_embedded()
1274
+ if self._closing or self.phase not in ("booting", "embedded"):
1275
+ return
1276
+ if self.phase == "booting" and time.monotonic() - self._started_at > self._timeout:
1277
+ self._fail(self._labels.err_timeout.format(seconds=int(self._timeout)))
1278
+ return
1279
+ if self._hotkey_pressed():
1280
+ self.close()
1281
+ return
1282
+ self._schedule_tick()
1283
+
1284
+ def _hotkey_pressed(self) -> bool:
1285
+ """Detecta a *borda* do atalho global (evita fechar repetidamente)."""
1286
+ pids = [os.getpid()] + ([self._proc.pid] if self._proc else list(self._target_pids()))
1287
+ down = self._backend.exit_hotkey_down(pids)
1288
+ fired = down and not self._hotkey_latched
1289
+ self._hotkey_latched = down
1290
+ return fired
1291
+
1292
+ def _target_pids(self) -> Sequence[int]:
1293
+ """PIDs cujas janelas podem ser incorporadas (processo lançado ou adotado)."""
1294
+ if self._proc is not None:
1295
+ return [self._proc.pid]
1296
+ if self._adopt_pids is not None:
1297
+ try:
1298
+ return list(self._adopt_pids())
1299
+ except Exception:
1300
+ return []
1301
+ return []
1302
+
1303
+ def _ensure_embedded(self) -> None:
1304
+ """Localiza/reparenta a janela e mantém o tamanho sincronizado."""
1305
+ proc, host_id = self._proc, self._host.winfo_id()
1306
+ if proc is None and not self._adopting:
1307
+ return
1308
+ if self._hwnd is not None and not self._backend.is_alive(self._hwnd):
1309
+ self._hwnd = None
1310
+ self._applied_size = None
1311
+ if self._hwnd is None:
1312
+ if self._adopt_handle is not None and self._backend.is_alive(self._adopt_handle):
1313
+ found: int | None = self._adopt_handle
1314
+ elif proc is not None:
1315
+ found = self._backend.find_window(proc.pid)
1316
+ else:
1317
+ pids = self._target_pids()
1318
+ found = self._backend.find_window_in(pids) if pids else None
1319
+ if found is None:
1320
+ return
1321
+ self._hwnd = found
1322
+ if not self._backend.is_embedded(self._hwnd, host_id):
1323
+ self._embed_now(host_id)
1324
+ return
1325
+ self._sync_size(force=False)
1326
+
1327
+ def _embed_now(self, host_id: int) -> None:
1328
+ hwnd = self._hwnd
1329
+ if hwnd is None:
1330
+ return
1331
+ width, height = self._host_size()
1332
+ try:
1333
+ self._backend.embed(hwnd, host_id, width, height)
1334
+ except EmbedError as exc:
1335
+ logger.warning("Incorporação falhou: %s", exc)
1336
+ self._fail(self._labels.embed_failed.format(reason=exc))
1337
+ return
1338
+ self._applied_size = (width, height)
1339
+ first = self.phase != "embedded"
1340
+ self.phase = "embedded"
1341
+ if first:
1342
+ with contextlib.suppress(tk.TclError):
1343
+ self._boot.place_forget()
1344
+ self._notify(self._labels.embedded)
1345
+ self._backend.focus(hwnd)
1346
+
1347
+ def _host_size(self) -> tuple[int, int]:
1348
+ return max(1, self._host.winfo_width()), max(1, self._host.winfo_height())
1349
+
1350
+ def _on_host_configure(self, _event: tk.Event) -> None:
1351
+ """Coalesce redimensionamentos do hospedeiro em uma única atualização."""
1352
+ if self._resize_job is None and self.phase == "embedded":
1353
+ self._resize_job = self.after_idle(self._apply_pending_resize)
1354
+
1355
+ def _apply_pending_resize(self) -> None:
1356
+ self._resize_job = None
1357
+ if not self._closing:
1358
+ self._sync_size(force=True)
1359
+
1360
+ def _sync_size(self, *, force: bool) -> None:
1361
+ if self._hwnd is None or self.phase != "embedded":
1362
+ return
1363
+ want = self._host_size()
1364
+ if force or want != self._applied_size or self._backend.size_of(self._hwnd) != want:
1365
+ self._backend.resize(self._hwnd, *want)
1366
+ self._applied_size = want
1367
+
1368
+ def _on_process_exit(self, code: int) -> None:
1369
+ """Processo terminou: encerra normalmente, ou reporta falha durante o boot."""
1370
+ logger.info("Processo embutido encerrou (código %s)", code)
1371
+ if self.phase == "embedded":
1372
+ self.close()
1373
+ return
1374
+ self._fail(self._labels.err_exited.format(code=code, log=self._log_tail()))
1375
+
1376
+ def _fail(self, message: str) -> None:
1377
+ """Mostra ``message`` no console e encerra o processo, mantendo o painel."""
1378
+ self.phase = "failed"
1379
+ self._cancel_jobs()
1380
+ self._terminate_process()
1381
+ with contextlib.suppress(tk.TclError):
1382
+ self._boot.place(x=0, y=0, relwidth=1, relheight=1)
1383
+ self._boot.insert("end", "\n" + message + "\n")
1384
+ self._boot.see("end")
1385
+ self._notify(message)
1386
+
1387
+ def _type_boot(self, idx: int) -> None:
1388
+ """Animação de digitação do console (cosmética)."""
1389
+ self._boot_job = None
1390
+ if self._closing or self.phase != "booting" or idx >= len(self._boot_lines):
1391
+ return
1392
+ with contextlib.suppress(tk.TclError):
1393
+ self._boot.insert("end", self._boot_lines[idx])
1394
+ self._boot.see("end")
1395
+ self._boot_job = self.after(70, lambda: self._type_boot(idx + 1))
1396
+
1397
+ def _open_log(self) -> None:
1398
+ if self._log_path is None:
1399
+ return
1400
+ try:
1401
+ self._log_path.parent.mkdir(parents=True, exist_ok=True)
1402
+ self._log = self._log_path.open("wb")
1403
+ except OSError as exc:
1404
+ logger.debug("Sem log do motor (%s): %s", self._log_path, exc)
1405
+ self._log = None
1406
+
1407
+ def _log_tail(self, lines: int = 3) -> str:
1408
+ if self._log_path is None:
1409
+ return ""
1410
+ try:
1411
+ if self._log is not None:
1412
+ self._log.flush()
1413
+ text = self._log_path.read_text(encoding="utf-8", errors="replace")
1414
+ except OSError:
1415
+ return ""
1416
+ return " | ".join(ln.strip() for ln in text.strip().splitlines()[-lines:])
1417
+
1418
+ def _cancel_jobs(self) -> None:
1419
+ for attr in ("_tick_job", "_boot_job", "_resize_job"):
1420
+ job = getattr(self, attr)
1421
+ if job is not None:
1422
+ with contextlib.suppress(tk.TclError, ValueError):
1423
+ self.after_cancel(job)
1424
+ setattr(self, attr, None)
1425
+
1426
+ def _terminate_process(self) -> None:
1427
+ """Pede o fim do processo (gracioso -> SIGTERM -> SIGKILL) sem bloquear a UI."""
1428
+ proc, hwnd = self._proc, self._hwnd
1429
+ self._hwnd = None
1430
+ if hwnd is not None:
1431
+ with contextlib.suppress(Exception):
1432
+ self._backend.release_pointer()
1433
+ if self._adopting:
1434
+ self._backend.detach(hwnd, restore=True)
1435
+ else:
1436
+ self._backend.detach(hwnd)
1437
+ self._backend.request_close(hwnd)
1438
+ if proc is None or proc.poll() is not None:
1439
+ self._release_proc(proc)
1440
+ return
1441
+ _signal_process(proc, force=False)
1442
+ deadline = time.monotonic() + 2.0
1443
+ reaper_host = self._root_widget
1444
+
1445
+ def _reap() -> None:
1446
+ if proc.poll() is not None:
1447
+ self._release_proc(proc)
1448
+ return
1449
+ if time.monotonic() < deadline and reaper_host is not None:
1450
+ with contextlib.suppress(tk.TclError):
1451
+ reaper_host.after(150, _reap)
1452
+ return
1453
+ _signal_process(proc, force=True)
1454
+ with contextlib.suppress(Exception):
1455
+ proc.wait(timeout=0.5)
1456
+ self._release_proc(proc)
1457
+
1458
+ _reap()
1459
+
1460
+ def _release_proc(self, proc: subprocess.Popen | None) -> None:
1461
+ if proc is not None:
1462
+ _LIVE_PROCS.discard(proc)
1463
+ if self._log is not None:
1464
+ with contextlib.suppress(OSError):
1465
+ self._log.close()
1466
+ self._log = None
1467
+
1468
+ def _shutdown(self, *, destroy: bool) -> None:
1469
+ self._cancel_jobs()
1470
+ was_embedded = self.phase == "embedded"
1471
+ self.phase = "closed"
1472
+ self._terminate_process()
1473
+ root = self._root_widget
1474
+ if root is not None and self._hotkey_bind:
1475
+ with contextlib.suppress(tk.TclError, ValueError):
1476
+ root.unbind("<Control-Shift-F12>", self._hotkey_bind)
1477
+ self._hotkey_bind = None
1478
+ with contextlib.suppress(Exception):
1479
+ self._backend.close()
1480
+ if was_embedded or destroy:
1481
+ self._notify(self._labels.closed)
1482
+ callback, self._on_close = self._on_close, None
1483
+ if destroy:
1484
+ with contextlib.suppress(tk.TclError):
1485
+ self.destroy()
1486
+ if callback is not None:
1487
+ with contextlib.suppress(Exception):
1488
+ callback()
1489
+
1490
+ def _on_destroy(self, event: tk.Event) -> None:
1491
+ """Se o widget for destruído por fora (ex.: app saindo), limpa o processo."""
1492
+ if event.widget is not self or self._closing:
1493
+ return
1494
+ self._closing = True
1495
+ self._shutdown(destroy=False)
1496
+
1497
+ def _notify(self, message: str) -> None:
1498
+ if self._on_status is not None:
1499
+ with contextlib.suppress(Exception):
1500
+ self._on_status(message)