codis 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
@@ -0,0 +1,2937 @@
1
+ """Mixin ``_PaneLSPMixin`` - camada LSP do painel de edição.
2
+
3
+ Adiciona ao ``EditorPane`` toda a integração com Language Servers: hover,
4
+ autocompletar, go-to-definition, referências, rename, code actions,
5
+ formatação, inlay hints e call hierarchy.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import logging
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ import tkinter as tk
18
+ from collections.abc import Callable
19
+ from pathlib import Path
20
+ from tkinter import filedialog, messagebox, simpledialog
21
+ from typing import TYPE_CHECKING, Any
22
+
23
+ from src.constants import (
24
+ AUTO_CLOSE,
25
+ AUTOCOMPLETE_LINE_LIMIT,
26
+ EXT_LANG,
27
+ FONT_MAX,
28
+ FONT_MIN,
29
+ FONT_MONO,
30
+ FONT_SIZE,
31
+ FONT_UI,
32
+ GIANT_FILE_BYTES,
33
+ HL_FULL_DISABLE,
34
+ HL_LINE_LIMIT,
35
+ LANG_COMMENT,
36
+ LANG_LABEL,
37
+ LARGE_CODE_BYTES,
38
+ LARGE_FILE_BYTES,
39
+ LINT_LINE_LIMIT,
40
+ LSP_LINE_LIMIT,
41
+ VIEWPORT_LINES,
42
+ VIEWPORT_SHIFT,
43
+ VIEWPORT_TRIGGER,
44
+ )
45
+ from src.editor._pane_utils import SaveDeclined, _BinaryDialog, _lsp_uri_to_path
46
+ from src.editor.kdocs import (
47
+ JSDocParser,
48
+ KDocsParser,
49
+ find_all_usages,
50
+ find_definition_line,
51
+ kdocs_annotation_to_sections,
52
+ lsp_hover_to_sections,
53
+ )
54
+ from src.editor.save_hooks import notify_saved as _notify_saved
55
+ from src.fileio import write_atomic
56
+ from src.i18n import _t
57
+ from src.lsp.edits import normalize_workspace_edit, sort_for_apply, utf16_to_index
58
+ from src.ui.file_timeline import FileTimeline
59
+
60
+ try:
61
+ from src.editor.large_file import VirtualFileBuffer
62
+
63
+ _VFB_AVAILABLE = True
64
+ except ImportError:
65
+ _VFB_AVAILABLE = False
66
+
67
+ logger = logging.getLogger(__name__)
68
+
69
+ if TYPE_CHECKING:
70
+ from src.lint.manager import Diag
71
+ from src.lsp.client import LSPManager
72
+
73
+ __all__ = ["_PaneLSPMixin"]
74
+
75
+ _MOTION_MIN_INTERVAL_S = 0.03
76
+
77
+
78
+
79
+ def _same_file(a: Path, b: Path) -> bool:
80
+ """Os dois caminhos apontam para o mesmo arquivo (tolera maiúsculas no Windows e links)."""
81
+ try:
82
+ return os.path.samefile(a, b)
83
+ except OSError:
84
+ return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
85
+
86
+
87
+ class _PaneLSPMixin:
88
+ """Mixin com toda a lógica LSP, hover e navegação do EditorPane.
89
+
90
+ Não instanciar diretamente - usado via herança múltipla por EditorPane.
91
+ Todos os atributos de instância são inicializados por EditorPane.__init__.
92
+ """
93
+
94
+ # Ligados pelo app: formatação e itens de menu de contexto vindos de plugins.
95
+ format_provider: Callable[[Any], str | None] | None = None
96
+ context_provider: Callable[[str, Any], list[tuple[str, Callable[[], None]]]] | None = None
97
+
98
+ _diag_motion_t = 0.0
99
+ _diag_tip_line: int | None = None
100
+ _diag_index_src: Any = None
101
+ _diag_index_len = -1
102
+ _diag_index: dict[int, list] = {}
103
+
104
+ def _hide_hover(self, _: Any = None) -> None:
105
+ if self._hover_job:
106
+ with contextlib.suppress(tk.TclError):
107
+ self.after_cancel(self._hover_job)
108
+ self._hover_job = None
109
+ self._close_balloon()
110
+
111
+ def _close_balloon(self) -> None:
112
+ """Fecha o balloon hover atual - respeita o modo interativo (pinned)."""
113
+ if self._hover_tip and self._hover_tip.winfo_exists():
114
+ with contextlib.suppress(tk.TclError):
115
+ self._hover_tip.destroy()
116
+ self._hover_tip = None
117
+ if self._balloon and self._balloon.is_visible():
118
+ if getattr(self._balloon, "_pinned", False):
119
+ return
120
+ with contextlib.suppress(tk.TclError):
121
+ self._balloon.hide()
122
+ self._balloon = None
123
+ self._last_hover_word = ""
124
+ self._last_hover_line = -1
125
+
126
+ def _get_balloon(self) -> Any:
127
+ """Retorna (ou cria) a instância compartilhada do KDocsBalloon."""
128
+ if self._balloon is None or not self._balloon.is_visible():
129
+ from src.editor.kdocs import KDocsBalloon
130
+
131
+ self._balloon = KDocsBalloon(self._tmgr.theme)
132
+ return self._balloon
133
+
134
+ _HOVER_SKIP_WORDS: frozenset[str] = frozenset(
135
+ {
136
+ "if",
137
+ "for",
138
+ "while",
139
+ "def",
140
+ "class",
141
+ "return",
142
+ "import",
143
+ "from",
144
+ "in",
145
+ "is",
146
+ "and",
147
+ "or",
148
+ "not",
149
+ "else",
150
+ "elif",
151
+ "try",
152
+ "except",
153
+ "finally",
154
+ "with",
155
+ "as",
156
+ "pass",
157
+ "break",
158
+ "continue",
159
+ "raise",
160
+ "yield",
161
+ "lambda",
162
+ "global",
163
+ "nonlocal",
164
+ "True",
165
+ "False",
166
+ "None",
167
+ "function",
168
+ "var",
169
+ "let",
170
+ "const",
171
+ "new",
172
+ "this",
173
+ "typeof",
174
+ "instanceof",
175
+ "void",
176
+ "delete",
177
+ "throw",
178
+ "catch",
179
+ "switch",
180
+ "case",
181
+ "default",
182
+ "do",
183
+ "of",
184
+ "async",
185
+ "await",
186
+ "export",
187
+ "extends",
188
+ "implements",
189
+ "interface",
190
+ "type",
191
+ "enum",
192
+ "namespace",
193
+ "module",
194
+ "declare",
195
+ "abstract",
196
+ "override",
197
+ "public",
198
+ "private",
199
+ "protected",
200
+ "static",
201
+ "readonly",
202
+ "true",
203
+ "false",
204
+ "null",
205
+ "undefined",
206
+ "super",
207
+ }
208
+ )
209
+
210
+ @staticmethod
211
+ def _src_sep(label: str) -> dict:
212
+ """Retorna um dict separador de fonte para o balloon de hover."""
213
+ return {"kind": "source_label", "label": label}
214
+
215
+ def _collect_local_hover_sections(
216
+ self,
217
+ word: str,
218
+ line: int,
219
+ line_text: str,
220
+ ) -> list[dict]:
221
+ """Coleta seções de hover das fontes locais (KDocs, JSDoc, Peek).
222
+
223
+ Não realiza chamadas de rede - é completamente síncrono.
224
+ """
225
+ sections: list[dict] = []
226
+ skip = self._HOVER_SKIP_WORDS
227
+ sep = self._src_sep
228
+
229
+ if self._kdocs and not self._is_large_mode and not self._is_giant_mode:
230
+ content_txt = self.text.get("1.0", "end-1c")
231
+ ann = KDocsParser.resolve_hover(
232
+ word, line, self._kdocs, content_txt)
233
+ if ann is not None:
234
+ sections.append(sep("KDocs"))
235
+ sections.extend(kdocs_annotation_to_sections(ann))
236
+
237
+ if word and word not in skip:
238
+ result = JSDocParser.resolve_hover(word, line, self._doc_symbols)
239
+ if result:
240
+ display, doc, mode = result
241
+ src_lang = doc.get("_lang", "") or (self.lang or "jsdoc")
242
+ jsdoc_sections = JSDocParser.format_sections_for_mode(
243
+ display, doc, mode
244
+ )
245
+ if jsdoc_sections:
246
+ if jsdoc_sections[0].get("kind") == "title":
247
+ jsdoc_sections[0]["source"] = src_lang
248
+ sections.append(sep(src_lang.upper() or "Doc"))
249
+ sections.extend(jsdoc_sections)
250
+
251
+ if not sections and word and word not in skip:
252
+ stripped = line_text.strip()
253
+ if stripped.startswith(("/**", "* ", "*/")):
254
+ full_txt = self.text.get("1.0", "end-1c")
255
+ block_lines = full_txt.splitlines()
256
+ end_idx = -1
257
+ for k in range(line - 1, min(line + 20, len(block_lines))):
258
+ if "*/" in block_lines[k]:
259
+ end_idx = k
260
+ break
261
+ if end_idx != -1:
262
+ for k in range(end_idx + 1, min(end_idx + 10, len(block_lines))):
263
+ nl = block_lines[k].strip()
264
+ if not nl:
265
+ continue
266
+ for pat in JSDocParser._COMPILED_PATTERNS:
267
+ m = pat.match(nl)
268
+ if m:
269
+ sym_name = m.group(1)
270
+ sym_doc = self._doc_symbols.get(sym_name)
271
+ if sym_doc:
272
+ src_lang = sym_doc.get("_lang", "") or (
273
+ self.lang or "jsdoc"
274
+ )
275
+ bs = JSDocParser.format_sections(
276
+ sym_name, sym_doc, source=src_lang
277
+ )
278
+ if bs:
279
+ if bs[0].get("kind") == "title":
280
+ bs[0]["source"] = src_lang
281
+ sections.append(
282
+ sep(src_lang.upper() or "Doc"))
283
+ sections.extend(bs)
284
+ break
285
+ if sections:
286
+ break
287
+
288
+ if (
289
+ not sections
290
+ and word
291
+ and word not in skip
292
+ and not self._is_large_mode
293
+ and not self._is_giant_mode
294
+ ):
295
+ full_txt = self.text.get("1.0", "end-1c")
296
+ def_line = find_definition_line(word, full_txt, line)
297
+ if def_line is not None:
298
+ def_text = full_txt.splitlines()[def_line - 1].strip()[:90]
299
+ sections.extend(
300
+ [
301
+ {
302
+ "kind": "title",
303
+ "symbol": word,
304
+ "ret_type": "",
305
+ "type_tag": "",
306
+ "modifiers": [],
307
+ "tpl_params": [],
308
+ "source": "peek",
309
+ },
310
+ {"kind": "example", "lines": [def_text]},
311
+ {"kind": "meta", "lines": [
312
+ f"definido na linha {def_line}"]},
313
+ ]
314
+ )
315
+
316
+ return sections
317
+
318
+ def _make_lsp_hover_callback(
319
+ self,
320
+ word: str,
321
+ sx: int,
322
+ sy: int,
323
+ hover_key: str,
324
+ hover_line: int,
325
+ local_sections: list[dict],
326
+ ):
327
+ """Constrói o callback LSP que mescla seções remotas com as locais."""
328
+ sep = self._src_sep
329
+
330
+ def _show_local():
331
+ """Mostra só as seções locais (o LSP não trouxe nada utilizável)."""
332
+ if self._last_hover_word != hover_key:
333
+ self._close_balloon()
334
+ self._get_balloon().show(self.text, sx, sy, local_sections)
335
+ self._last_hover_word = hover_key
336
+ self._last_hover_line = hover_line
337
+
338
+ def _lsp_cb(result):
339
+ if not result:
340
+ if local_sections:
341
+ self.after(0, _show_local)
342
+ return
343
+
344
+ md = ""
345
+ if hasattr(result, "contents"):
346
+ c = result.contents
347
+ if isinstance(c, dict):
348
+ md = c.get("value", str(c))
349
+ elif hasattr(c, "value"):
350
+ md = c.value
351
+ elif isinstance(c, list):
352
+ md = "\n\n".join(
353
+ (
354
+ item
355
+ if isinstance(item, str)
356
+ else item.get("value", "") if isinstance(item, dict) else ""
357
+ )
358
+ for item in c
359
+ )
360
+ else:
361
+ md = str(c)
362
+ elif isinstance(result, dict):
363
+ c = result.get("contents", {})
364
+ md = c.get("value", str(c)) if isinstance(c, dict) else str(c)
365
+
366
+ if not md or not md.strip():
367
+ if local_sections:
368
+ self.after(0, _show_local)
369
+ return
370
+
371
+ lsp_sections = lsp_hover_to_sections(word, md)
372
+
373
+ def _show_merged():
374
+ merged = []
375
+ if lsp_sections:
376
+ merged.append(sep("LSP"))
377
+ merged.extend(lsp_sections)
378
+ if local_sections:
379
+ merged.extend(local_sections)
380
+ if merged:
381
+ self._close_balloon()
382
+ balloon = self._get_balloon()
383
+ balloon.show(self.text, sx, sy, merged)
384
+ self._last_hover_word = hover_key
385
+ self._last_hover_line = hover_line
386
+
387
+ self.after(0, _show_merged)
388
+
389
+ return _lsp_cb
390
+
391
+ def _show_hover(self, x: int, y: int) -> None:
392
+ """Sistema unificado de hover: coleta fontes em paralelo (LSP, KDocs, JSDoc, Peek).
393
+
394
+ Exibe uma única bolha com seções separadas por origem - sem sobrescrita.
395
+ Ctrl ao mover o mouse pina o balloon (não fecha automaticamente).
396
+ """
397
+ with contextlib.suppress(tk.TclError, AttributeError):
398
+ if self.text.tag_ranges(tk.SEL) and self.text.tag_ranges("sel"):
399
+ return
400
+
401
+ idx = self.text.index(f"@{x},{y}")
402
+ line = int(idx.split(".", maxsplit=1)[0])
403
+ col = int(idx.split(".", maxsplit=1)[1])
404
+ line_text = self.text.get(f"{line}.0", f"{line}.end")
405
+
406
+ word = ""
407
+ word_start = col
408
+ for m in re.finditer(r"[$\w][\w$]*", line_text):
409
+ if m.start() <= col <= m.end():
410
+ word = m.group()
411
+ word_start = m.start()
412
+ break
413
+
414
+ hover_key = f"{word}:{line}"
415
+ if hover_key == self._last_hover_word and line == self._last_hover_line:
416
+ return
417
+
418
+ try:
419
+ bbox = self.text.bbox(f"{line}.{word_start}")
420
+ if bbox:
421
+ char_x, char_y, _cw, char_h = bbox
422
+ sx = self.text.winfo_rootx() + char_x
423
+ sy = self.text.winfo_rooty() + char_y + char_h
424
+ else:
425
+ raise tk.TclError
426
+ except tk.TclError:
427
+ sx = self.text.winfo_rootx() + x
428
+ sy = self.text.winfo_rooty() + y + 18
429
+
430
+ sections = self._collect_local_hover_sections(
431
+ word, line, line_text)
432
+
433
+ if sections and not (
434
+ self._lsp_mgr
435
+ and self.path
436
+ and word
437
+ and word not in self._HOVER_SKIP_WORDS
438
+ ):
439
+ self._close_balloon()
440
+ balloon = self._get_balloon()
441
+ balloon.show(self.text, sx, sy, sections)
442
+ self._last_hover_word = hover_key
443
+ self._last_hover_line = line
444
+
445
+ if (
446
+ self._lsp_mgr
447
+ and self.path
448
+ and word
449
+ and word not in self._HOVER_SKIP_WORDS
450
+ ):
451
+ cb = self._make_lsp_hover_callback(
452
+ word, sx, sy, hover_key, line, list(sections)
453
+ )
454
+ with contextlib.suppress(tk.TclError):
455
+ self._lsp_mgr.hover(
456
+ self.path, self.lang, line - 1, col, cb)
457
+
458
+
459
+ def _cancel_hide(self) -> None:
460
+ """Cancela o agendamento de ocultação do hover balloon."""
461
+ if hasattr(self, "_hide_job") and self._hide_job:
462
+ with contextlib.suppress(tk.TclError):
463
+ self.after_cancel(self._hide_job)
464
+ self._hide_job = None
465
+
466
+ def _schedule_hide(self) -> None:
467
+ """Agenda o ocultamento do hover balloon após delay configurado."""
468
+ self._cancel_hide()
469
+ self._hide_job = self.after(500, self._hide_hover)
470
+
471
+ def _make_auto_pair(self, opener: str) -> Callable:
472
+ closer = AUTO_CLOSE[opener]
473
+
474
+ def handler(_e: tk.Event) -> str | None:
475
+ """Insere o par de delimitadores, envolve seleção ou avança o cursor se já fechado."""
476
+ with contextlib.suppress(tk.TclError):
477
+ if self.text.tag_ranges(tk.SEL):
478
+ sel_text = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
479
+ self.text.delete(tk.SEL_FIRST, tk.SEL_LAST)
480
+ self.text.insert(tk.INSERT, opener + sel_text + closer)
481
+ return "break"
482
+ next_char = self.text.get(tk.INSERT)
483
+
484
+ if next_char == closer and opener == closer:
485
+ self.text.mark_set(tk.INSERT, f"{tk.INSERT}+1c")
486
+ return "break"
487
+
488
+ if next_char and next_char not in " \n\t\r)]}\"'":
489
+ return None
490
+ self.text.insert(tk.INSERT, opener + closer)
491
+ self.text.mark_set(tk.INSERT, f"{tk.INSERT}-1c")
492
+ return "break"
493
+
494
+ return handler
495
+
496
+ def _show_context_menu(self, _e: tk.Event) -> None:
497
+ t = self._tmgr.theme
498
+ menu = tk.Menu(
499
+ self,
500
+ tearoff=False,
501
+ bg=t.floating_bg,
502
+ fg=t.fg,
503
+ activebackground=t.sel_bg,
504
+ activeforeground=t.sel_fg,
505
+ relief="flat",
506
+ bd=1,
507
+ )
508
+
509
+ menu.add_command(
510
+ label=_t("edit.context_undo"),
511
+ command=lambda: self.text.event_generate("<<Undo>>"),
512
+ )
513
+ menu.add_command(
514
+ label=_t("edit.context_redo"),
515
+ command=lambda: self.text.event_generate("<<Redo>>"),
516
+ )
517
+ menu.add_separator()
518
+ menu.add_command(
519
+ label=_t("edit.context_cut"),
520
+ command=lambda: self.text.event_generate("<<Cut>>"),
521
+ )
522
+ menu.add_command(
523
+ label=_t("edit.context_copy"),
524
+ command=lambda: self.text.event_generate("<<Copy>>"),
525
+ )
526
+ menu.add_command(
527
+ label=_t("edit.context_paste"),
528
+ command=lambda: self.text.event_generate("<<Paste>>"),
529
+ )
530
+ menu.add_command(
531
+ label=_t("edit.context_select_all"),
532
+ command=lambda: self.text.tag_add(tk.SEL, "1.0", "end"),
533
+ )
534
+ menu.add_separator()
535
+ menu.add_command(label=_t("edit.context_comment"),
536
+ command=self.toggle_comment)
537
+ menu.add_command(
538
+ label=_t("edit.context_duplicate"), command=self.duplicate_line
539
+ )
540
+ menu.add_command(label=_t("edit.context_delete_line"),
541
+ command=self.delete_line)
542
+ menu.add_separator()
543
+ menu.add_command(label=_t("edit.context_format"),
544
+ command=self.format_document)
545
+ menu.add_command(
546
+ label=_t("edit.context_goto_line"), command=self.goto_line_dialog
547
+ )
548
+ plugin_items = self.context_provider("editor", None) if self.context_provider else []
549
+ if plugin_items:
550
+ menu.add_separator()
551
+ for label, action in plugin_items:
552
+ menu.add_command(label=label, command=action)
553
+ menu.add_separator()
554
+
555
+ word = self.get_word_at_cursor()
556
+ nav_sub = tk.Menu(
557
+ menu,
558
+ tearoff=False,
559
+ bg=t.floating_bg,
560
+ fg=t.fg,
561
+ activebackground=t.sel_bg,
562
+ activeforeground=t.sel_fg,
563
+ relief="flat",
564
+ bd=1,
565
+ )
566
+
567
+ def _goto_def():
568
+ if self._lsp_mgr and self.path:
569
+ self.lsp_goto_definition()
570
+ else:
571
+ self._local_goto_definition()
572
+
573
+ nav_sub.add_command(
574
+ label=_t("hc.pane.ir_para_defini_o_f12"), command=_goto_def)
575
+
576
+ def _find_refs():
577
+ if self._lsp_mgr and self.path:
578
+ self.lsp_find_references()
579
+ else:
580
+ self._show_context_info("LSP não disponível para referências")
581
+
582
+ nav_sub.add_command(
583
+ label=_t("hc.pane.localizar_refer_ncias_shift_f1"), command=_find_refs
584
+ )
585
+
586
+ nav_sub.add_command(
587
+ label=_t("hc.pane.localizar_usos_alt_shift_f"),
588
+ command=self._find_all_usages_popup,
589
+ )
590
+
591
+ if self._lsp_mgr and self.path:
592
+ nav_sub.add_separator()
593
+ nav_sub.add_command(
594
+ label="📣 Ir para Declaração",
595
+ command=self.lsp_goto_declaration,
596
+ )
597
+ nav_sub.add_command(
598
+ label="🔷 Ir para Tipo da Definição",
599
+ command=self.lsp_goto_type_definition,
600
+ )
601
+ nav_sub.add_command(
602
+ label="⚙ Ir para Implementação (Ctrl+F12)",
603
+ command=self.lsp_goto_implementation,
604
+ )
605
+ nav_sub.add_separator()
606
+ nav_sub.add_command(
607
+ label="Code Actions (Ctrl+.)",
608
+ command=self.lsp_code_action,
609
+ )
610
+ nav_sub.add_command(
611
+ label="✏️ Renomear Símbolo (F6)",
612
+ command=self.lsp_rename_symbol,
613
+ )
614
+ nav_sub.add_separator()
615
+ nav_sub.add_command(
616
+ label="📋 Hierarquia: Chamadas Entrantes",
617
+ command=self.lsp_incoming_calls,
618
+ )
619
+ nav_sub.add_command(
620
+ label="📤 Hierarquia: Chamadas Saindo",
621
+ command=self.lsp_outgoing_calls,
622
+ )
623
+
624
+ label = f"🧭 Navegar: '{word}'" if word else "🧭 Navegar"
625
+ menu.add_cascade(label=label, menu=nav_sub)
626
+ menu.add_separator()
627
+
628
+ def _mk_sub():
629
+ return tk.Menu(
630
+ menu,
631
+ tearoff=False,
632
+ bg=t.floating_bg,
633
+ fg=t.fg,
634
+ activebackground=t.sel_bg,
635
+ activeforeground=t.sel_fg,
636
+ relief="flat",
637
+ bd=1,
638
+ )
639
+
640
+ try:
641
+ from src.editor.text_transforms import (
642
+ TRANSFORMS,
643
+ apply_transform,
644
+ insert_at_cursor,
645
+ )
646
+
647
+ _tt_ok = True
648
+ except ImportError:
649
+ _tt_ok = False
650
+
651
+ if _tt_ok:
652
+ trans_sub = _mk_sub()
653
+ _case_items = [
654
+ ("camel", "camelCase"),
655
+ ("pascal", "PascalCase"),
656
+ ("snake", "snake_case"),
657
+ ("kebab", "kebab-case"),
658
+ ("constant", "CONSTANT_CASE"),
659
+ ]
660
+ for key, label_t in _case_items:
661
+ entry = TRANSFORMS[key]
662
+ trans_sub.add_command(
663
+ label=f"{entry[2]} {label_t}",
664
+ command=lambda k=key: apply_transform(self.text, k),
665
+ )
666
+ trans_sub.add_separator()
667
+ _enc_items = [
668
+ ("b64enc", "Base64 Encode"),
669
+ ("b64dec", "Base64 Decode"),
670
+ ("urlenc", "URL Encode"),
671
+ ("urldec", "URL Decode"),
672
+ ("htmlesc", "HTML Escape"),
673
+ ("htmlune", "HTML Unescape"),
674
+ ("jsonesc", "JSON Escape"),
675
+ ]
676
+ for key, label_t in _enc_items:
677
+ entry = TRANSFORMS[key]
678
+ trans_sub.add_command(
679
+ label=f"{entry[2]} {label_t}",
680
+ command=lambda k=key: apply_transform(self.text, k),
681
+ )
682
+ trans_sub.add_separator()
683
+ _hash_items = [("md5", "MD5"), ("sha1", "SHA-1"),
684
+ ("sha256", "SHA-256")]
685
+ for key, label_t in _hash_items:
686
+ trans_sub.add_command(
687
+ label=f"# {label_t} Hash",
688
+ command=lambda k=key: apply_transform(self.text, k),
689
+ )
690
+ trans_sub.add_separator()
691
+ _line_items = [
692
+ ("dedup", "Remover Linhas Duplicadas"),
693
+ ("revlines", "Inverter Linhas"),
694
+ ("numlines", "Numerar Linhas"),
695
+ ("remempty", "Remover Linhas Vazias"),
696
+ ]
697
+ for key, label_t in _line_items:
698
+ entry = TRANSFORMS[key]
699
+ trans_sub.add_command(
700
+ label=f"{entry[2]} {label_t}",
701
+ command=lambda k=key: apply_transform(self.text, k),
702
+ )
703
+ menu.add_cascade(
704
+ label=_t("edit.context_transform", "Transformar"),
705
+ menu=trans_sub,
706
+ )
707
+
708
+ ins_sub = _mk_sub()
709
+ _ins_items = [
710
+ ("uuid", "UUID v4"),
711
+ ("ts_iso", "Timestamp ISO 8601"),
712
+ ("ts_date", "Data (YYYY-MM-DD)"),
713
+ ("ts_unix", "Unix Timestamp"),
714
+ ("lorem1", "Lorem Ipsum (1 frase)"),
715
+ ("lorem3", "Lorem Ipsum (3 frases)"),
716
+ ("lorem5", "Lorem Ipsum (5 frases)"),
717
+ ]
718
+ for key, label_t in _ins_items:
719
+ ins_sub.add_command(
720
+ label=label_t,
721
+ command=lambda k=key: insert_at_cursor(self.text, k),
722
+ )
723
+ menu.add_cascade(
724
+ label=_t("edit.context_insert", "➕ Inserir"),
725
+ menu=ins_sub,
726
+ )
727
+ menu.add_separator()
728
+
729
+ menu.add_command(label=_t("edit.context_copy_path"),
730
+ command=self._copy_path)
731
+ menu.add_command(
732
+ label=_t("edit.context_reveal"), command=self._reveal_in_explorer
733
+ )
734
+
735
+ try:
736
+ cursor_idx = self.text.index(f"@{_e.x},{_e.y}")
737
+ cursor_line = int(cursor_idx.split(".")[0])
738
+ except (tk.TclError, ValueError, AttributeError):
739
+ cursor_line = -1
740
+
741
+ line_diags = [d for d in self._diags if d.line ==
742
+ cursor_line and d.fix]
743
+ all_fixable = [d for d in self._diags if d.fix]
744
+
745
+ if line_diags or all_fixable:
746
+ menu.add_separator()
747
+
748
+ for d in line_diags:
749
+ _d = d
750
+ label_fix = f"🔧 Corrigir: {d.rule or d.message[:40]}"
751
+ menu.add_command(
752
+ label=label_fix,
753
+ command=lambda diag=_d: self._apply_single_fix(diag),
754
+ )
755
+
756
+ if line_diags:
757
+ for d in line_diags:
758
+ if d.rule:
759
+ same_rule = [
760
+ x for x in self._diags if x.fix and x.rule == d.rule
761
+ ]
762
+ if len(same_rule) > 1:
763
+ _same = same_rule
764
+ menu.add_command(
765
+ label=f"🔧 Corrigir todas: {d.rule} ({len(same_rule)})",
766
+ command=lambda diags=_same: self._apply_fix_list(
767
+ diags),
768
+ )
769
+ break
770
+
771
+ if all_fixable:
772
+ menu.add_command(
773
+ label=f"✅ Corrigir todas as falhas do arquivo ({len(all_fixable)})",
774
+ command=self.fix_all,
775
+ )
776
+
777
+ try:
778
+ menu.tk_popup(_e.x_root, _e.y_root)
779
+ finally:
780
+ menu.grab_release()
781
+
782
+ def _apply_single_fix(self, diag: Diag) -> None:
783
+ """Aplica o fix de um único diagnóstico ESLint no editor.
784
+
785
+ Args:
786
+ diag: Diagnóstico com campo ``fix`` (dict com ``range`` e ``text``).
787
+ """
788
+ if not diag.fix or not self.path:
789
+ return
790
+ try:
791
+ content = self.text.get("1.0", "end-1c")
792
+ from src.lint.manager import LintManager
793
+
794
+ fixed = LintManager.apply_eslint_fix(content, diag.fix)
795
+ if fixed != content:
796
+ self.set_content(fixed)
797
+ except Exception as exc:
798
+ import logging
799
+
800
+ logging.getLogger("Codis").warning("_apply_single_fix: %s", exc)
801
+
802
+ def _apply_fix_list(self, diags: list[Diag]) -> None:
803
+ """Aplica uma lista de fixes num único passo atômico.
804
+
805
+ Usa o algoritmo de merge do ESLint via ``apply_all_eslint_fixes``:
806
+ ordena por posição, descarta sobrepostos e aplica numa única varredura.
807
+ Nunca aplica fixes sequencialmente sobre texto já modificado.
808
+
809
+ Args:
810
+ diags: Lista de diagnósticos com fix disponível.
811
+ """
812
+ if not diags or not self.path:
813
+ return
814
+ try:
815
+ content = self.text.get("1.0", "end-1c")
816
+ fixed = self._lint_mgr.apply_all_eslint_fixes(
817
+ self.path, content, diags)
818
+ if fixed != content:
819
+ self.set_content(fixed)
820
+ except Exception as exc:
821
+ import logging
822
+
823
+ logging.getLogger("Codis").warning("_apply_fix_list: %s", exc)
824
+
825
+ def _diags_for_line(self, line: int) -> list:
826
+ """Retorna os diagnósticos de ``line`` usando um índice por linha.
827
+
828
+ O índice é reconstruído só quando a lista de diagnósticos muda, em vez
829
+ de varrê-la inteira a cada movimento do mouse.
830
+ """
831
+ source = self._diags
832
+ if self._diag_index_src is not source or self._diag_index_len != len(source):
833
+ index: dict[int, list] = {}
834
+ for diag in source:
835
+ index.setdefault(diag.line, []).append(diag)
836
+ self._diag_index = index
837
+ self._diag_index_src = source
838
+ self._diag_index_len = len(source)
839
+ return self._diag_index.get(line, [])
840
+
841
+ def _on_mouse_motion_diag(self, e: tk.Event) -> None:
842
+ """Mostra tooltip de diagnóstico ao passar o mouse sobre uma linha com erro/aviso.
843
+
844
+ O handler é limitado a ~30 Hz e não recria o balão enquanto o mouse
845
+ continua sobre a mesma linha.
846
+
847
+ Args:
848
+ e: Evento de movimento do mouse.
849
+ """
850
+ now = time.monotonic()
851
+ if now - self._diag_motion_t < _MOTION_MIN_INTERVAL_S:
852
+ return
853
+ self._diag_motion_t = now
854
+ try:
855
+ idx = self.text.index(f"@{e.x},{e.y}")
856
+ line = int(idx.split(".")[0])
857
+ except (tk.TclError, ValueError):
858
+ self._hide_diag_tip()
859
+ return
860
+
861
+ line_diags = self._diags_for_line(line)
862
+ if not line_diags:
863
+ if self._diag_tip_job or self._diag_tip_win:
864
+ self._hide_diag_tip()
865
+ return
866
+
867
+ if line == self._diag_tip_line and (self._diag_tip_job or self._diag_tip_win):
868
+ return
869
+
870
+ if self._diag_tip_job:
871
+ with contextlib.suppress(tk.TclError):
872
+ self.text.after_cancel(self._diag_tip_job)
873
+ self._diag_tip_line = line
874
+ self._diag_tip_job = self.text.after(
875
+ 400, lambda: self._show_diag_tip(e.x_root, e.y_root, line_diags)
876
+ )
877
+
878
+ def _show_diag_tip(self, rx: int, ry: int, diags: list[Diag]) -> None:
879
+ """Exibe o balão com os erros do linter para a linha.
880
+
881
+ Args:
882
+ rx: Coordenada X global.
883
+ ry: Coordenada Y global.
884
+ diags: Lista de diagnósticos da linha.
885
+ """
886
+ self._hide_diag_tip()
887
+ t = self._tmgr.theme
888
+ win = tk.Toplevel(self)
889
+ win.wm_overrideredirect(True)
890
+ win.wm_attributes("-topmost", True)
891
+
892
+ frame = tk.Frame(
893
+ win,
894
+ bg=t.floating_bg,
895
+ highlightthickness=1,
896
+ highlightbackground=t.floating_border,
897
+ )
898
+ frame.pack()
899
+
900
+ _SEV_COLOR = {
901
+ 1: getattr(t, "err_fg", "#f87171"),
902
+ 2: getattr(t, "warn_fg", "#fabd2f"),
903
+ 3: getattr(t, "info_fg", "#89dceb"),
904
+ 4: getattr(t, "hint_fg", "#a6e3a1"),
905
+ }
906
+ _SEV_ICON = {1: "✖", 2: "⚠", 3: "ℹ", 4: "-"}
907
+
908
+ for d in diags[:5]:
909
+ icon = _SEV_ICON.get(d.severity, "·")
910
+ color = _SEV_COLOR.get(d.severity, t.fg)
911
+ rule_txt = f" [{d.rule}]" if d.rule else ""
912
+ text = f"{icon} {d.message}{rule_txt}"
913
+ tk.Label(
914
+ frame,
915
+ text=text,
916
+ bg=t.floating_bg,
917
+ fg=color,
918
+ font=(self._font_family, self._font_size - 1),
919
+ padx=8,
920
+ pady=2,
921
+ anchor="w",
922
+ justify="left",
923
+ wraplength=400,
924
+ ).pack(fill="x")
925
+
926
+ if len(diags) > 5:
927
+ tk.Label(
928
+ frame,
929
+ text=f" … e mais {len(diags) - 5} problema(s)",
930
+ bg=t.floating_bg,
931
+ fg=t.fg_muted,
932
+ font=(self._font_family, self._font_size - 2),
933
+ padx=8,
934
+ pady=2,
935
+ anchor="w",
936
+ ).pack(fill="x")
937
+
938
+ win.geometry(f"+{rx + 14}+{ry + 14}")
939
+ self._diag_tip_win = win
940
+ self._diag_tip_line = diags[0].line if diags else None
941
+
942
+ win.bind("<Enter>", lambda _: None)
943
+
944
+ def _hide_diag_tip(self, _e=None) -> None:
945
+ """Oculta o tooltip de diagnóstico do linter."""
946
+
947
+ if self._diag_tip_job:
948
+ with contextlib.suppress(tk.TclError):
949
+ self.text.after_cancel(self._diag_tip_job)
950
+ self._diag_tip_job = None
951
+ if self._diag_tip_win and self._diag_tip_win.winfo_exists():
952
+ with contextlib.suppress(tk.TclError):
953
+ self._diag_tip_win.destroy()
954
+ self._diag_tip_win = None
955
+ self._diag_tip_line = None
956
+
957
+ def _local_goto_definition(self) -> None:
958
+ """Vai para a definição sem LSP - busca puramente textual no arquivo."""
959
+ word = self.get_word_at_cursor()
960
+ if not word:
961
+ return
962
+ idx = self.text.index(tk.INSERT)
963
+ line = int(idx.split(".", maxsplit=1)[0])
964
+ full = self.text.get("1.0", "end-1c")
965
+ def_line = find_definition_line(word, full, line)
966
+ if def_line:
967
+ self.goto_line(def_line)
968
+ else:
969
+ self._show_context_info(f"Sem definição para '{word}'")
970
+
971
+ def _find_all_usages_popup(self) -> None:
972
+ """Abre popup com todas as referências do símbolo sob o cursor."""
973
+ word = self.get_word_at_cursor()
974
+ if not word:
975
+ return
976
+ if self._is_large_mode or self._is_giant_mode:
977
+ self._show_context_info(
978
+ "Busca de usos desativada para arquivos grandes")
979
+ return
980
+ full = self.text.get("1.0", "end-1c")
981
+ lines = full.splitlines()
982
+ usages = find_all_usages(word, full)
983
+ if not usages:
984
+ self._show_context_info(f"Sem usos de '{word}' encontrados")
985
+ return
986
+
987
+ t = self._tmgr.theme
988
+ sx = self.text.winfo_rootx() + 80
989
+ sy = self.text.winfo_rooty() + 60
990
+
991
+ win = tk.Toplevel(self)
992
+ win.wm_overrideredirect(True)
993
+ win.wm_attributes("-topmost", True)
994
+ win.geometry("+9999+9999")
995
+
996
+ outer = tk.Frame(
997
+ win, bg=getattr(t, "floating_border", "#3d4455"), padx=1, pady=1
998
+ )
999
+ outer.pack(fill="both", expand=True)
1000
+ inner = tk.Frame(outer, bg=t.floating_bg)
1001
+ inner.pack(fill="both", expand=True)
1002
+
1003
+ hdr = tk.Frame(inner, bg=getattr(t, "activity_bg", t.floating_bg))
1004
+ hdr.pack(fill="x")
1005
+ tk.Label(
1006
+ hdr,
1007
+ text=f" 🔍 {len(usages)} usos de '{word}'",
1008
+ bg=hdr["bg"],
1009
+ fg=t.fg,
1010
+ font=(FONT_UI, 9, "bold"),
1011
+ ).pack(side="left", padx=6, pady=5)
1012
+ close = tk.Label(
1013
+ hdr,
1014
+ text="✕",
1015
+ bg=hdr["bg"],
1016
+ fg=t.fg_muted,
1017
+ font=(FONT_UI, 9),
1018
+ cursor="hand2",
1019
+ padx=8,
1020
+ )
1021
+ close.pack(side="right", pady=5)
1022
+ close.bind("<Button-1>", lambda _: win.destroy())
1023
+
1024
+ tk.Frame(inner, bg=getattr(t, "border", "#3d4455"),
1025
+ height=1).pack(fill="x")
1026
+
1027
+ canvas = tk.Canvas(
1028
+ inner,
1029
+ bg=t.floating_bg,
1030
+ highlightthickness=0,
1031
+ width=420,
1032
+ height=min(len(usages), 18) * 22 + 4,
1033
+ )
1034
+ vsb = tk.Scrollbar(inner, orient="vertical", command=canvas.yview)
1035
+ canvas.config(yscrollcommand=vsb.set)
1036
+ vsb.pack(side="right", fill="y")
1037
+ canvas.pack(fill="both", expand=True)
1038
+
1039
+ lf = tk.Frame(canvas, bg=t.floating_bg)
1040
+ win_id = canvas.create_window((0, 0), window=lf, anchor="nw")
1041
+ lf.bind("<Configure>", lambda _: canvas.config(
1042
+ scrollregion=canvas.bbox("all")))
1043
+ canvas.bind(
1044
+ "<Configure>",
1045
+ lambda _: canvas.itemconfig(win_id, width=canvas.winfo_width()),
1046
+ )
1047
+
1048
+ mono = getattr(t, "font_mono", FONT_MONO)
1049
+ for ln in usages:
1050
+ row_bg = t.floating_bg
1051
+ text_preview = lines[ln - 1].strip()[:70]
1052
+ row = tk.Frame(lf, bg=row_bg, cursor="hand2")
1053
+ row.pack(fill="x", padx=4, pady=1)
1054
+ num_lbl = tk.Label(
1055
+ row,
1056
+ text=f"{ln:4d} ",
1057
+ bg=row_bg,
1058
+ fg=t.fg_muted,
1059
+ font=(mono, 8),
1060
+ width=5,
1061
+ anchor="e",
1062
+ )
1063
+ num_lbl.pack(side="left")
1064
+ code_lbl = tk.Label(
1065
+ row, text=text_preview, bg=row_bg, fg=t.fg, font=(mono, 8), anchor="w"
1066
+ )
1067
+ code_lbl.pack(side="left", fill="x", expand=True)
1068
+
1069
+ def _on_click(l_=ln, w=win):
1070
+ w.destroy()
1071
+ self.goto_line(l_)
1072
+
1073
+ def _enter(_ev, r=row, nl=num_lbl, cl=code_lbl):
1074
+ r.config(bg=t.sel_bg)
1075
+ nl.config(bg=t.sel_bg)
1076
+ cl.config(bg=t.sel_bg)
1077
+
1078
+ def _leave(_ev, r=row, nl=num_lbl, cl=code_lbl, bg=row_bg):
1079
+ r.config(bg=bg)
1080
+ nl.config(bg=bg)
1081
+ cl.config(bg=bg)
1082
+
1083
+ for w2 in (row, num_lbl, code_lbl):
1084
+ w2.bind("<Button-1>", lambda ev, l_=ln, fn=_on_click: fn(l_))
1085
+ w2.bind("<Enter>", _enter)
1086
+ w2.bind("<Leave>", _leave)
1087
+
1088
+ def _wheel(ev):
1089
+ delta = -1 * \
1090
+ (ev.delta // 120) if ev.delta else (1 if ev.num == 5 else -1)
1091
+ canvas.yview_scroll(delta, "units")
1092
+
1093
+ canvas.bind("<MouseWheel>", _wheel)
1094
+ canvas.bind("<Button-4>", _wheel)
1095
+ canvas.bind("<Button-5>", _wheel)
1096
+
1097
+ win.bind("<Escape>", lambda _: win.destroy())
1098
+ win.bind("<FocusOut>", lambda _: win.destroy()
1099
+ if win.winfo_exists() else None)
1100
+
1101
+ win.update_idletasks()
1102
+ w2 = win.winfo_reqwidth()
1103
+ h2 = win.winfo_reqheight()
1104
+ sw = self.winfo_screenwidth()
1105
+ sh = self.winfo_screenheight()
1106
+ bx = min(sx, sw - w2 - 8)
1107
+ by = min(sy, sh - h2 - 8)
1108
+ win.geometry(f"+{bx}+{by}")
1109
+
1110
+ def _show_context_info(self, msg: str) -> None:
1111
+ """Exibe brevemente uma mensagem informativa próxima ao editor."""
1112
+ t = self._tmgr.theme
1113
+ sx = self.text.winfo_rootx() + 40
1114
+ sy = self.text.winfo_rooty() + self.text.winfo_height() - 40
1115
+ tip = tk.Toplevel(self.winfo_toplevel())
1116
+ tip.wm_overrideredirect(True)
1117
+ tip.wm_attributes("-topmost", True)
1118
+ tip.geometry("+9999+9999")
1119
+ frm = tk.Frame(
1120
+ tip,
1121
+ bg=t.floating_bg,
1122
+ highlightthickness=1,
1123
+ highlightbackground=getattr(t, "floating_border", "#3d4455"),
1124
+ )
1125
+ frm.pack()
1126
+ tk.Label(
1127
+ frm,
1128
+ text=msg,
1129
+ bg=t.floating_bg,
1130
+ fg=t.fg_muted,
1131
+ font=(FONT_UI, 9),
1132
+ padx=10,
1133
+ pady=6,
1134
+ ).pack()
1135
+ tip.update_idletasks()
1136
+ tip.winfo_reqwidth()
1137
+ tip.geometry(f"+{sx}+{sy}")
1138
+ tip.after(2500, tip.destroy)
1139
+
1140
+ def _copy_path(self) -> None:
1141
+ """Copia o caminho do arquivo para a área de transferência."""
1142
+ if self.path:
1143
+ self.clipboard_clear()
1144
+ self.clipboard_append(str(self.path))
1145
+
1146
+ def _reveal_in_explorer(self) -> None:
1147
+ """Abre o explorador de arquivos do sistema com o arquivo selecionado."""
1148
+ if self.path:
1149
+ with contextlib.suppress(OSError):
1150
+ if sys.platform == "win32":
1151
+ subprocess.Popen(["explorer", "/select,", str(self.path)])
1152
+ elif sys.platform == "darwin":
1153
+ subprocess.Popen(["open", "-R", str(self.path)])
1154
+ else:
1155
+ subprocess.Popen(["xdg-open", str(self.path.parent)])
1156
+
1157
+ def _update_cursor(self) -> None:
1158
+ """Atualiza o cursor visual de acordo com o modo LSP ativo."""
1159
+ with contextlib.suppress(tk.TclError):
1160
+ idx = self.text.index(tk.INSERT)
1161
+ ln, col = map(int, idx.split("."))
1162
+ self.gutter.set_current_line(ln)
1163
+ self._on_cursor(ln + (self._viewport_start if self._is_giant_mode else 0), col + 1)
1164
+
1165
+ with contextlib.suppress(tk.TclError):
1166
+ if self.inline_blame and self._blame_enabled:
1167
+ self.inline_blame.notify_cursor_moved()
1168
+
1169
+ def _on_marked_lines_change(self, lines: set[int]) -> None:
1170
+ """Chamado quando o conjunto de linhas marcadas no gutter muda."""
1171
+ self._multicursor_lines = lines
1172
+ if lines:
1173
+ self._multicursor_active = True
1174
+
1175
+ self.text.tag_remove("multicursor_line", "1.0", "end")
1176
+ for ln in lines:
1177
+ self.text.tag_add("multicursor_line",
1178
+ f"{ln}.0", f"{ln}.end+1c")
1179
+ t = self._tmgr.theme
1180
+ accent = getattr(t, "accent", "#4fc3f7")
1181
+
1182
+ from src.theme.utils import hex_blend
1183
+
1184
+ hl = hex_blend(t.editor_bg, accent, 0.15)
1185
+ self.text.tag_configure("multicursor_line", background=hl)
1186
+ else:
1187
+ self._multicursor_active = False
1188
+ self.text.tag_remove("multicursor_line", "1.0", "end")
1189
+
1190
+ with contextlib.suppress(tk.TclError):
1191
+ self.text.tag_lower("multicursor_line")
1192
+
1193
+ def _multicursor_insert(self, char: str) -> None:
1194
+ """Insere char no início de cada linha marcada (multicursor simultâneo).
1195
+
1196
+ Usado para edição síncrona de múltiplas linhas quando multicursor
1197
+ está ativo. Insere na coluna 0 de cada linha marcada.
1198
+ """
1199
+ if not self._multicursor_lines:
1200
+ return
1201
+
1202
+ for ln in sorted(self._multicursor_lines, reverse=True):
1203
+ with contextlib.suppress(tk.TclError):
1204
+ self.text.insert(f"{ln}.0", char)
1205
+ self.gutter.redraw()
1206
+
1207
+ def _multicursor_delete_col(self, col: int = 0) -> None:
1208
+ """Remove o caractere na coluna col de cada linha marcada."""
1209
+ for ln in sorted(self._multicursor_lines, reverse=True):
1210
+ with contextlib.suppress(tk.TclError):
1211
+ ch = self.text.get(f"{ln}.{col}", f"{ln}.{col + 1}")
1212
+ if ch and ch != "\n":
1213
+ self.text.delete(f"{ln}.{col}", f"{ln}.{col + 1}")
1214
+
1215
+ def _on_modified(self, _e: Any = None) -> None:
1216
+ with contextlib.suppress(tk.TclError):
1217
+ if self.text.edit_modified():
1218
+ if not self.modified:
1219
+ self.modified = True
1220
+ name = self.path.name if self.path else _t(
1221
+ "ui.tab_untitled")
1222
+ self._on_title(name, True)
1223
+ self._on_change()
1224
+ self.text.edit_modified(False)
1225
+ if getattr(self, "ligature_engine", None):
1226
+ self.ligature_engine.on_change()
1227
+
1228
+ def load(self, path: Path) -> bool:
1229
+ """Carrega um arquivo no editor usando a estratégia adequada ao tamanho.
1230
+
1231
+ Tier 1 (< GIANT_FILE_BYTES): inserção assíncrona em chunks, features pesadas off.
1232
+ Tier 2 (>= GIANT_FILE_BYTES): viewport virtual via mmap, só VIEWPORT_LINES linhas.
1233
+
1234
+ Antes de qualquer carga, verifica se o arquivo é binário, compactado ou de formato
1235
+ não gerenciável - exibindo um diálogo apropriado em cada caso.
1236
+ """
1237
+ self._close_vfb()
1238
+ try:
1239
+ file_size = path.stat().st_size
1240
+ except OSError as exc:
1241
+ messagebox.showerror(
1242
+ _t("err.file_not_found_title"), _t(
1243
+ "err.file_open", err=str(exc))
1244
+ )
1245
+ return False
1246
+
1247
+ _IMAGE_EXTS = {
1248
+ ".png",
1249
+ ".jpg",
1250
+ ".jpeg",
1251
+ ".bmp",
1252
+ ".gif",
1253
+ ".webp",
1254
+ ".tiff",
1255
+ ".tif",
1256
+ ".ico",
1257
+ ".svg",
1258
+ }
1259
+ _MEDIA_EXTS = {
1260
+ ".mp3",
1261
+ ".mp4",
1262
+ ".wav",
1263
+ ".ogg",
1264
+ ".flac",
1265
+ ".aac",
1266
+ ".m4a",
1267
+ ".webm",
1268
+ ".mkv",
1269
+ ".avi",
1270
+ ".mov",
1271
+ ".wma",
1272
+ }
1273
+ ext = path.suffix.lower()
1274
+ if ext in _IMAGE_EXTS:
1275
+ self._open_image_viewer(path)
1276
+ return False
1277
+ if ext in _MEDIA_EXTS:
1278
+ self._open_media_player(path)
1279
+ return False
1280
+
1281
+ guard = self._guard_binary(path, file_size)
1282
+ if guard == "cancel":
1283
+ return False
1284
+ if guard == "archive":
1285
+ self._open_archive_viewer(path)
1286
+ return False
1287
+
1288
+ if file_size >= GIANT_FILE_BYTES and _VFB_AVAILABLE:
1289
+ return self._load_tier2(path, file_size)
1290
+
1291
+ lang_hint = EXT_LANG.get(path.suffix.lower(), "text")
1292
+ _TEXT_LANGS = {"text", "markdown", "plaintext", ""}
1293
+ force_tier1 = (
1294
+ guard != "force_text"
1295
+ and lang_hint not in _TEXT_LANGS
1296
+ and file_size >= LARGE_CODE_BYTES
1297
+ )
1298
+ if file_size >= LARGE_FILE_BYTES or force_tier1:
1299
+ return self._load_tier1(path, file_size)
1300
+ return self._load_tier0(path)
1301
+
1302
+ _ARCHIVE_MAGIC: list[tuple[bytes, int, str]] = [
1303
+ (b"PK\x03\x04", 0, "zip"),
1304
+ (b"PK\x05\x06", 0, "zip"),
1305
+ (b"Rar!\x1a\x07\x00", 0, "rar"),
1306
+ (b"Rar!\x1a\x07\x01", 0, "rar"),
1307
+ (b"7z\xbc\xaf\x27\x1c", 0, "7z"),
1308
+ (b"\x1f\x8b", 0, "gz"),
1309
+ (b"BZh", 0, "bz2"),
1310
+ (b"ustar", 257, "tar"),
1311
+ ]
1312
+
1313
+ _MAX_UNMANAGED_OPEN = 500 * 1024 * 1024
1314
+
1315
+ def _guard_binary(self, path: Path, file_size: int) -> str:
1316
+ """Verifica se o arquivo é binário, compactado ou não gerenciável.
1317
+
1318
+ Lê os primeiros 512 bytes e analisa magic bytes + null bytes.
1319
+
1320
+ Returns:
1321
+ 'ok' - pode abrir normalmente
1322
+ 'cancel' - usuário cancelou / arquivo bloqueado
1323
+ 'force_text' - usuário forçou exibição em modo texto
1324
+ 'archive' - usuário quer visualizar como arquivo compactado
1325
+ """
1326
+ if file_size == 0:
1327
+ return "ok"
1328
+
1329
+ read_size = min(file_size, 512)
1330
+ try:
1331
+ with open(path, "rb") as fh:
1332
+ header = fh.read(read_size)
1333
+ except OSError:
1334
+ return "ok"
1335
+
1336
+ for magic, offset, kind in self._ARCHIVE_MAGIC:
1337
+ end = offset + len(magic)
1338
+ if len(header) >= end and header[offset:end] == magic:
1339
+ return self._ask_archive_action(path, kind, file_size)
1340
+
1341
+ if header[:2] in (b"\xff\xfe", b"\xfe\xff"):
1342
+ return "ok"
1343
+
1344
+ check = header[3:] if header[:3] == b"\xef\xbb\xbf" else header
1345
+ if b"\x00" in check[:512]:
1346
+ if file_size > self._MAX_UNMANAGED_OPEN:
1347
+ size_gb = file_size / (1024**3)
1348
+ ext = path.suffix or "desconhecido"
1349
+ messagebox.showwarning(
1350
+ "Arquivo não suportado",
1351
+ f'O arquivo "{path.name}" ({size_gb:.1f} GB) é um binário de grande '
1352
+ f'porte sem gerenciador registrado para o formato "{ext}".\n\n'
1353
+ "Para abri-lo, instale uma extensão que suporte este formato ou ative "
1354
+ "o modo 'Forçar exibição' nas configurações.",
1355
+ )
1356
+ return "cancel"
1357
+ return self._ask_binary_force(path, file_size)
1358
+
1359
+ return "ok"
1360
+
1361
+ def _ask_archive_action(self, path: Path, kind: str, file_size: int) -> str:
1362
+ """Diálogo para arquivo compactado: listar conteúdo, forçar texto ou cancelar."""
1363
+ label_map = {
1364
+ "zip": "ZIP",
1365
+ "rar": "RAR",
1366
+ "7z": "7-Zip",
1367
+ "gz": "GZip",
1368
+ "bz2": "BZip2",
1369
+ "tar": "TAR",
1370
+ }
1371
+ label = label_map.get(kind, kind.upper())
1372
+ size_mb = file_size / (1024 * 1024)
1373
+
1374
+ native_browser = kind == "zip"
1375
+
1376
+ if native_browser:
1377
+ msg = (
1378
+ f'O arquivo "{path.name}" ({size_mb:.1f} MB) é um arquivo {label}.\n\n'
1379
+ "- Listar conteudo - abre o visualizador de arquivo compactado\n"
1380
+ "- Forcar exibicao - abre os bytes brutos como texto (pode ser ilegivel)\n"
1381
+ "- Cancelar - nao abre o arquivo"
1382
+ )
1383
+ choice = _BinaryDialog.ask(
1384
+ self,
1385
+ title=f"Arquivo {label} detectado",
1386
+ message=msg,
1387
+ buttons=[
1388
+ ("📂 Listar conteúdo", "archive"),
1389
+ ("📄 Forçar exibição", "force_text"),
1390
+ ("Cancelar", "cancel"),
1391
+ ],
1392
+ )
1393
+ else:
1394
+ msg = (
1395
+ f'O arquivo "{path.name}" ({size_mb:.1f} MB) é um arquivo {label}.\n\n'
1396
+ f"O Codis não possui visualizador nativo para o formato {label}.\n"
1397
+ "Instale uma extensão que suporte este formato, ou force a exibição "
1398
+ "dos dados binários como texto.\n\n"
1399
+ "- Forcar exibicao - mostra os bytes brutos (pode ser ilegivel)\n"
1400
+ "- Cancelar"
1401
+ )
1402
+ choice = _BinaryDialog.ask(
1403
+ self,
1404
+ title=f"Arquivo {label} detectado",
1405
+ message=msg,
1406
+ buttons=[
1407
+ ("📄 Forçar exibição", "force_text"),
1408
+ ("Cancelar", "cancel"),
1409
+ ],
1410
+ )
1411
+ return choice or "cancel"
1412
+
1413
+ def _ask_binary_force(self, path: Path, file_size: int) -> str:
1414
+ """Diálogo para arquivo binário genérico: forçar exibição ou cancelar."""
1415
+ size_mb = file_size / (1024 * 1024)
1416
+ ext = path.suffix or "sem extensão"
1417
+ msg = (
1418
+ f'O arquivo "{path.name}" ({size_mb:.1f} MB) parece ser um binário '
1419
+ f"não reconhecido (formato: {ext}).\n\n"
1420
+ "Forçar a exibição pode mostrar caracteres ilegíveis ou travar o editor "
1421
+ "em arquivos muito grandes.\n\n"
1422
+ "- Forcar exibicao - abre mesmo assim\n"
1423
+ "- Cancelar"
1424
+ )
1425
+ choice = _BinaryDialog.ask(
1426
+ self,
1427
+ title=_t("editor.binary_detected"),
1428
+ message=msg,
1429
+ buttons=[
1430
+ ("⚠️ Forçar exibição", "force_text"),
1431
+ ("Cancelar", "cancel"),
1432
+ ],
1433
+ )
1434
+ return choice or "cancel"
1435
+
1436
+ def _open_image_viewer(self, path: Path) -> None:
1437
+ """Abre uma imagem no Paint integrado do Codis."""
1438
+ try:
1439
+ from src.ui.paint_panel import PaintPanel
1440
+
1441
+ win = tk.Toplevel(self)
1442
+ win.title(f"Cor: {path.name}")
1443
+ win.geometry("900x650")
1444
+ panel = PaintPanel(win, self._tmgr, initial_path=path)
1445
+ panel.pack(fill="both", expand=True)
1446
+ except Exception as exc:
1447
+ logger.warning("PaintPanel (imagem) falhou: %s", exc)
1448
+ messagebox.showerror(_t("editor.open_file_error"), str(exc))
1449
+
1450
+ def _open_media_player(self, path: Path) -> None:
1451
+ """Abre um arquivo de áudio/vídeo no Zen Media Player."""
1452
+ try:
1453
+ from src.ui.zen_media import ZenMediaPlayer
1454
+
1455
+ player = ZenMediaPlayer(tk_root=self.winfo_toplevel())
1456
+ player.set_playlist([str(path)])
1457
+ player.show() # pylint: disable=no-member
1458
+ except Exception as exc:
1459
+ logger.warning("ZenMediaPlayer falhou: %s", exc)
1460
+ messagebox.showerror(_t("editor.open_file_error"), str(exc))
1461
+
1462
+ def _open_archive_viewer(self, path: Path) -> None:
1463
+ """Abre o visualizador de arquivo compactado em uma nova janela."""
1464
+ try:
1465
+ from src.ui.archive_panel import ArchivePanel
1466
+
1467
+ win = tk.Toplevel(self)
1468
+ win.title(f"📦 {path.name}")
1469
+ win.geometry("700x500")
1470
+ panel = ArchivePanel(
1471
+ win, path, on_open_file=self._on_archive_extract)
1472
+ panel.pack(fill="both", expand=True)
1473
+ except Exception as exc:
1474
+ logger.warning("ArchivePanel falhou: %s", exc)
1475
+ messagebox.showerror(_t("editor.open_file_error"), str(exc))
1476
+
1477
+ def _on_archive_extract(self, extracted_path: Path) -> None:
1478
+ """Callback do ArchivePanel: abre o arquivo extraído no editor."""
1479
+ self.load(extracted_path)
1480
+
1481
+ def _load_tier0(self, path: Path) -> bool:
1482
+ """Carrega o arquivo em tier-0 (síncrono, somente leitura). Retorna True se bem-sucedido."""
1483
+ try:
1484
+ self.path = path
1485
+ self.lang = EXT_LANG.get(path.suffix.lower(), "text")
1486
+ if self.code_folding:
1487
+ self.code_folding.set_lang(self.lang)
1488
+ self._is_large_mode = False
1489
+ self._is_giant_mode = False
1490
+ self._viewport_start = 0
1491
+
1492
+ raw = path.read_bytes()
1493
+ content = self._decode_bytes(raw)
1494
+ if raw.startswith(b"\xef\xbb\xbf"):
1495
+ self.encoding = "UTF-8 BOM"
1496
+ del raw
1497
+ content, self.eol = self._normalize_eol(content)
1498
+ content, _n_rem, _n_trunc = self._sanitize_for_display(content)
1499
+ self._last_saved_content = content
1500
+
1501
+ self.text.config(state="normal", undo=True, maxundo=-1)
1502
+ self.text.delete("1.0", "end")
1503
+ self.text.insert("1.0", content)
1504
+ self.text.edit_reset()
1505
+ self.text.edit_modified(False)
1506
+ self.modified = False
1507
+
1508
+ self._restore_full_features()
1509
+ self.hl.reenable()
1510
+ self.hl.set_lang(self.lang)
1511
+
1512
+ n_lines = content.count("\n") + 1
1513
+ self._code_line_count = n_lines
1514
+
1515
+ if n_lines >= HL_FULL_DISABLE:
1516
+ self.hl.disable_large_file()
1517
+ self._show_perf_banner("highlight desativado", n_lines)
1518
+ elif n_lines >= HL_LINE_LIMIT:
1519
+ self.hl.enable_viewport_only()
1520
+ self.hl.highlight()
1521
+ self._show_perf_banner("highlight parcial (viewport)", n_lines)
1522
+ else:
1523
+ self.hl.highlight()
1524
+
1525
+ self.autocomplete.set_lang(self.lang)
1526
+
1527
+ self.gutter._update_width()
1528
+ self.gutter.redraw()
1529
+ self.minimap._schedule_redraw()
1530
+
1531
+ self.autocomplete.update_doc_symbols(content, self.lang)
1532
+ _fname = str(
1533
+ self.path) if self.path else f"untitled.{self.lang or 'txt'}"
1534
+ self._doc_symbols = JSDocParser.parse_file(content, _fname)
1535
+ self._update_kdocs()
1536
+
1537
+ if n_lines < LINT_LINE_LIMIT:
1538
+ self._lint_mgr.schedule(path, content, self.lang)
1539
+
1540
+ if self._lsp_mgr and path:
1541
+ with contextlib.suppress(tk.TclError):
1542
+ if n_lines < LSP_LINE_LIMIT:
1543
+ self._lsp_mgr.did_open(path, self.lang, content)
1544
+
1545
+ if n_lines < AUTOCOMPLETE_LINE_LIMIT:
1546
+ self.autocomplete.set_lsp_manager(
1547
+ self._lsp_mgr, path)
1548
+ if self.lang not in (
1549
+ "text",
1550
+ "plaintext",
1551
+ "",
1552
+ ) and not self._lsp_mgr.available_for(self.lang):
1553
+ self._on_lsp_hint(self.lang)
1554
+
1555
+ self._post_load_common(path)
1556
+ if _n_rem or _n_trunc:
1557
+ self.after(200, lambda: self._show_sanitize_banner(
1558
+ _n_rem, _n_trunc))
1559
+ return True
1560
+
1561
+ except (OSError, UnicodeDecodeError, MemoryError) as exc:
1562
+ messagebox.showerror(
1563
+ _t("err.file_not_found_title"), _t(
1564
+ "err.file_open", err=str(exc))
1565
+ )
1566
+ return False
1567
+
1568
+ def _load_tier1(self, path: Path, file_size: int) -> bool:
1569
+ """Arquivo grande: lê na RAM, insere no widget em chunks via after_idle.
1570
+
1571
+ Desativa: undo stack, syntax highlight, minimap, lint, autocomplete,
1572
+ kdocs, jsdoc, inlay hints, color preview, inline blame, code folding,
1573
+ sticky scroll, LSP - para garantir UI responsiva durante a carga.
1574
+ """
1575
+ try:
1576
+ self.path = path
1577
+ self.lang = EXT_LANG.get(path.suffix.lower(), "text")
1578
+ if self.code_folding:
1579
+ self.code_folding.set_lang(self.lang)
1580
+ self._is_large_mode = True
1581
+ self._is_giant_mode = False
1582
+ self._viewport_start = 0
1583
+
1584
+ raw = path.read_bytes()
1585
+ content = self._decode_bytes(raw)
1586
+ if raw.startswith(b"\xef\xbb\xbf"):
1587
+ self.encoding = "UTF-8 BOM"
1588
+ content, self.eol = self._normalize_eol(content)
1589
+ content, _n_rem, _n_trunc = self._sanitize_for_display(content)
1590
+ self._last_saved_content = content
1591
+ self._sanitize_stats = (_n_rem, _n_trunc)
1592
+
1593
+ self._disable_heavy_features()
1594
+ self.text.config(state="normal", undo=False)
1595
+ self.text.delete("1.0", "end")
1596
+ self.text.edit_reset()
1597
+ self.text.edit_modified(False)
1598
+ self.modified = False
1599
+
1600
+ self.hl.set_lang(self.lang)
1601
+ self.autocomplete.set_lang(self.lang)
1602
+
1603
+ mb = file_size / (1024 * 1024)
1604
+ self._show_loading_overlay(
1605
+ f"\u23f3 Abrindo arquivo grande ({mb:.1f} MB)\u2026 0%"
1606
+ )
1607
+ self._is_loading = True
1608
+ CHUNK = 80_000
1609
+ self._load_chunks = [
1610
+ content[i: i + CHUNK] for i in range(0, len(content), CHUNK)
1611
+ ]
1612
+ self._load_total = len(self._load_chunks)
1613
+ self._load_mb = len(content) / (1024 * 1024)
1614
+ self._on_title(path.name, False)
1615
+ del content
1616
+ self.after_idle(self._insert_chunk, 0)
1617
+ return True
1618
+
1619
+ except (OSError, UnicodeDecodeError, MemoryError) as exc:
1620
+ messagebox.showerror(
1621
+ _t("err.file_not_found_title"), _t(
1622
+ "err.file_open", err=str(exc))
1623
+ )
1624
+ return False
1625
+
1626
+ def _insert_chunk(self, idx: int) -> None:
1627
+ """Insere fatias do texto por ~12 ms e agenda a continuação, deixando a interface respirar."""
1628
+ if not self._is_loading:
1629
+ return
1630
+ chunks = self._load_chunks
1631
+ deadline = time.perf_counter() + 0.012
1632
+ try:
1633
+ while idx < self._load_total:
1634
+ self.text.insert("end", chunks[idx])
1635
+ chunks[idx] = ""
1636
+ idx += 1
1637
+ if time.perf_counter() >= deadline:
1638
+ break
1639
+ except tk.TclError:
1640
+ return
1641
+ if idx >= self._load_total:
1642
+ self._on_tier1_load_complete()
1643
+ return
1644
+ pct = int(idx / max(1, self._load_total) * 100)
1645
+ self._update_loading_overlay(
1646
+ f"\u23f3 Abrindo arquivo grande ({self._load_mb:.1f} MB)\u2026 {pct}%"
1647
+ )
1648
+ self.after_idle(self._insert_chunk, idx)
1649
+
1650
+ def _on_tier1_load_complete(self) -> None:
1651
+ """Finaliza o carregamento tier-1: atualiza UI e notifica o bus de eventos."""
1652
+ self._is_loading = False
1653
+ self._load_chunks = []
1654
+ self._hide_loading_overlay()
1655
+ self.text.edit_reset()
1656
+ self.text.edit_modified(False)
1657
+ self.modified = False
1658
+ self.hl.disable_large_file()
1659
+ self.gutter._update_width()
1660
+ self.gutter.redraw()
1661
+ with contextlib.suppress(tk.TclError):
1662
+ self.minimap._schedule_redraw()
1663
+ if self.path:
1664
+ self._post_load_common(self.path)
1665
+ self._show_large_file_notice()
1666
+ _n_rem, _n_trunc = self._sanitize_stats
1667
+ if _n_rem or _n_trunc:
1668
+ self.after(
1669
+ 300, lambda r=_n_rem, t=_n_trunc: self._show_sanitize_banner(
1670
+ r, t)
1671
+ )
1672
+
1673
+ def _load_tier2(self, path: Path, file_size: int) -> bool:
1674
+ """Arquivo gigante: mmap + índice de linhas em background + viewport virtual."""
1675
+ self.path = path
1676
+ self.lang = EXT_LANG.get(path.suffix.lower(), "text")
1677
+ if self.code_folding:
1678
+ self.code_folding.set_lang(self.lang)
1679
+ self._is_large_mode = False
1680
+ self._is_giant_mode = True
1681
+ self._viewport_start = 0
1682
+
1683
+ try:
1684
+ with open(path, "rb") as fh:
1685
+ header = fh.read(4)
1686
+ except OSError as exc:
1687
+ messagebox.showerror(
1688
+ _t("err.file_not_found_title"), _t(
1689
+ "err.file_open", err=str(exc))
1690
+ )
1691
+ return False
1692
+
1693
+ self.encoding, self.eol = self._sniff_encoding_eol(header)
1694
+
1695
+ self._disable_heavy_features()
1696
+ self.text.config(state="normal", undo=False)
1697
+ self.text.delete("1.0", "end")
1698
+ self.hl.set_lang(self.lang)
1699
+ self.autocomplete.set_lang(self.lang)
1700
+
1701
+ mb = file_size / (1024 * 1024)
1702
+ self._show_loading_overlay(
1703
+ f"\U0001f5fa\ufe0f Indexando arquivo gigante ({mb:.0f} MB)\u2026\n"
1704
+ "Aguarde - isso ocorre apenas uma vez por sessão."
1705
+ )
1706
+ self._on_title(path.name, False)
1707
+
1708
+ enc_for_vfb = (
1709
+ self.encoding.lower().replace(" bom", "").replace("utf-8-sig", "utf-8")
1710
+ )
1711
+ self._vfb_total = None
1712
+ self._window_len = 0
1713
+ self._vfb = VirtualFileBuffer(
1714
+ path=path,
1715
+ encoding=enc_for_vfb,
1716
+ eol=self.eol,
1717
+ on_ready=self._on_vfb_ready,
1718
+ )
1719
+ self.after(40, self._poll_vfb)
1720
+ return True
1721
+
1722
+ def _on_vfb_ready(self, total_lines: int) -> None:
1723
+ """Chamado pela thread de indexação: só guarda o resultado, pois o Tk não pode ser tocado daqui."""
1724
+ self._vfb_total = total_lines
1725
+
1726
+ def _poll_vfb(self) -> None:
1727
+ """Na thread principal: espera o índice ficar pronto e então monta a primeira janela."""
1728
+ if self._vfb is None:
1729
+ return
1730
+ total, self._vfb_total = self._vfb_total, None
1731
+ if total is None:
1732
+ with contextlib.suppress(tk.TclError):
1733
+ self.after(40, self._poll_vfb)
1734
+ return
1735
+ self._giant_init_complete(total)
1736
+
1737
+ def _giant_init_complete(self, total_lines: int) -> None:
1738
+ """Executado no thread principal quando o índice VFB fica pronto."""
1739
+ self._hide_loading_overlay()
1740
+ vfb = self._vfb
1741
+ if total_lines == 0 or vfb is None:
1742
+ err = getattr(
1743
+ vfb, "error", "desconhecido") if vfb else "desconhecido"
1744
+ messagebox.showerror(
1745
+ _t("err.file_not_found_title"), f"Falha ao indexar arquivo: {err}"
1746
+ )
1747
+ self._is_giant_mode = False
1748
+ return
1749
+
1750
+ if vfb.detected_eol:
1751
+ self.eol = vfb.detected_eol # o byte-sniff do cabeçalho não enxerga o arquivo todo
1752
+ lines_to_load = min(VIEWPORT_LINES, total_lines)
1753
+ initial_lines = vfb.get_lines(0, lines_to_load)
1754
+ self._window_len = len(initial_lines)
1755
+ self.gutter.line_offset, self.gutter.line_total = 0, total_lines
1756
+ content = "\n".join(initial_lines)
1757
+ content, _n_rem, _n_trunc = self._sanitize_for_display(content)
1758
+ self._sanitize_stats = (_n_rem, _n_trunc)
1759
+
1760
+ self.text.config(state="normal")
1761
+ self.text.delete("1.0", "end")
1762
+ self.text.insert("1.0", content)
1763
+ self.text.edit_reset()
1764
+ self.text.edit_modified(False)
1765
+ self.modified = False
1766
+ self._viewport_start = 0
1767
+
1768
+ self.hl.disable_large_file()
1769
+ self.gutter._update_width()
1770
+ self.gutter.redraw()
1771
+ self._show_giant_status_label()
1772
+ self._update_giant_status()
1773
+ if self.path:
1774
+ self._post_load_common(self.path)
1775
+ self._show_large_file_notice()
1776
+ if _n_rem or _n_trunc:
1777
+ self.after(
1778
+ 300, lambda r=_n_rem, t=_n_trunc: self._show_sanitize_banner(
1779
+ r, t)
1780
+ )
1781
+
1782
+ def _schedule_viewport_shift(self, direction: int) -> None:
1783
+ """Agenda um shift de viewport com debounce de 120 ms."""
1784
+ if self._vp_shift_job:
1785
+ with contextlib.suppress(tk.TclError):
1786
+ self.after_cancel(self._vp_shift_job)
1787
+ self._vp_shift_job = self.after(
1788
+ 120, lambda: self._do_viewport_shift(direction))
1789
+
1790
+ def _display_line(self, line: str) -> str:
1791
+ """Como uma linha do arquivo aparece no widget (a sanitização de exibição, linha a linha)."""
1792
+ return self._sanitize_for_display(line)[0]
1793
+
1794
+ def _flush_window(self) -> None:
1795
+ """Passa ao buffer virtual o que foi editado na janela exibida."""
1796
+ vfb = self._vfb
1797
+ if vfb is None or not vfb.is_ready:
1798
+ return
1799
+ with contextlib.suppress(tk.TclError):
1800
+ lines = self.text.get("1.0", "end-1c").split("\n")
1801
+ vfb.flush_widget_edits(lines, self._viewport_start, self._window_len, self._display_line)
1802
+
1803
+ def _show_window(self, new_start: int, top_line: int | None = None) -> None:
1804
+ """Carrega no widget a janela que começa em ``new_start`` (base 0, linha absoluta).
1805
+
1806
+ ``top_line`` é a linha absoluta que deve ficar no topo da tela; sem ela a tela continua
1807
+ mostrando o mesmo trecho de antes. Quem chama já gravou as edições com ``_flush_window``.
1808
+ """
1809
+ vfb = self._vfb
1810
+ if vfb is None or not vfb.is_ready:
1811
+ return
1812
+ total = vfb.total_lines
1813
+ old_start = self._viewport_start
1814
+ new_start = max(0, min(new_start, max(0, total - VIEWPORT_LINES)))
1815
+ try:
1816
+ cur_rel, cur_col = map(int, self.text.index(tk.INSERT).split("."))
1817
+ if top_line is None:
1818
+ top_line = old_start + int(self.text.index("@0,0").split(".")[0]) - 1
1819
+ except (tk.TclError, ValueError):
1820
+ cur_rel, cur_col = 1, 0
1821
+ top_line = top_line if top_line is not None else old_start
1822
+ cur_abs = old_start + cur_rel - 1
1823
+
1824
+ lines = vfb.get_lines(new_start, min(new_start + VIEWPORT_LINES, total))
1825
+ content, _, _ = self._sanitize_for_display("\n".join(lines))
1826
+ self.text.config(state="normal")
1827
+ self.text.delete("1.0", "end")
1828
+ self.text.insert("1.0", content)
1829
+ self._viewport_start = new_start
1830
+ self._window_len = len(lines)
1831
+
1832
+ top_rel = max(1, min(top_line - new_start + 1, max(1, len(lines))))
1833
+ cur_rel = max(1, min(cur_abs - new_start + 1, max(1, len(lines))))
1834
+ with contextlib.suppress(tk.TclError):
1835
+ self.text.mark_set(tk.INSERT, f"{cur_rel}.{cur_col}")
1836
+ self.text.yview(f"{top_rel}.0")
1837
+
1838
+ self.gutter.line_offset, self.gutter.line_total = new_start, total
1839
+ self.gutter._update_width()
1840
+ self.gutter._schedule_redraw()
1841
+ self._update_giant_status()
1842
+ if vfb.has_edits() and not self.modified:
1843
+ self.modified = True
1844
+ name = self.path.name if self.path else _t("ui.tab_untitled")
1845
+ self._on_title(name, True)
1846
+
1847
+ def _do_viewport_shift(self, direction: int) -> None:
1848
+ """Desloca a janela virtual em ``VIEWPORT_SHIFT`` linhas, persistindo as edições antes."""
1849
+ self._vp_shift_job = None
1850
+ vfb = self._vfb
1851
+ if vfb is None or not vfb.is_ready:
1852
+ return
1853
+ self._flush_window()
1854
+ total = vfb.total_lines
1855
+ old_start = self._viewport_start
1856
+ if direction > 0:
1857
+ new_start = min(old_start + VIEWPORT_SHIFT, max(0, total - VIEWPORT_LINES))
1858
+ else:
1859
+ new_start = max(0, old_start - VIEWPORT_SHIFT)
1860
+ if new_start != old_start:
1861
+ self._show_window(new_start)
1862
+
1863
+ def _giant_local_line(self, line: int) -> int:
1864
+ """Número (base 1) da linha absoluta ``line`` dentro do widget, carregando outra janela se preciso."""
1865
+ vfb = self._vfb
1866
+ total = vfb.total_lines
1867
+ line = max(1, min(line, total))
1868
+ first, last = self._viewport_start + 1, self._viewport_start + self._window_len
1869
+ margin = int(VIEWPORT_LINES * VIEWPORT_TRIGGER)
1870
+ low = first if self._viewport_start == 0 else first + margin
1871
+ high = last if last >= total else last - margin
1872
+ if not low <= line <= high:
1873
+ self._flush_window()
1874
+ self._show_window(line - 1 - VIEWPORT_LINES // 2, top_line=max(0, line - 1 - 8))
1875
+ return line - self._viewport_start
1876
+
1877
+ def _yview_dispatch(self, *args: str) -> None:
1878
+ """Comando da barra de rolagem: no modo gigante, ``moveto`` vale para o arquivo inteiro."""
1879
+ vfb = self._vfb
1880
+ if self._is_giant_mode and vfb is not None and vfb.is_ready and args and args[0] == "moveto":
1881
+ line = int(float(args[1]) * vfb.total_lines) + 1
1882
+ local = self._giant_local_line(line)
1883
+ with contextlib.suppress(tk.TclError):
1884
+ self.text.yview(f"{local}.0")
1885
+ return
1886
+ self.text.yview(*args)
1887
+
1888
+ def _sync_scroll_y(self, first: str, last: str) -> None:
1889
+ """Sincroniza scrollbar, gutter e minimapa.
1890
+
1891
+ Guard: pode ser chamado pelo yscrollcommand do tk.Text antes de
1892
+ self.gutter ser atribuído em _build_ui (a ordem de init é:
1893
+ text.config(yscrollcommand=...) -> gutter = LineNumbers(...)).
1894
+ hasattr() evita o AttributeError nessa janela de tempo.
1895
+
1896
+ Estratégia anti-lag:
1897
+ - scrollbar e gutter são atualizados imediatamente (operações leves)
1898
+ - minimap usa seu próprio debounce (120ms) - atualiza só o retângulo
1899
+ de viewport durante scroll, evitando redraw completo
1900
+ - highlight de sintaxe é reagendado apenas quando o scroll para
1901
+ (via _hl_scroll_job com debounce de 100ms), não a cada frame
1902
+ - sticky_scroll e inline_blame também só são notificados no "scroll end"
1903
+
1904
+ Em modo giant mapeia posição do viewport para posição real no arquivo
1905
+ completo e dispara viewport shifts quando o usuário se aproxima das bordas.
1906
+ """
1907
+ if not hasattr(self, "gutter"):
1908
+ return
1909
+
1910
+ first_f = float(first)
1911
+ last_f = float(last)
1912
+
1913
+ if self._is_giant_mode and self._vfb is not None and self._vfb.is_ready:
1914
+ total = self._vfb.total_lines
1915
+ vp = min(VIEWPORT_LINES, max(1, total))
1916
+ if total > 0:
1917
+ abs_first = (self._viewport_start + first_f * vp) / total
1918
+ abs_last = (self._viewport_start + last_f * vp) / total
1919
+ self._vsb.set(str(max(0.0, abs_first)),
1920
+ str(min(1.0, abs_last)))
1921
+ else:
1922
+ self._vsb.set(first, last)
1923
+ self.gutter._schedule_redraw()
1924
+
1925
+ if last_f > (1.0 - VIEWPORT_TRIGGER) and (
1926
+ self._viewport_start + VIEWPORT_LINES < total
1927
+ ):
1928
+ self._schedule_viewport_shift(+1)
1929
+ elif first_f < VIEWPORT_TRIGGER and self._viewport_start > 0:
1930
+ self._schedule_viewport_shift(-1)
1931
+ return
1932
+
1933
+ self._vsb.set(first, last)
1934
+ self.gutter._schedule_redraw()
1935
+
1936
+ self.minimap._schedule_viewport_update()
1937
+
1938
+ if hasattr(self, "_hl_scroll_job") and self._hl_scroll_job:
1939
+ with contextlib.suppress(tk.TclError):
1940
+ self.after_cancel(self._hl_scroll_job)
1941
+
1942
+ def _on_scroll_end() -> None:
1943
+ self._hl_scroll_job = None
1944
+ with contextlib.suppress(tk.TclError):
1945
+ self.hl.schedule(debounce=80)
1946
+ with contextlib.suppress(tk.TclError):
1947
+ if self.sticky_scroll:
1948
+ self.sticky_scroll.notify_scroll()
1949
+ with contextlib.suppress(tk.TclError):
1950
+ if self.inline_blame and self._blame_enabled:
1951
+ self.inline_blame.notify_scroll()
1952
+
1953
+ self._hl_scroll_job = self.after(100, _on_scroll_end)
1954
+
1955
+ def save(self) -> bool:
1956
+ """Salva o arquivo; redireciona para save_as se sem caminho."""
1957
+ if not self.path:
1958
+ return self.save_as()
1959
+ return self._write(self.path)
1960
+
1961
+ def save_as(self) -> bool:
1962
+ """Abre diálogo para escolher caminho e escreve o arquivo."""
1963
+ p = filedialog.asksaveasfilename(
1964
+ defaultextension="",
1965
+ filetypes=[
1966
+ (_t("menu.file"), "*.*"),
1967
+ ("Python", "*.py"),
1968
+ ("JavaScript", "*.js"),
1969
+ ("TypeScript", "*.ts"),
1970
+ ("HTML", "*.html"),
1971
+ ("CSS", "*.css"),
1972
+ ("JSON", "*.json"),
1973
+ ("Markdown", "*.md"),
1974
+ ],
1975
+ initialfile=self.path.name if self.path else "untitled",
1976
+ )
1977
+ if not p:
1978
+ return False
1979
+ self.set_path(Path(p))
1980
+ return self._write(self.path)
1981
+
1982
+ def set_path(self, path: Path) -> None:
1983
+ """Passa a editar o arquivo em ``path`` (salvar como ou arquivo renomeado fora do editor).
1984
+
1985
+ Atualiza a linguagem pela extensão, o realce, o autocompletar e o vigia de alterações
1986
+ externas, para que um próximo salvamento vá ao caminho novo e não recrie o antigo.
1987
+ """
1988
+ self.path = Path(path)
1989
+ self.lang = EXT_LANG.get(self.path.suffix.lower(), "text")
1990
+ self.hl.set_lang(self.lang)
1991
+ self.autocomplete.set_lang(self.lang)
1992
+ with contextlib.suppress(Exception):
1993
+ if getattr(self, "file_watcher", None):
1994
+ self.file_watcher.watch(self.path)
1995
+ with contextlib.suppress(Exception):
1996
+ self._on_title(self.path.name, self.modified)
1997
+
1998
+ def revert(self) -> None:
1999
+ """Reverte para o último conteúdo salvo."""
2000
+ if not self.path or not self.path.exists():
2001
+ return
2002
+ if self.modified:
2003
+ name = self.path.name
2004
+ if not messagebox.askyesno(
2005
+ _t("edit.revert"), _t("edit.revert_confirm", name=name), parent=self
2006
+ ):
2007
+ return
2008
+ self.load(self.path)
2009
+
2010
+ def _write(self, path: Path) -> bool:
2011
+ """Escreve o arquivo no disco.
2012
+
2013
+ Em modo giant, usa streaming via VirtualFileBuffer (zero-copy para linhas
2014
+ não editadas). Nos outros modos usa escrita atômica convencional.
2015
+ """
2016
+ with contextlib.suppress(Exception):
2017
+ if getattr(self, "file_watcher", None):
2018
+ self.file_watcher.pause()
2019
+ try:
2020
+ trim = bool(self._cfg.get("trim_trailing_whitespace"))
2021
+ fnl = bool(self._cfg.get("insert_final_newline"))
2022
+ eol = self.eol
2023
+ enc = self._save_codec()[0]
2024
+
2025
+ if self._is_giant_mode and self._vfb is not None and self._vfb.is_ready:
2026
+ self._flush_window()
2027
+ self._vfb.save_to_path(
2028
+ dest=path,
2029
+ eol=eol,
2030
+ encoding=enc,
2031
+ trim_trailing=trim,
2032
+ insert_final_newline=fnl,
2033
+ )
2034
+ self.text.edit_modified(False)
2035
+ self.modified = False
2036
+ self._on_title(path.name, False)
2037
+ _notify_saved(path)
2038
+ return True
2039
+
2040
+ content = self.text.get("1.0", "end-1c")
2041
+
2042
+ if not self._is_large_mode and self._cfg.get("format_on_save") and path:
2043
+ with contextlib.suppress(tk.TclError):
2044
+ formatted = self._format_content(content)
2045
+ if formatted and formatted != content:
2046
+ pos = self.text.index(tk.INSERT)
2047
+ self.text.delete("1.0", "end")
2048
+ self.text.insert("1.0", formatted.rstrip("\n"))
2049
+ with contextlib.suppress(tk.TclError):
2050
+ self.text.mark_set(tk.INSERT, pos)
2051
+ content = formatted.rstrip("\n")
2052
+
2053
+ if trim:
2054
+ content = "\n".join(ln.rstrip() for ln in content.split("\n"))
2055
+
2056
+ file_content = content
2057
+ if fnl and not file_content.endswith("\n"):
2058
+ file_content += "\n"
2059
+ if eol != "\n":
2060
+ file_content = file_content.replace("\n", eol)
2061
+
2062
+ write_atomic(path, self._encode_for_save(file_content))
2063
+
2064
+ self._last_saved_content = content
2065
+ self.text.edit_modified(False)
2066
+ self.modified = False
2067
+ self._on_title(path.name, False)
2068
+
2069
+ if self._lsp_mgr and path:
2070
+ with contextlib.suppress(tk.TclError):
2071
+ self._lsp_mgr.did_save(path, self.lang, content)
2072
+
2073
+ with contextlib.suppress(tk.TclError):
2074
+ FileTimeline.save_backup(
2075
+ str(path),
2076
+ content,
2077
+ max_backups=self._cfg.get("timeline_max_backups", 20),
2078
+ max_age_days=self._cfg.get("timeline_max_age_days", 30),
2079
+ )
2080
+ _notify_saved(path)
2081
+ return True
2082
+
2083
+ except SaveDeclined:
2084
+ return False
2085
+ except (OSError, UnicodeError) as exc:
2086
+ messagebox.showerror(_t("err.title"), _t(
2087
+ "err.file_save", err=str(exc)))
2088
+ return False
2089
+ finally:
2090
+ with contextlib.suppress(Exception):
2091
+ if getattr(self, "file_watcher", None):
2092
+ self.file_watcher.resume(grace_ms=1500)
2093
+
2094
+ def _format_content(self, content: str) -> str | None:
2095
+ """Formata o conteúdo com a ferramenta apropriada."""
2096
+ if self.lang in (
2097
+ "javascript",
2098
+ "typescript",
2099
+ "json",
2100
+ "css",
2101
+ "scss",
2102
+ "html",
2103
+ "markdown",
2104
+ ):
2105
+ if self.path:
2106
+ return self._lint_mgr.format_prettier(self.path, content)
2107
+ elif self.lang == "python":
2108
+ return self._lint_mgr.format_python(content)
2109
+ return None
2110
+
2111
+ def format_document(self, override: str | None = None) -> None:
2112
+ """Formata o documento atual; ``override`` é o texto já formatado por um plugin."""
2113
+ content = self.text.get("1.0", "end-1c")
2114
+ if override is None and self.format_provider is not None:
2115
+ override = self.format_provider(self)
2116
+ formatted = override if override is not None else self._format_content(content)
2117
+ if formatted and formatted.rstrip("\n") != content.rstrip("\n"):
2118
+ pos = self.text.index(tk.INSERT)
2119
+ self.text.delete("1.0", "end")
2120
+ self.text.insert("1.0", formatted.rstrip("\n"))
2121
+ with contextlib.suppress(tk.TclError):
2122
+ self.text.mark_set(tk.INSERT, pos)
2123
+ self.hl.schedule(debounce=0)
2124
+ else:
2125
+ lang_name = LANG_LABEL.get(self.lang, self.lang)
2126
+ if formatted is None:
2127
+ messagebox.showinfo(
2128
+ _t("run.format_document"),
2129
+ _t("msg.no_formatter", lang=lang_name),
2130
+ )
2131
+
2132
+ def toggle_comment(self) -> None:
2133
+ """Ctrl+/ - comenta/descomenta linhas selecionadas."""
2134
+ comment = LANG_COMMENT.get(self.lang)
2135
+ if not comment:
2136
+ self._toggle_block_comment()
2137
+ return
2138
+ with contextlib.suppress(tk.TclError):
2139
+ if self.text.tag_ranges(tk.SEL):
2140
+ start = int(self.text.index(
2141
+ tk.SEL_FIRST).split(".", maxsplit=1)[0])
2142
+ end = int(self.text.index(
2143
+ tk.SEL_LAST).split(".", maxsplit=1)[0])
2144
+
2145
+ if self.text.index(tk.SEL_LAST).split(".", maxsplit=1)[1] == "0":
2146
+ end = max(start, end - 1)
2147
+ else:
2148
+ start = end = int(self.text.index(
2149
+ tk.INSERT).split(".", maxsplit=1)[0])
2150
+
2151
+ all_commented = all(
2152
+ self.text.get(
2153
+ f"{ln}.0", f"{ln}.end").lstrip().startswith(comment)
2154
+ for ln in range(start, end + 1)
2155
+ if self.text.get(f"{ln}.0", f"{ln}.end").strip()
2156
+ )
2157
+
2158
+ for ln in range(start, end + 1):
2159
+ line = self.text.get(f"{ln}.0", f"{ln}.end")
2160
+ stripped = line.lstrip()
2161
+ indent = len(line) - len(stripped)
2162
+
2163
+ if all_commented:
2164
+ if stripped.startswith(comment + " "):
2165
+ new = " " * indent + stripped[len(comment) + 1:]
2166
+ elif stripped.startswith(comment):
2167
+ new = " " * indent + stripped[len(comment):]
2168
+ else:
2169
+ new = line
2170
+ else:
2171
+ new = " " * indent + comment + " " + stripped
2172
+
2173
+ self.text.delete(f"{ln}.0", f"{ln}.end")
2174
+ self.text.insert(f"{ln}.0", new)
2175
+
2176
+ def _toggle_block_comment(self) -> None:
2177
+ """Alterna comentário de bloco para CSS/HTML."""
2178
+ with contextlib.suppress(tk.TclError):
2179
+ if self.text.tag_ranges(tk.SEL):
2180
+ sel = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
2181
+ if sel.startswith("/*") and sel.endswith("*/"):
2182
+ new = sel[2:-2].strip()
2183
+ else:
2184
+ new = f"/* {sel} */"
2185
+ self.text.delete(tk.SEL_FIRST, tk.SEL_LAST)
2186
+ self.text.insert(tk.INSERT, new)
2187
+
2188
+ def duplicate_line(self) -> None:
2189
+ """Duplica a linha atual (Ctrl+D)."""
2190
+ with contextlib.suppress(tk.TclError):
2191
+ pos = self.text.index(tk.INSERT)
2192
+ ln = pos.split(".", maxsplit=1)[0]
2193
+ line = self.text.get(f"{ln}.0", f"{ln}.end")
2194
+ self.text.insert(f"{ln}.end", "\n" + line)
2195
+
2196
+ def delete_line(self) -> None:
2197
+ """Deleta a linha atual."""
2198
+ with contextlib.suppress(tk.TclError):
2199
+ pos = self.text.index(tk.INSERT)
2200
+ ln = pos.split(".", maxsplit=1)[0]
2201
+
2202
+ self.text.delete(f"{ln}.0", f"{int(ln) + 1}.0")
2203
+
2204
+ def move_line(self, direction: int) -> None:
2205
+ """Move a linha para cima (-1) ou para baixo (+1)."""
2206
+ with contextlib.suppress(tk.TclError):
2207
+ pos = self.text.index(tk.INSERT)
2208
+ ln = int(pos.split(".", maxsplit=1)[0])
2209
+ col = pos.split(".", maxsplit=1)[1]
2210
+
2211
+ if direction == -1 and ln <= 1:
2212
+ return
2213
+ total = int(self.text.index("end").split(".", maxsplit=1)[0])
2214
+ if direction == 1 and ln >= total - 1:
2215
+ return
2216
+
2217
+ curr_line = self.text.get(f"{ln}.0", f"{ln}.end")
2218
+ other_ln = ln + direction
2219
+ other_line = self.text.get(f"{other_ln}.0", f"{other_ln}.end")
2220
+
2221
+ self.text.delete(f"{ln}.0", f"{ln}.end")
2222
+ self.text.insert(f"{ln}.0", other_line)
2223
+ self.text.delete(f"{other_ln}.0", f"{other_ln}.end")
2224
+ self.text.insert(f"{other_ln}.0", curr_line)
2225
+ self.text.mark_set(tk.INSERT, f"{other_ln}.{col}")
2226
+
2227
+ def select_line(self) -> None:
2228
+ """Seleciona a linha atual."""
2229
+ with contextlib.suppress(tk.TclError):
2230
+ pos = self.text.index(tk.INSERT)
2231
+ ln = pos.split(".", maxsplit=1)[0]
2232
+ self.text.tag_remove(tk.SEL, "1.0", "end")
2233
+ self.text.tag_add(tk.SEL, f"{ln}.0", f"{ln}.end+1c")
2234
+ self.text.mark_set(tk.INSERT, f"{ln}.end")
2235
+
2236
+ def delete_word_left(self) -> str:
2237
+ """Ctrl+Backspace: apaga a palavra à esquerda."""
2238
+ with contextlib.suppress(tk.TclError):
2239
+ pos = self.text.index(tk.INSERT)
2240
+ line = self.text.get(f"{pos} linestart", pos)
2241
+ m = re.search(r"(\w+|\W+)\s*$", line)
2242
+ if m:
2243
+ start = f"{pos} - {len(m.group())}c"
2244
+ self.text.delete(start, pos)
2245
+ return "break"
2246
+
2247
+ def delete_word_right(self) -> str:
2248
+ """Ctrl+Delete: apaga a palavra à direita."""
2249
+ with contextlib.suppress(tk.TclError):
2250
+ pos = self.text.index(tk.INSERT)
2251
+ rest = self.text.get(pos, f"{pos} lineend")
2252
+ m = re.match(r"\s*(\w+|\W+)", rest)
2253
+ if m:
2254
+ self.text.delete(pos, f"{pos} + {len(m.group())}c")
2255
+ return "break"
2256
+
2257
+ def sort_lines(self, reverse: bool = False) -> None:
2258
+ """Ordena as linhas selecionadas."""
2259
+ with contextlib.suppress(tk.TclError):
2260
+ if self.text.tag_ranges(tk.SEL):
2261
+ start = self.text.index(tk.SEL_FIRST).split(".", maxsplit=1)[0]
2262
+ end = self.text.index(tk.SEL_LAST).split(".", maxsplit=1)[0]
2263
+ else:
2264
+ start = end = "1"
2265
+ end = str(
2266
+ int(self.text.index("end").split(".", maxsplit=1)[0]) - 1)
2267
+ s_ln, e_ln = int(start), int(end)
2268
+ lines = [
2269
+ self.text.get(f"{ln}.0", f"{ln}.end") for ln in range(s_ln, e_ln + 1)
2270
+ ]
2271
+ lines.sort(reverse=reverse)
2272
+ for i, ln in enumerate(range(s_ln, e_ln + 1)):
2273
+ self.text.delete(f"{ln}.0", f"{ln}.end")
2274
+ self.text.insert(f"{ln}.0", lines[i])
2275
+
2276
+ def join_lines(self) -> None:
2277
+ """Une a linha atual com a próxima."""
2278
+ with contextlib.suppress(tk.TclError):
2279
+ pos = self.text.index(tk.INSERT)
2280
+ ln = int(pos.split(".", maxsplit=1)[0])
2281
+ self.text.delete(f"{ln}.end", f"{ln + 1}.0")
2282
+ self.text.insert(f"{ln}.end", " ")
2283
+
2284
+ def transform_case(self, mode: str) -> None:
2285
+ """Transforma a seleção: upper, lower, title, camel, snake, kebab, pascal, constant."""
2286
+ with contextlib.suppress(tk.TclError):
2287
+ with contextlib.suppress(ImportError):
2288
+ from src.editor.text_transforms import apply_transform
2289
+
2290
+ case_map = {
2291
+ "camel": "camel",
2292
+ "snake": "snake",
2293
+ "kebab": "kebab",
2294
+ "pascal": "pascal",
2295
+ "constant": "constant",
2296
+ }
2297
+ if mode in case_map:
2298
+ apply_transform(self.text, case_map[mode])
2299
+ return
2300
+ if self.text.tag_ranges(tk.SEL):
2301
+ sel = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
2302
+ if mode == "upper":
2303
+ new = sel.upper()
2304
+ elif mode == "lower":
2305
+ new = sel.lower()
2306
+ elif mode == "title":
2307
+ new = sel.title()
2308
+ else:
2309
+ return
2310
+ self.text.delete(tk.SEL_FIRST, tk.SEL_LAST)
2311
+ self.text.insert(tk.INSERT, new)
2312
+
2313
+ def trim_trailing_whitespace(self) -> None:
2314
+ """Remove espaços/tabs do final de cada linha.
2315
+
2316
+ Em modo giant, delega ao VFB (o trim ocorre no save_to_path). Em modo
2317
+ large, processa o conteúdo do widget em chunks para não bloquear a UI.
2318
+ """
2319
+ if self._is_giant_mode:
2320
+ self._show_context_info("Espaços finais serão removidos ao salvar")
2321
+ return
2322
+ with contextlib.suppress(tk.TclError):
2323
+ content = self.text.get("1.0", "end-1c")
2324
+ lines = content.split("\n")
2325
+ new_content = "\n".join(l_.rstrip() for l_ in lines)
2326
+ if new_content != content:
2327
+ pos = self.text.index(tk.INSERT)
2328
+ self.text.delete("1.0", "end")
2329
+ self.text.insert("1.0", new_content)
2330
+ with contextlib.suppress(tk.TclError):
2331
+ self.text.mark_set(tk.INSERT, pos)
2332
+
2333
+ def zoom(self, delta: int) -> None:
2334
+ """Aumenta (+1) ou diminui (-1) o tamanho da fonte (Ctrl+= / Ctrl+-)."""
2335
+ if delta == 0:
2336
+ self._font_size = self._cfg.get("font_size", FONT_SIZE)
2337
+ else:
2338
+ self._font_size = max(FONT_MIN, min(
2339
+ FONT_MAX, self._font_size + delta))
2340
+ self.text.config(font=(self._font_family, self._font_size))
2341
+ self.gutter.update_font(self._font_family, self._font_size)
2342
+ self.hl.reconfigure()
2343
+
2344
+ def toggle_word_wrap(self) -> None:
2345
+ """Alterna o modo de quebra de linha (ativado ↔ desativado)."""
2346
+ self.set_word_wrap(not self._word_wrap)
2347
+
2348
+ def set_word_wrap(self, enabled: bool) -> None:
2349
+ """Define explicitamente o estado da quebra de linha (idempotente)."""
2350
+ if self._word_wrap == enabled:
2351
+ return
2352
+ self._word_wrap = enabled
2353
+ self.text.config(wrap="word" if self._word_wrap else "none")
2354
+
2355
+ def toggle_minimap(self) -> None:
2356
+ """Alterna a visibilidade do minimapa (ativado ↔ desativado)."""
2357
+ self.set_minimap(not self._show_minimap)
2358
+
2359
+ def set_minimap(self, enabled: bool) -> None:
2360
+ """Define explicitamente a visibilidade do minimapa (idempotente)."""
2361
+ if self._show_minimap == enabled:
2362
+ return
2363
+ self._show_minimap = enabled
2364
+ if self._show_minimap:
2365
+ self._minimap_frame.pack(side="right", fill="y")
2366
+ else:
2367
+ self._minimap_frame.pack_forget()
2368
+
2369
+ def goto_line(self, line: int, col: int = 0) -> None:
2370
+ """Posiciona o cursor na linha e coluna especificadas, garantindo visibilidade."""
2371
+ if self._is_giant_mode and self._vfb is not None and self._vfb.is_ready:
2372
+ line = self._giant_local_line(line)
2373
+ with contextlib.suppress(tk.TclError):
2374
+ idx = f"{line}.{col}"
2375
+ self.text.mark_set(tk.INSERT, idx)
2376
+ self.text.see(idx)
2377
+ self.hl.hl_current_line()
2378
+ self._update_cursor()
2379
+
2380
+ def goto_line_dialog(self) -> None:
2381
+ """Abre diálogo para o usuário digitar um número de linha e navega até ela."""
2382
+ result = simpledialog.askstring(
2383
+ _t("go.to_line"),
2384
+ _t("go.to_line") + ":",
2385
+ parent=self,
2386
+ )
2387
+ if result:
2388
+ with contextlib.suppress(ValueError):
2389
+ if ":" in result:
2390
+ ln, col = map(int, result.split(":", 1))
2391
+ elif "," in result:
2392
+ ln, col = map(int, result.split(",", 1))
2393
+ else:
2394
+ ln, col = int(result), 0
2395
+ self.goto_line(ln, col)
2396
+
2397
+ def get_word_at_cursor(self) -> str:
2398
+ """Retorna a palavra sob o cursor."""
2399
+ with contextlib.suppress(tk.TclError, ValueError):
2400
+ pos = self.text.index(tk.INSERT)
2401
+ line = self.text.get(f"{pos} linestart", f"{pos} lineend")
2402
+ col = int(pos.split(".", maxsplit=1)[1])
2403
+ for m in re.finditer(r"\b\w+\b", line):
2404
+ if m.start() <= col <= m.end():
2405
+ return m.group()
2406
+ return ""
2407
+
2408
+ @property
2409
+ def filepath(self) -> str | None:
2410
+ """Caminho do arquivo como string, ou ``None``."""
2411
+ return str(self.path) if self.path else None
2412
+
2413
+ def get_content(self) -> str:
2414
+ """Retorna o conteúdo completo do editor como string."""
2415
+ return self.text.get("1.0", "end-1c")
2416
+
2417
+ def set_lsp_manager(self, lsp_mgr: LSPManager | None) -> None:
2418
+ """Conecta o gerenciador LSP. Chamado pelo CodisApp após a inicialização."""
2419
+ self._lsp_mgr = lsp_mgr
2420
+ if lsp_mgr and self.path:
2421
+ self.autocomplete.set_lsp_manager(lsp_mgr, self.path)
2422
+ elif lsp_mgr:
2423
+ self.autocomplete.set_lsp_manager(lsp_mgr, None)
2424
+
2425
+ @staticmethod
2426
+ def _on_lsp_hint(lang: str) -> None:
2427
+ """Registra no log uma dica de instalação quando não há servidor LSP disponível.
2428
+
2429
+ O log é capturado pelo handler de output panel do CodisApp, tornando
2430
+ a mensagem visível para o usuário sem violar a injeção de dependência
2431
+ do EditorPane. Exibido no máximo uma vez por linguagem por sessão.
2432
+ """
2433
+ from src.editor.pane import EditorPane
2434
+
2435
+ already_warned: set = getattr(EditorPane, "_lsp_warned_langs", set())
2436
+ if lang in already_warned:
2437
+ return
2438
+ already_warned.add(lang)
2439
+ EditorPane._lsp_warned_langs = already_warned
2440
+
2441
+ install_hints = {
2442
+ "python": "pip install python-lsp-server",
2443
+ "javascript": "npm i -g typescript-language-server typescript",
2444
+ "typescript": "npm i -g typescript-language-server typescript",
2445
+ "rust": "rustup component add rust-analyzer",
2446
+ "go": "go install golang.org/x/tools/gopls@latest",
2447
+ "c": "apt install clangd (ou brew install llvm)",
2448
+ "cpp": "apt install clangd (ou brew install llvm)",
2449
+ "lua": "brew install lua-language-server",
2450
+ "bash": "npm i -g bash-language-server",
2451
+ "shell": "npm i -g bash-language-server",
2452
+ "markdown": "brew install marksman (ou baixe em github.com/artempyanykh/marksman)",
2453
+ }
2454
+ hint = install_hints.get(lang, "")
2455
+ if hint:
2456
+ logger.info(
2457
+ "LSP para '%s' não encontrado. Instale com: %s "
2458
+ "(ver wiki/linting.md para guia completo)",
2459
+ lang,
2460
+ hint,
2461
+ )
2462
+ else:
2463
+ logger.info(
2464
+ "LSP para '%s' não encontrado. Consulte wiki/linting.md para guias de instalação.",
2465
+ lang,
2466
+ )
2467
+
2468
+ def _lsp_did_change(self, content: str) -> None:
2469
+ """Notificação LSP textDocument/didChange com debounce."""
2470
+ if self._lsp_mgr and self.path:
2471
+ with contextlib.suppress(tk.TclError):
2472
+ self._lsp_mgr.did_change(self.path, self.lang, content)
2473
+
2474
+ _doc_langs = {
2475
+ "javascript",
2476
+ "typescript",
2477
+ "python",
2478
+ "rust",
2479
+ "go",
2480
+ "java",
2481
+ "kotlin",
2482
+ "swift",
2483
+ "csharp",
2484
+ "cpp",
2485
+ "c",
2486
+ "ruby",
2487
+ "lua",
2488
+ "php",
2489
+ "dart",
2490
+ "elixir",
2491
+ "r",
2492
+ "julia",
2493
+ }
2494
+ if self.lang in _doc_langs and self.path:
2495
+ _fname = str(self.path)
2496
+ self._doc_symbols = JSDocParser.parse_file(content, _fname)
2497
+
2498
+ def _set_ctrl(self, pressed: bool) -> None:
2499
+ """Rastreia se a tecla Ctrl está pressionada - usada pelo balloon para pinar."""
2500
+ with contextlib.suppress(tk.TclError):
2501
+ self.tk.call("set", "_codis_ctrl_held", "1" if pressed else "0")
2502
+
2503
+ def _on_ctrl_click(self, event: tk.Event) -> None:
2504
+
2505
+ with contextlib.suppress(tk.TclError):
2506
+ self.lsp_goto_definition()
2507
+
2508
+ def lsp_goto_definition(self) -> None:
2509
+ """Vai para a definição via LSP (F12 / Ctrl+Clique)."""
2510
+ from src.theme.utils import lsp_loc_pair
2511
+
2512
+ if not self._lsp_mgr or not self.path:
2513
+ self._local_goto_definition()
2514
+ return
2515
+ try:
2516
+ idx = self.text.index(tk.INSERT)
2517
+ line = int(idx.split(".", maxsplit=1)[0]) - 1
2518
+ col = int(idx.split(".", maxsplit=1)[1])
2519
+
2520
+ client = self._lsp_mgr.client_for(self.lang)
2521
+ if client is None:
2522
+ self._local_goto_definition()
2523
+ return
2524
+
2525
+ def _do_request() -> None:
2526
+ if client.starting and not client.wait_initialized(timeout=5.0):
2527
+ self.after(0, self._local_goto_definition)
2528
+ return
2529
+ if not client.running:
2530
+ self.after(0, self._local_goto_definition)
2531
+ return
2532
+
2533
+ def _cb(locations: list) -> None:
2534
+ if not locations:
2535
+ self._local_goto_definition()
2536
+ return
2537
+ loc = locations[0] if isinstance(
2538
+ locations, list) else locations
2539
+ try:
2540
+ uri, tline = lsp_loc_pair(loc)
2541
+ tpath = _lsp_uri_to_path(uri)
2542
+ self.after(
2543
+ 0, lambda: self._goto_location(tpath, tline))
2544
+ except (ValueError, AttributeError, KeyError):
2545
+ self.after(0, self._local_goto_definition)
2546
+
2547
+ client.goto_definition(self.path, line, col, _cb)
2548
+
2549
+ import threading as _thr
2550
+
2551
+ _thr.Thread(target=_do_request, daemon=True,
2552
+ name="lsp-goto-def").start()
2553
+ except (tk.TclError, ValueError):
2554
+ self._local_goto_definition()
2555
+
2556
+ def lsp_find_references(self) -> None:
2557
+ """Localiza todas as referências via LSP (Shift+F12)."""
2558
+ if not self._lsp_mgr or not self.path:
2559
+ return
2560
+ with contextlib.suppress(tk.TclError, ValueError):
2561
+ idx = self.text.index(tk.INSERT)
2562
+ line = int(idx.split(".", maxsplit=1)[0]) - 1
2563
+ col = int(idx.split(".", maxsplit=1)[1])
2564
+
2565
+ client = self._lsp_mgr.client_for(self.lang)
2566
+ if client is None:
2567
+ return
2568
+
2569
+ def _do_request() -> None:
2570
+ if client.starting and not client.wait_initialized(timeout=5.0):
2571
+ return
2572
+ if not client.running:
2573
+ return
2574
+
2575
+ def _cb(refs: list) -> None:
2576
+ from src.theme.utils import lsp_loc_pair
2577
+
2578
+ if not refs:
2579
+ self.after(0, lambda: self._show_refs_popup(""))
2580
+ return
2581
+ linhas: list[str] = []
2582
+ for r in refs if isinstance(refs, list) else []:
2583
+ with contextlib.suppress(ValueError, AttributeError, KeyError):
2584
+ uri, tline = lsp_loc_pair(r)
2585
+ tpath = _lsp_uri_to_path(uri)
2586
+ linhas.append(f"{tpath}:{tline}")
2587
+ msg = "\n".join(linhas[:50])
2588
+ if len(refs) > 50:
2589
+ msg += f"\n...e mais {len(refs) - 50}"
2590
+ self.after(0, lambda: self._show_refs_popup(msg))
2591
+
2592
+ client.find_references(self.path, line, col, _cb)
2593
+
2594
+ import threading as _thr
2595
+
2596
+ _thr.Thread(target=_do_request, daemon=True,
2597
+ name="lsp-find-refs").start()
2598
+
2599
+ def lsp_rename_symbol(self) -> None:
2600
+ """Renomeia o símbolo via LSP (F6)."""
2601
+ if not self._lsp_mgr or not self.path:
2602
+ return
2603
+ new_name = simpledialog.askstring(
2604
+ _t("lsp.rename_symbol"), _t("lsp.new_name"), parent=self
2605
+ )
2606
+ if not new_name:
2607
+ return
2608
+ with contextlib.suppress(tk.TclError, ValueError):
2609
+ idx = self.text.index(tk.INSERT)
2610
+ line = int(idx.split(".", maxsplit=1)[0]) - 1
2611
+ col = int(idx.split(".", maxsplit=1)[1])
2612
+
2613
+ def _rename_cb(workspace_edit):
2614
+ # O callback chega na thread do LSP; o Tk só pode ser tocado pela thread da interface.
2615
+ with contextlib.suppress(tk.TclError, RuntimeError):
2616
+ self.after(0, lambda: self.apply_workspace_edit(workspace_edit))
2617
+
2618
+ self._lsp_mgr.rename(
2619
+ self.path, self.lang, line, col, new_name, callback=_rename_cb
2620
+ )
2621
+
2622
+ def apply_lsp_edits(self, edits: list) -> None:
2623
+ """Aplica uma lista de TextEdit (objetos ou dicts) ao conteúdo do editor.
2624
+
2625
+ Tudo vira um único passo de desfazer, as edições são aplicadas de trás para frente
2626
+ e as colunas (UTF-16 no LSP) são convertidas para a contagem de caracteres do Tk.
2627
+ """
2628
+ ordered = sort_for_apply(edits)
2629
+ if not ordered:
2630
+ return
2631
+ with contextlib.suppress(tk.TclError, AttributeError, TypeError):
2632
+ self.text.config(state="normal")
2633
+ utf16_index = self._tk_indexes_in_utf16()
2634
+ auto = self.text.cget("autoseparators")
2635
+ self.text.config(autoseparators=False) # senão o Tk quebra o lote em vários passos
2636
+ self.text.edit_separator()
2637
+ last_line = int(self.text.index("end-1c").split(".")[0])
2638
+ for start_line, start_col, end_line, end_col, new_text in ordered:
2639
+ s_line = min(start_line + 1, last_line)
2640
+ e_line = min(end_line + 1, last_line)
2641
+ s_col = self._lsp_col(s_line, start_col, utf16_index)
2642
+ e_col = self._lsp_col(e_line, end_col, utf16_index)
2643
+ self.text.delete(f"{s_line}.{s_col}", f"{e_line}.{e_col}")
2644
+ self.text.insert(f"{s_line}.{s_col}", new_text)
2645
+ self.text.edit_separator()
2646
+ self.text.config(autoseparators=auto)
2647
+
2648
+ def _tk_indexes_in_utf16(self) -> bool:
2649
+ """O Tk deste sistema conta um emoji como 2 posições de índice (como o LSP) ou como 1?
2650
+
2651
+ Depende do build do Tcl/Tk (``TCL_UTF_MAX``), então é medido em vez de presumido.
2652
+ """
2653
+ probe = tk.Text(self)
2654
+ try:
2655
+ probe.insert("1.0", "\U0001f600")
2656
+ return probe.index("1.end") != "1.1"
2657
+ finally:
2658
+ probe.destroy()
2659
+
2660
+ def _lsp_col(self, line: int, units: int, utf16_index: bool) -> int:
2661
+ """Coluna do LSP (unidades UTF-16) convertida para o índice de coluna do Tk."""
2662
+ if utf16_index:
2663
+ return max(0, units)
2664
+ return utf16_to_index(self.text.get(f"{line}.0", f"{line}.end"), units)
2665
+
2666
+ def apply_workspace_edit(self, workspace_edit: Any) -> int:
2667
+ """Aplica um ``WorkspaceEdit`` (dict ou objeto): este arquivo aqui, os outros pelo app.
2668
+
2669
+ Devolve quantos arquivos foram alterados. Sem o callback do app (editor isolado),
2670
+ só o arquivo deste editor é alterado.
2671
+ """
2672
+ changed = 0
2673
+ for uri, edits in normalize_workspace_edit(workspace_edit).items():
2674
+ target = _lsp_uri_to_path(uri)
2675
+ if self.path and _same_file(target, self.path):
2676
+ self.apply_lsp_edits(edits)
2677
+ changed += 1
2678
+ continue
2679
+ cb = getattr(self, "_workspace_edit_cb", None)
2680
+ if cb is not None and cb(target, edits):
2681
+ changed += 1
2682
+ return changed
2683
+
2684
+ def set_workspace_edit_callback(self, cb) -> None:
2685
+ """Define quem aplica edições em outros arquivos: ``cb(path, edits) -> bool``."""
2686
+ self._workspace_edit_cb = cb
2687
+
2688
+ def _lsp_cursor_pos(self) -> tuple[int, int]:
2689
+ """Retorna (line_0based, col) da posição atual do cursor."""
2690
+ idx = self.text.index(tk.INSERT)
2691
+ line = int(idx.split(".", maxsplit=1)[0]) - 1
2692
+ col = int(idx.split(".", maxsplit=1)[1])
2693
+ return line, col
2694
+
2695
+ def _lsp_run_in_bg(self, fn, name: str = "lsp-bg") -> None:
2696
+ """Executa fn em thread de background daemon."""
2697
+ import threading as _thr
2698
+
2699
+ _thr.Thread(target=fn, daemon=True, name=name).start()
2700
+
2701
+ def _lsp_wait_client(self, client) -> bool:
2702
+ """Aguarda o cliente inicializar (uso em threads de background). Retorna False se falhar."""
2703
+ if client.starting:
2704
+ return client.wait_initialized(timeout=6.0)
2705
+ return client.running
2706
+
2707
+ def _lsp_goto_single(
2708
+ self,
2709
+ client_method_name: str,
2710
+ bg_tag: str,
2711
+ ) -> None:
2712
+ """Implementação comum para goto_declaration / goto_type_definition.
2713
+
2714
+ Ambos têm comportamento idêntico (navega para o primeiro resultado);
2715
+ só diferem no método LSP chamado e na tag de background thread.
2716
+ """
2717
+ from src.theme.utils import lsp_loc_pair
2718
+
2719
+ if not self._lsp_mgr or not self.path:
2720
+ return
2721
+ with contextlib.suppress(tk.TclError, ValueError):
2722
+ line, col = self._lsp_cursor_pos()
2723
+ client = self._lsp_mgr.client_for(self.lang)
2724
+ if not client:
2725
+ return
2726
+ method = getattr(client, client_method_name)
2727
+
2728
+ def _cb(locs: list) -> None:
2729
+ if not locs:
2730
+ return
2731
+ uri, tline = lsp_loc_pair(locs[0])
2732
+ tpath = _lsp_uri_to_path(uri)
2733
+ self.after(0, lambda: self._goto_location(tpath, tline))
2734
+
2735
+ def _run() -> None:
2736
+ if self._lsp_wait_client(client):
2737
+ method(self.path, line, col, _cb)
2738
+
2739
+ self._lsp_run_in_bg(_run, bg_tag)
2740
+
2741
+ def lsp_goto_declaration(self) -> None:
2742
+ """Vai para a declaração do símbolo via LSP."""
2743
+ self._lsp_goto_single("goto_declaration", "lsp-goto-decl")
2744
+
2745
+ def lsp_goto_type_definition(self) -> None:
2746
+ """Vai para a definição de tipo do símbolo via LSP."""
2747
+ self._lsp_goto_single("goto_type_definition", "lsp-goto-typedef")
2748
+
2749
+ def lsp_goto_implementation(self) -> None:
2750
+ """Vai para a implementação do símbolo via LSP."""
2751
+ from src.theme.utils import lsp_loc_pair
2752
+
2753
+ if not self._lsp_mgr or not self.path:
2754
+ return
2755
+ with contextlib.suppress(tk.TclError, ValueError):
2756
+ line, col = self._lsp_cursor_pos()
2757
+ client = self._lsp_mgr.client_for(self.lang)
2758
+ if not client:
2759
+ return
2760
+
2761
+ def _cb(locs: list) -> None:
2762
+ if not locs:
2763
+ return
2764
+ if len(locs) == 1:
2765
+ uri, tline = lsp_loc_pair(locs[0])
2766
+ tpath = _lsp_uri_to_path(uri)
2767
+ self.after(0, lambda: self._goto_location(tpath, tline))
2768
+ else:
2769
+ lines = [
2770
+ f"{_lsp_uri_to_path(lsp_loc_pair(r)[0])}:{lsp_loc_pair(r)[1]}"
2771
+ for r in locs[:50]
2772
+ ]
2773
+ msg = "\n".join(lines)
2774
+ self.after(0, lambda: self._show_refs_popup(msg))
2775
+
2776
+ def _run() -> None:
2777
+ if self._lsp_wait_client(client):
2778
+ client.goto_implementation(self.path, line, col, _cb)
2779
+
2780
+ self._lsp_run_in_bg(_run, "lsp-goto-impl")
2781
+
2782
+ def lsp_code_action(self) -> None:
2783
+ """Mostra code actions (quick fix, refactor...) via LSP para a posição atual."""
2784
+ if not self._lsp_mgr or not self.path:
2785
+ return
2786
+ with contextlib.suppress(tk.TclError, ValueError):
2787
+ line, col = self._lsp_cursor_pos()
2788
+ client = self._lsp_mgr.client_for(self.lang)
2789
+ if not client:
2790
+ return
2791
+
2792
+ from src.lsp.protocol import Position as LSPPos
2793
+ from src.lsp.protocol import Range as LSPRange
2794
+
2795
+ rng = LSPRange(LSPPos(line, col), LSPPos(line, col))
2796
+
2797
+ def _run() -> None:
2798
+ if not self._lsp_wait_client(client):
2799
+ return
2800
+
2801
+ def _cb(actions: list) -> None:
2802
+ if not actions:
2803
+ self.after(
2804
+ 0,
2805
+ lambda: messagebox.showinfo(
2806
+ "Code Actions", "Nenhuma ação disponível aqui."
2807
+ ),
2808
+ )
2809
+ return
2810
+ self.after(
2811
+ 0, lambda a=actions: self._show_code_actions_popup(a))
2812
+
2813
+ client.code_action(self.path, rng, [], _cb)
2814
+
2815
+ self._lsp_run_in_bg(_run, "lsp-code-action")
2816
+
2817
+ def _show_code_actions_popup(self, actions: list) -> None:
2818
+ """Exibe menu popup com as code actions disponíveis."""
2819
+ menu = tk.Menu(self, tearoff=False)
2820
+ t = self._tmgr.theme
2821
+ menu.config(
2822
+ bg=t.floating_bg,
2823
+ fg=t.fg,
2824
+ activebackground=t.sel_bg,
2825
+ activeforeground=t.sel_fg,
2826
+ )
2827
+ for action in actions[:20]:
2828
+ title = (
2829
+ action.title if hasattr(
2830
+ action, "title") else action.get("title", "")
2831
+ )
2832
+ kind_lbl = (
2833
+ action.kind_label
2834
+ if hasattr(action, "kind_label")
2835
+ else action.get("kind", "")
2836
+ )
2837
+ label = f"{kind_lbl}: {title}" if kind_lbl else title
2838
+
2839
+ def _apply(a=action) -> None:
2840
+ self._apply_code_action(a)
2841
+
2842
+ menu.add_command(label=label, command=_apply)
2843
+ with contextlib.suppress(tk.TclError):
2844
+ x = self.winfo_rootx() + self.text.winfo_x()
2845
+ y = self.winfo_rooty() + self.text.winfo_y()
2846
+ menu.tk_popup(x + 20, y + 20)
2847
+
2848
+ def _apply_code_action(self, action) -> None:
2849
+ """Aplica o WorkspaceEdit de uma code action, ou executa seu command."""
2850
+ try:
2851
+ edit = action.edit if hasattr(action, "edit") else None
2852
+ if edit:
2853
+ self.apply_workspace_edit(edit)
2854
+ cmd = action.command if hasattr(action, "command") else None
2855
+ if cmd and self._lsp_mgr:
2856
+ command_id = (
2857
+ cmd.get("command", "")
2858
+ if isinstance(cmd, dict)
2859
+ else getattr(cmd, "command", "")
2860
+ )
2861
+ arguments = (
2862
+ cmd.get("arguments")
2863
+ if isinstance(cmd, dict)
2864
+ else getattr(cmd, "arguments", None)
2865
+ )
2866
+ self._lsp_mgr.execute_command(self.lang, command_id, arguments)
2867
+ except Exception:
2868
+ logger.debug("_apply_code_action: erro ignorado", exc_info=True)
2869
+
2870
+ def lsp_incoming_calls(self) -> None:
2871
+ """Solicita ao servidor LSP as chamadas de entrada do símbolo sob o cursor."""
2872
+ self._lsp_call_hierarchy(incoming=True)
2873
+
2874
+ def lsp_outgoing_calls(self) -> None:
2875
+ """Solicita ao servidor LSP as chamadas de saída do símbolo sob o cursor."""
2876
+ self._lsp_call_hierarchy(incoming=False)
2877
+
2878
+ def _lsp_call_hierarchy(self, incoming: bool) -> None:
2879
+ """Prepara a hierarquia de chamadas no cursor e mostra as de entrada ou de saída."""
2880
+ if not self._lsp_mgr or not self.path:
2881
+ return
2882
+ title = "Incoming Calls" if incoming else "Outgoing Calls"
2883
+ with contextlib.suppress(tk.TclError, ValueError):
2884
+ line, col = self._lsp_cursor_pos()
2885
+ client = self._lsp_mgr.client_for(self.lang)
2886
+ if not client:
2887
+ return
2888
+ request = client.incoming_calls if incoming else client.outgoing_calls
2889
+
2890
+ def _run() -> None:
2891
+ if not self._lsp_wait_client(client):
2892
+ return
2893
+
2894
+ def _on_items(items: list) -> None:
2895
+ if not items:
2896
+ self.after(
2897
+ 0, lambda: messagebox.showinfo("Call Hierarchy", "Nenhum resultado.")
2898
+ )
2899
+ return
2900
+
2901
+ def _on_calls(calls: list) -> None:
2902
+ if not calls:
2903
+ self.after(
2904
+ 0,
2905
+ lambda: messagebox.showinfo(title, "Nenhuma chamada encontrada."),
2906
+ )
2907
+ return
2908
+ lines: list[str] = []
2909
+ for c in calls[:50]:
2910
+ ci = c.item if hasattr(c, "item") else {}
2911
+ name = ci.name if hasattr(ci, "name") else ci.get("name", "?")
2912
+ uri = ci.uri if hasattr(ci, "uri") else ci.get("uri", "")
2913
+ lines.append(f"{name} ({_lsp_uri_to_path(uri)})")
2914
+ summary = "\n".join(lines)
2915
+ self.after(0, lambda: self._show_refs_popup(summary))
2916
+
2917
+ request(items[0], _on_calls)
2918
+
2919
+ client.prepare_call_hierarchy(self.path, line, col, _on_items)
2920
+
2921
+ self._lsp_run_in_bg(_run, "lsp-incoming-calls" if incoming else "lsp-outgoing-calls")
2922
+
2923
+ def _goto_location(self, target_path: Path, target_line: int) -> None:
2924
+ """Despacha para o callback externo se definido, caso contrário não faz nada."""
2925
+ cb = getattr(self, "_goto_location_cb", None)
2926
+ if cb is not None:
2927
+ cb(target_path, target_line)
2928
+
2929
+ @staticmethod
2930
+ def _show_refs_popup(text: str) -> None:
2931
+ """Exibe os resultados de "localizar referências" em um popup simples."""
2932
+ messagebox.showinfo(_t("lsp.references"),
2933
+ text or _t("lsp.no_references"))
2934
+
2935
+ def set_goto_callback(self, cb) -> None:
2936
+ """Define o callback externo para navegar a arquivo:linha."""
2937
+ self._goto_location_cb = cb