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/lsp/dap_client.py ADDED
@@ -0,0 +1,480 @@
1
+ """Cliente DAP (Debug Adapter Protocol) real para o Codis.
2
+
3
+ Diferente de um simples lançador de subprocesso, este módulo implementa o
4
+ papel de *cliente* do protocolo DAP: conecta-se via TCP a um servidor
5
+ debugpy já em execução, realiza o handshake completo (``initialize`` -> ``attach``/``launch`` -> ``setBreakpoints`` -> ``configurationDone``) e then
6
+ permite enviar comandos de execução (``continue``, ``next``, ``stepIn``,
7
+ ``stepOut``, ``pause``, ``disconnect``) e consultar estado (``stackTrace``,
8
+ ``scopes``, ``variables``, ``evaluate``).
9
+
10
+ Sem este cliente, iniciar o debugpy com ``--listen`` apenas abre um socket
11
+ e o processo roda livremente (ou fica parado para sempre se
12
+ ``--wait-for-client`` estiver ativo) - nada no Codis fala DAP de fato, então
13
+ breakpoints/stepping nunca têm efeito. Esta classe resolve isso: o próprio
14
+ Codis é o cliente DAP.
15
+
16
+ Uso típico (a partir do ``DebugPanel``):
17
+
18
+ client = DAPClient(
19
+ on_event=self._on_dap_event, # despachado na thread Tk
20
+ on_close=self._on_dap_close,
21
+ )
22
+ client.connect("127.0.0.1", 5678)
23
+ client.attach(breakpoints={"path/to/script.py": [3, 7]})
24
+ ...
25
+ client.continue_()
26
+ client.step_over()
27
+ client.disconnect()
28
+
29
+ O framing usado é idêntico ao LSP (``Content-Length: N\\r\\n\\r\\n`` + corpo
30
+ JSON), pois DAP reutiliza o mesmo formato de transporte.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import contextlib
36
+ import logging
37
+ import socket
38
+ import threading
39
+ import time
40
+ from collections.abc import Callable
41
+ from typing import Any
42
+
43
+ from .framing import FrameDecoder, MessageTooLarge, encode_frame
44
+
45
+ logger = logging.getLogger("Codis.DAP")
46
+
47
+ _REQUEST_TIMEOUT = 5.0
48
+ _CONNECT_RETRIES = 30
49
+ _CONNECT_RETRY_DELAY = 0.2
50
+
51
+
52
+ class DAPClient:
53
+ """Cliente DAP mínimo, porém funcional, voltado para debugpy.
54
+
55
+ Todas as chamadas de rede ocorrem em uma thread de leitura dedicada;
56
+ callbacks (``on_event``/``on_close``) são despachados via
57
+ ``tk_widget.after(0, ...)`` quando um widget Tk é fornecido, garantindo
58
+ que a UI só seja tocada na thread principal.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ on_event: Callable[[str, dict], None] | None = None,
64
+ on_close: Callable[[], None] | None = None,
65
+ tk_widget: Any = None,
66
+ ) -> None:
67
+ """Cria o cliente (ainda não conectado).
68
+
69
+ Args:
70
+ on_event: Chamado com ``(event_name, body)`` para cada evento
71
+ DAP assíncrono recebido (``stopped``, ``output``,
72
+ ``terminated``, ``continued``, ``exited`` etc.).
73
+ on_close: Chamado quando a conexão é perdida ou encerrada.
74
+ tk_widget: Widget Tk usado para despachar callbacks na thread
75
+ principal via ``.after(0, ...)``. Se ``None``, os callbacks
76
+ são chamados diretamente na thread de leitura (cuidado).
77
+ """
78
+ self._on_event = on_event
79
+ self._on_close = on_close
80
+ self._tk_widget = tk_widget
81
+
82
+ self._sock: socket.socket | None = None
83
+ self._seq = 0
84
+ self._seq_lock = threading.Lock()
85
+ self._pending: dict[int, dict[str, Any]] = {}
86
+ self._pending_lock = threading.Lock()
87
+
88
+ self._reader_thread: threading.Thread | None = None
89
+ self._alive = False
90
+ self._initialized = False
91
+ self._initialized_event = threading.Event()
92
+ self._supports_config_done = False
93
+
94
+ self.is_attached = False
95
+ self.is_stopped = False
96
+ self.last_stopped_thread_id: int | None = None
97
+ self.last_stopped_reason: str = ""
98
+
99
+ def connect(self, host: str, port: int, retries: int = _CONNECT_RETRIES) -> bool:
100
+ """Conecta ao servidor debugpy, tentando algumas vezes (ele pode
101
+ ainda não estar escutando logo após o processo ser lançado).
102
+
103
+ Returns:
104
+ True se a conexão TCP foi estabelecida com sucesso.
105
+ """
106
+ for attempt in range(retries):
107
+ try:
108
+ sock = socket.create_connection((host, port), timeout=2.0)
109
+ self._sock = sock
110
+ self._alive = True
111
+ self._reader_thread = threading.Thread(
112
+ target=self._reader_loop, daemon=True
113
+ )
114
+ self._reader_thread.start()
115
+ logger.debug(
116
+ "DAP: conectado a %s:%s (tentativa %d)", host, port, attempt + 1
117
+ )
118
+ return True
119
+ except OSError:
120
+ time.sleep(_CONNECT_RETRY_DELAY)
121
+ logger.warning("DAP: não foi possível conectar a %s:%s", host, port)
122
+ return False
123
+
124
+ def attach(
125
+ self,
126
+ breakpoints: dict[str, list[int]] | None = None,
127
+ timeout: float = _REQUEST_TIMEOUT,
128
+ ) -> bool:
129
+ """Executa o handshake completo de attach com debugpy.
130
+
131
+ A ordem exigida pelo debugpy é sutil e não corresponde à ingênua
132
+ leitura da spec DAP genérica: o request ``attach`` deve ser
133
+ ENVIADO logo após ``initialize`` (antes de ``setBreakpoints``/
134
+ ``configurationDone``), mas sua RESPOSTA só chega depois que
135
+ ``configurationDone`` é processado. Ou seja: -> initialize (aguarda resposta) -> attach (envia, NÃO aguarda resposta ainda) <- initialized event (aguarda) -> setBreakpoints (aguarda resposta, por arquivo) -> configurationDone (aguarda resposta) <- attach response (chega só agora - lida em seguida) <- stopped/process events (a execução já pode ter iniciado)
136
+
137
+ Enviar ``configurationDone`` antes de ``attach`` faz o debugpy
138
+ recusá-lo ("only allowed during handling of a launch/attach
139
+ request"); bloquear esperando a resposta de ``attach`` antes de
140
+ enviar ``configurationDone`` trava ambos os lados. Esta
141
+ implementação envia ``attach`` de forma assíncrona (sem bloquear)
142
+ e só lê sua resposta depois de completar a configuração.
143
+
144
+ Args:
145
+ breakpoints: Mapa ``{caminho_absoluto: [linhas]}`` a enviar via
146
+ ``setBreakpoints`` antes de liberar a execução.
147
+
148
+ Returns:
149
+ True se o handshake foi concluído sem erros bloqueantes.
150
+ """
151
+ if not self._sock:
152
+ return False
153
+
154
+ init_resp = self._request(
155
+ "initialize",
156
+ {
157
+ "clientID": "codis",
158
+ "clientName": "Codis",
159
+ "adapterID": "debugpy",
160
+ "pathFormat": "path",
161
+ "linesStartAt1": True,
162
+ "columnsStartAt1": True,
163
+ "supportsRunInTerminalRequest": False,
164
+ "supportsVariableType": True,
165
+ "supportsVariablePaging": False,
166
+ "supportsConfigurationDoneRequest": True,
167
+ },
168
+ timeout=timeout,
169
+ )
170
+ if init_resp is None or not init_resp.get("success", False):
171
+ logger.warning("DAP: initialize falhou: %s", init_resp)
172
+ return False
173
+ caps = init_resp.get("body", {}) or {}
174
+ self._supports_config_done = bool(
175
+ caps.get("supportsConfigurationDoneRequest", True)
176
+ )
177
+
178
+ attach_seq = self._next_seq()
179
+ attach_event = threading.Event()
180
+ attach_box: dict[str, Any] = {}
181
+ with self._pending_lock:
182
+ self._pending[attach_seq] = {
183
+ "event": attach_event, "box": attach_box}
184
+ self._send(
185
+ {
186
+ "seq": attach_seq,
187
+ "type": "request",
188
+ "command": "attach",
189
+ "arguments": {
190
+ "justMyCode": False,
191
+ "redirectOutput": True,
192
+ },
193
+ }
194
+ )
195
+
196
+ if not self._wait_for_initialized(timeout=timeout):
197
+ logger.warning("DAP: evento 'initialized' não recebido a tempo")
198
+ with self._pending_lock:
199
+ self._pending.pop(attach_seq, None)
200
+ return False
201
+
202
+ if breakpoints:
203
+ for path, lines in breakpoints.items():
204
+ self._request(
205
+ "setBreakpoints",
206
+ {
207
+ "source": {"path": path},
208
+ "breakpoints": [{"line": ln} for ln in sorted(lines)],
209
+ },
210
+ timeout=timeout,
211
+ )
212
+
213
+ if self._supports_config_done:
214
+ self._request("configurationDone", {}, timeout=timeout)
215
+
216
+ got = attach_event.wait(timeout)
217
+ with self._pending_lock:
218
+ self._pending.pop(attach_seq, None)
219
+ attach_resp = attach_box.get("response") if got else None
220
+ if attach_resp is None or not attach_resp.get("success", False):
221
+ logger.warning("DAP: attach falhou: %s", attach_resp)
222
+ return False
223
+
224
+ self.is_attached = True
225
+ self._initialized = True
226
+ return True
227
+
228
+ def _wait_for_initialized(self, timeout: float) -> bool:
229
+ """Bloqueia até o evento ``initialized`` ser recebido (ou timeout).
230
+
231
+ Usa um ``threading.Event`` interno alimentado por ``_handle_message``
232
+ quando esse evento específico chega, evitando uma espera ocupada.
233
+ """
234
+ if self._initialized_event.is_set():
235
+ return True
236
+ return self._initialized_event.wait(timeout)
237
+
238
+ def set_breakpoints(
239
+ self, path: str, lines: list[int], timeout: float = _REQUEST_TIMEOUT
240
+ ) -> list[dict]:
241
+ """Atualiza os breakpoints para um arquivo específico em tempo real.
242
+
243
+ Pode ser chamado a qualquer momento após ``attach`` (inclusive com
244
+ a execução parada ou em andamento) - debugpy reavalia a lista
245
+ completa enviada, então o conjunto é sempre substituído, não
246
+ somado.
247
+
248
+ Returns:
249
+ A lista de breakpoints confirmados pelo adaptador (cada um com
250
+ ``verified``: bool), ou lista vazia em caso de falha.
251
+ """
252
+ resp = self._request(
253
+ "setBreakpoints",
254
+ {
255
+ "source": {"path": path},
256
+ "breakpoints": [{"line": ln} for ln in sorted(lines)],
257
+ },
258
+ timeout=timeout,
259
+ )
260
+ if resp and resp.get("success"):
261
+ return resp.get("body", {}).get("breakpoints", [])
262
+ return []
263
+
264
+ def continue_(self, thread_id: int | None = None) -> None:
265
+ """Libera a execução (Continue / F5)."""
266
+ self._async_request("continue", {"threadId": thread_id or 0})
267
+
268
+ def step_over(self, thread_id: int | None = None) -> None:
269
+ """Executa a linha atual sem entrar em chamadas de função (Step Over / F10)."""
270
+ self._async_request("next", {"threadId": thread_id or 0})
271
+
272
+ def step_in(self, thread_id: int | None = None) -> None:
273
+ """Entra na próxima chamada de função (Step Into / F11)."""
274
+ self._async_request("stepIn", {"threadId": thread_id or 0})
275
+
276
+ def step_out(self, thread_id: int | None = None) -> None:
277
+ """Sai da função atual, voltando ao chamador (Step Out / Shift+F11)."""
278
+ self._async_request("stepOut", {"threadId": thread_id or 0})
279
+
280
+ def pause(self, thread_id: int | None = None) -> None:
281
+ """Pausa a execução em andamento."""
282
+ self._async_request("pause", {"threadId": thread_id or 0})
283
+
284
+ def disconnect(self) -> None:
285
+ """Encerra a sessão de depuração e fecha a conexão."""
286
+ if self._sock:
287
+ with contextlib.suppress(Exception):
288
+ self._request(
289
+ "disconnect", {"terminateDebuggee": True}, timeout=1.5)
290
+ self._shutdown()
291
+
292
+ def threads(self, timeout: float = _REQUEST_TIMEOUT) -> list[dict]:
293
+ """Lista as threads ativas na sessão de depuração."""
294
+ resp = self._request("threads", {}, timeout=timeout)
295
+ if resp and resp.get("success"):
296
+ return resp.get("body", {}).get("threads", [])
297
+ return []
298
+
299
+ def stack_trace(
300
+ self, thread_id: int, timeout: float = _REQUEST_TIMEOUT
301
+ ) -> list[dict]:
302
+ """Retorna os frames da pilha de chamadas para a thread parada."""
303
+ resp = self._request(
304
+ "stackTrace", {"threadId": thread_id}, timeout=timeout)
305
+ if resp and resp.get("success"):
306
+ return resp.get("body", {}).get("stackFrames", [])
307
+ return []
308
+
309
+ def scopes(self, frame_id: int, timeout: float = _REQUEST_TIMEOUT) -> list[dict]:
310
+ """Retorna os escopos (locals/globals) de um frame."""
311
+ resp = self._request("scopes", {"frameId": frame_id}, timeout=timeout)
312
+ if resp and resp.get("success"):
313
+ return resp.get("body", {}).get("scopes", [])
314
+ return []
315
+
316
+ def variables(
317
+ self, variables_ref: int, timeout: float = _REQUEST_TIMEOUT
318
+ ) -> list[dict]:
319
+ """Retorna as variáveis de um escopo/estrutura, por referência."""
320
+ resp = self._request(
321
+ "variables", {"variablesReference": variables_ref}, timeout=timeout
322
+ )
323
+ if resp and resp.get("success"):
324
+ return resp.get("body", {}).get("variables", [])
325
+ return []
326
+
327
+ def evaluate(
328
+ self, expr: str, frame_id: int | None, timeout: float = _REQUEST_TIMEOUT
329
+ ) -> dict:
330
+ """Avalia uma expressão no contexto de um frame parado (REPL real)."""
331
+ args: dict[str, Any] = {"expression": expr, "context": "repl"}
332
+ if frame_id is not None:
333
+ args["frameId"] = frame_id
334
+ resp = self._request("evaluate", args, timeout=timeout)
335
+ if resp and resp.get("success"):
336
+ return resp.get("body", {})
337
+ return {"result": "", "error": (resp or {}).get("message", "evaluate failed")}
338
+
339
+ def _next_seq(self) -> int:
340
+ with self._seq_lock:
341
+ self._seq += 1
342
+ return self._seq
343
+
344
+ def _send(self, data: dict) -> None:
345
+ if not self._sock:
346
+ return
347
+ try:
348
+ self._sock.sendall(encode_frame(data))
349
+ except OSError as exc:
350
+ logger.debug("DAP: erro ao enviar: %s", exc)
351
+ self._shutdown()
352
+
353
+ def _request(
354
+ self, command: str, arguments: dict, timeout: float = _REQUEST_TIMEOUT
355
+ ) -> dict | None:
356
+ """Envia um request DAP e bloqueia até a resposta correspondente
357
+ chegar (ou o timeout expirar). Seguro para chamar fora da thread
358
+ de leitura - não deve ser chamado de dentro de ``on_event``.
359
+ """
360
+ seq = self._next_seq()
361
+ event = threading.Event()
362
+ box: dict[str, Any] = {}
363
+
364
+ with self._pending_lock:
365
+ self._pending[seq] = {"event": event, "box": box}
366
+
367
+ self._send(
368
+ {
369
+ "seq": seq,
370
+ "type": "request",
371
+ "command": command,
372
+ "arguments": arguments,
373
+ }
374
+ )
375
+
376
+ got = event.wait(timeout)
377
+ with self._pending_lock:
378
+ self._pending.pop(seq, None)
379
+ if not got:
380
+ logger.debug("DAP: timeout esperando resposta de '%s'", command)
381
+ return None
382
+ return box.get("response")
383
+
384
+ def _async_request(self, command: str, arguments: dict) -> None:
385
+ """Envia um request DAP sem esperar a resposta (fire-and-forget) -
386
+ usado para comandos de execução, cujo efeito real chega via os
387
+ eventos ``stopped``/``continued``/``terminated``, não na resposta
388
+ síncrona em si."""
389
+ seq = self._next_seq()
390
+ self._send(
391
+ {
392
+ "seq": seq,
393
+ "type": "request",
394
+ "command": command,
395
+ "arguments": arguments,
396
+ }
397
+ )
398
+
399
+ def _dispatch_event(self, name: str, body: dict) -> None:
400
+ if name == "initialized":
401
+ self._initialized_event.set()
402
+ elif name == "stopped":
403
+ self.is_stopped = True
404
+ self.last_stopped_thread_id = body.get("threadId")
405
+ self.last_stopped_reason = body.get("reason", "")
406
+ elif name in ("continued", "exited", "terminated"):
407
+ self.is_stopped = False
408
+
409
+ if not self._on_event:
410
+ return
411
+ if self._tk_widget is not None:
412
+ with contextlib.suppress(Exception):
413
+ self._tk_widget.after(0, lambda: self._on_event(name, body))
414
+ else:
415
+ with contextlib.suppress(Exception):
416
+ self._on_event(name, body)
417
+
418
+ def _reader_loop(self) -> None:
419
+ decoder = FrameDecoder()
420
+ sock = self._sock
421
+ if sock is None:
422
+ return
423
+ while self._alive:
424
+ try:
425
+ chunk = sock.recv(4096)
426
+ if not chunk:
427
+ break
428
+ for msg in decoder.feed(chunk):
429
+ self._safe_handle_message(msg)
430
+ except MessageTooLarge as exc:
431
+ logger.warning("DAP: %s descartada", exc)
432
+ break
433
+ except OSError as exc:
434
+ logger.debug("DAP: reader encerrado: %s", exc)
435
+ break
436
+ self._shutdown()
437
+
438
+ def _safe_handle_message(self, msg: Any) -> None:
439
+ """Trata uma mensagem sem deixar uma mensagem malformada matar a thread leitora."""
440
+ if not isinstance(msg, dict):
441
+ return
442
+ try:
443
+ self._handle_message(msg)
444
+ except Exception:
445
+ logger.exception("DAP: erro ao tratar mensagem do adaptador")
446
+
447
+ def _handle_message(self, msg: dict) -> None:
448
+ mtype = msg.get("type")
449
+ if mtype == "response":
450
+ req_seq = msg.get("request_seq")
451
+ with self._pending_lock:
452
+ waiter = self._pending.get(req_seq)
453
+ if waiter:
454
+ waiter["box"]["response"] = msg
455
+ waiter["event"].set()
456
+ elif mtype == "event":
457
+ body = msg.get("body")
458
+ self._dispatch_event(
459
+ msg.get("event", ""), body if isinstance(body, dict) else {}
460
+ )
461
+
462
+ def _shutdown(self) -> None:
463
+ if not self._alive:
464
+ return
465
+ self._alive = False
466
+ with contextlib.suppress(Exception):
467
+ if self._sock:
468
+ self._sock.close()
469
+ self._sock = None
470
+ with self._pending_lock:
471
+ for waiter in self._pending.values():
472
+ waiter["event"].set()
473
+ self._pending.clear()
474
+ if self._on_close:
475
+ if self._tk_widget is not None:
476
+ with contextlib.suppress(Exception):
477
+ self._tk_widget.after(0, self._on_close)
478
+ else:
479
+ with contextlib.suppress(Exception):
480
+ self._on_close()
src/lsp/edits.py ADDED
@@ -0,0 +1,84 @@
1
+ """Interpretação das edições que um servidor LSP devolve (rename, quick fix, refactor).
2
+
3
+ Funções puras, sem Tk: aceitam tanto os dicionários do protocolo quanto os objetos de
4
+ ``src.lsp.protocol`` (``TextEdit``, ``WorkspaceEdit``).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterable
10
+ from typing import Any
11
+
12
+ Edit = tuple[int, int, int, int, str]
13
+ """``(linha_inicial, coluna_inicial, linha_final, coluna_final, novo_texto)``, base 0, colunas em UTF-16."""
14
+
15
+
16
+ def edit_fields(edit: Any) -> Edit:
17
+ """Extrai ``(sl, sc, el, ec, texto)`` de um ``TextEdit`` (objeto ou dicionário)."""
18
+ if hasattr(edit, "range"):
19
+ rng = edit.range
20
+ return (rng.start.line, rng.start.character, rng.end.line, rng.end.character, edit.new_text)
21
+ rng = edit.get("range") or {}
22
+ start, end = rng.get("start") or {}, rng.get("end") or {}
23
+ return (
24
+ int(start.get("line", 0)),
25
+ int(start.get("character", 0)),
26
+ int(end.get("line", 0)),
27
+ int(end.get("character", 0)),
28
+ edit.get("newText", ""),
29
+ )
30
+
31
+
32
+ def sort_for_apply(edits: Iterable[Any]) -> list[Edit]:
33
+ """Edições em ordem segura para aplicar uma a uma: de trás para frente.
34
+
35
+ Ordenar só pela linha deixava as edições de uma mesma linha na ordem original, e a
36
+ primeira deslocava as colunas das seguintes (ex.: renomear dois usos na mesma linha).
37
+ """
38
+ return sorted((edit_fields(e) for e in edits), key=lambda e: (e[0], e[1], e[2], e[3]), reverse=True)
39
+
40
+
41
+ def utf16_to_index(line_text: str, units: int) -> int:
42
+ """Converte uma coluna em unidades UTF-16 (como o LSP conta) para o índice no texto Python/Tk.
43
+
44
+ Caracteres fora do plano básico (emoji, por exemplo) ocupam 2 unidades no LSP e 1 no Tk.
45
+ """
46
+ if units <= 0:
47
+ return 0
48
+ used = 0
49
+ for index, char in enumerate(line_text):
50
+ if used >= units:
51
+ return index
52
+ used += 2 if ord(char) > 0xFFFF else 1
53
+ return len(line_text)
54
+
55
+
56
+ def normalize_workspace_edit(edit: Any) -> dict[str, list[Any]]:
57
+ """Reduz um ``WorkspaceEdit`` (dicionário ou objeto) a ``{uri: [TextEdit, ...]}``.
58
+
59
+ Cobre ``changes`` e ``documentChanges`` (apenas ``TextDocumentEdit``; criar, renomear e
60
+ apagar arquivos não são aplicados aqui). Devolve ``{}`` para ``None`` ou formatos desconhecidos.
61
+ """
62
+ if not edit:
63
+ return {}
64
+ if isinstance(edit, dict):
65
+ changes = edit.get("changes") or {}
66
+ document_changes = edit.get("documentChanges") or []
67
+ else:
68
+ changes = getattr(edit, "changes", None) or {}
69
+ document_changes = getattr(edit, "document_changes", None) or []
70
+
71
+ merged: dict[str, list[Any]] = {}
72
+ if isinstance(changes, dict):
73
+ for uri, edits in changes.items():
74
+ if uri and edits:
75
+ merged.setdefault(uri, []).extend(edits)
76
+ if isinstance(document_changes, list):
77
+ for change in document_changes:
78
+ if not isinstance(change, dict) or "kind" in change:
79
+ continue # CreateFile/RenameFile/DeleteFile
80
+ uri = (change.get("textDocument") or {}).get("uri", "")
81
+ edits = change.get("edits") or []
82
+ if uri and edits:
83
+ merged.setdefault(uri, []).extend(edits)
84
+ return merged
src/lsp/framing.py ADDED
@@ -0,0 +1,73 @@
1
+ """Enquadramento de mensagens JSON-RPC por ``Content-Length`` (LSP e DAP).
2
+
3
+ Os dois protocolos usam o mesmo formato: um cabeçalho ``Content-Length: N``, uma
4
+ linha em branco e ``N`` bytes de JSON em UTF-8. Aqui ficam a codificação e a
5
+ decodificação incremental, para que o cliente LSP e o cliente DAP não mantenham
6
+ cada um a sua cópia.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from typing import Any
14
+
15
+ MAX_MESSAGE_BYTES = 256 * 1024 * 1024
16
+
17
+ _SEPARATOR = b"\r\n\r\n"
18
+ _LENGTH = re.compile(rb"Content-Length:\s*(\d+)", re.IGNORECASE)
19
+
20
+
21
+ class MessageTooLarge(Exception):
22
+ """O cabeçalho anuncia uma mensagem maior que o limite aceito."""
23
+
24
+ def __init__(self, length: int) -> None:
25
+ super().__init__(f"mensagem de {length} bytes")
26
+ self.length = length
27
+
28
+
29
+ def encode_frame(message: Any) -> bytes:
30
+ """Serializa ``message`` como JSON e antepõe o cabeçalho ``Content-Length``."""
31
+ body = json.dumps(message, ensure_ascii=False).encode("utf-8")
32
+ return f"Content-Length: {len(body)}\r\n\r\n".encode("ascii") + body
33
+
34
+
35
+ class FrameDecoder:
36
+ """Remonta mensagens a partir de pedaços de bytes de tamanho qualquer.
37
+
38
+ Cabeçalhos sem ``Content-Length`` e corpos que não são JSON válido são
39
+ descartados sem interromper o fluxo.
40
+ """
41
+
42
+ def __init__(self, max_bytes: int = MAX_MESSAGE_BYTES) -> None:
43
+ self._buffer = b""
44
+ self._max_bytes = max_bytes
45
+
46
+ def feed(self, data: bytes) -> list[Any]:
47
+ """Acrescenta ``data`` e devolve as mensagens que ficaram completas.
48
+
49
+ Raises:
50
+ MessageTooLarge: se um cabeçalho anunciar mais que o limite.
51
+ """
52
+ self._buffer += data
53
+ messages: list[Any] = []
54
+ while (separator := self._buffer.find(_SEPARATOR)) != -1:
55
+ header = self._buffer[:separator]
56
+ match = _LENGTH.search(header)
57
+ if match is None:
58
+ self._buffer = self._buffer[separator + len(_SEPARATOR) :]
59
+ continue
60
+ length = int(match.group(1))
61
+ if length > self._max_bytes:
62
+ raise MessageTooLarge(length)
63
+ start = separator + len(_SEPARATOR)
64
+ end = start + length
65
+ if len(self._buffer) < end:
66
+ break
67
+ body = self._buffer[start:end]
68
+ self._buffer = self._buffer[end:]
69
+ try:
70
+ messages.append(json.loads(body.decode("utf-8", errors="replace")))
71
+ except json.JSONDecodeError:
72
+ continue
73
+ return messages