codis 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/editor/pane.py ADDED
@@ -0,0 +1,2082 @@
1
+ """Painel de edição principal do Codis - ``EditorPane``.
2
+
3
+ Widget central do IDE: combina edição de texto com highlight de sintaxe,
4
+ números de linha, minimap, multi-cursor, vim mode, sticky scroll e toda
5
+ a integração LSP via ``_PaneLSPMixin``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import logging
12
+ import re
13
+ import tkinter as tk
14
+ import tkinter.font as tkfont
15
+ from collections.abc import Callable
16
+ from pathlib import Path
17
+ from tkinter import messagebox, ttk
18
+
19
+ from src.config import ConfigManager
20
+ from src.constants import (
21
+ _SANITIZE_TABLE,
22
+ AUTO_CLOSE,
23
+ FONT_MONO,
24
+ FONT_SIZE,
25
+ FONT_UI,
26
+ LINT_JS,
27
+ MAX_LINE_RENDER_CHARS,
28
+ MINIMAP_WIDTH,
29
+ TAB_SIZE,
30
+ )
31
+ from src.editor._pane_lsp import _PaneLSPMixin
32
+ from src.editor._pane_utils import SaveDeclined
33
+ from src.editor.autocomplete import AutocompletePopup
34
+ from src.editor.kdocs import (
35
+ JSDocParser,
36
+ KDocsBalloon,
37
+ KDocsNotes,
38
+ KDocsParser,
39
+ )
40
+ from src.editor.line_numbers import LineNumbers
41
+ from src.editor.minimap import MiniMap
42
+ from src.editor.snippets import SnippetEngine
43
+ from src.i18n import _t
44
+ from src.lint.manager import Diag, LintManager
45
+ from src.syntax.highlighter import _OM_CACHE, SyntaxHL
46
+ from src.theme.base import Theme
47
+ from src.theme.manager import ThemeManager
48
+
49
+ try:
50
+ _VFB_AVAILABLE = True
51
+ except ImportError:
52
+ _VFB_AVAILABLE = False
53
+
54
+ try:
55
+ from src.editor.sticky_scroll import StickyScroll
56
+
57
+ _STICKY_AVAILABLE = True
58
+ except ImportError:
59
+ _STICKY_AVAILABLE = False
60
+
61
+ try:
62
+ from src.editor.code_folding import CodeFolding
63
+
64
+ _FOLDING_AVAILABLE = True
65
+ except ImportError:
66
+ _FOLDING_AVAILABLE = False
67
+
68
+ try:
69
+ from src.editor.complexity_lens import ComplexityLens
70
+
71
+ _COMPLEXITY_LENS_OK = True
72
+ except ImportError:
73
+ _COMPLEXITY_LENS_OK = False
74
+
75
+ try:
76
+ from src.editor.focus_block import FocusBlock
77
+
78
+ _FOCUS_BLOCK_OK = True
79
+ except ImportError:
80
+ _FOCUS_BLOCK_OK = False
81
+
82
+ try:
83
+ from src.editor.sticky_note_gutter import StickyNoteGutter
84
+
85
+ _STICKY_NOTES_OK = True
86
+ except ImportError:
87
+ _STICKY_NOTES_OK = False
88
+
89
+ try:
90
+ from src.editor.inline_blame import InlineBlame
91
+
92
+ _BLAME_AVAILABLE = True
93
+ except ImportError:
94
+ _BLAME_AVAILABLE = False
95
+
96
+ try:
97
+ from src.editor.color_preview import ColorPreview
98
+
99
+ _COLOR_PREVIEW_AVAILABLE = True
100
+ except ImportError:
101
+ _COLOR_PREVIEW_AVAILABLE = False
102
+
103
+ try:
104
+ from src.editor.inlay_hints import InlayHints
105
+
106
+ _INLAY_AVAILABLE = True
107
+ except ImportError:
108
+ _INLAY_AVAILABLE = False
109
+
110
+ try:
111
+ from src.editor.smart_selection import SmartSelection
112
+
113
+ _SMART_SEL_AVAILABLE = True
114
+ except ImportError:
115
+ _SMART_SEL_AVAILABLE = False
116
+
117
+ logger = logging.getLogger("Codis")
118
+
119
+ try:
120
+ from src.editor.heatmap import EditHeatmap
121
+
122
+ _HEATMAP_OK = True
123
+ except ImportError:
124
+ _HEATMAP_OK = False
125
+
126
+ try:
127
+ from src.editor.rhythm import CodeRhythm
128
+
129
+ _RHYTHM_OK = True
130
+ except ImportError:
131
+ _RHYTHM_OK = False
132
+
133
+ try:
134
+ from src.editor.ligatures import LigatureEngine
135
+
136
+ _LIGATURE_OK = True
137
+ except ImportError:
138
+ _LIGATURE_OK = False
139
+
140
+ try:
141
+ from src.editor.file_watcher import FileWatcher
142
+
143
+ _FILEWATCHER_OK = True
144
+ except ImportError:
145
+ _FILEWATCHER_OK = False
146
+
147
+ try:
148
+ from src.lsp.client import LSPManager
149
+
150
+ _LSP_AVAILABLE = True
151
+ except ImportError:
152
+ _LSP_AVAILABLE = False
153
+
154
+
155
+
156
+ class EditorPane(_PaneLSPMixin, tk.Frame):
157
+ """
158
+ Painel de edição completo com todas as funcionalidades:
159
+
160
+ Editor:
161
+ - Realce de sintaxe multi-linguagem
162
+ - Autocompletar inteligente (snippets + palavras-chave + símbolos)
163
+ - Auto-indentação e fechamento automático de pares
164
+ - Correspondência de colchetes
165
+ - Realce da linha atual
166
+ - Números de linha (gutter) com breakpoints
167
+ - Minimapa lateral
168
+ - Breadcrumb (exposto via callback)
169
+ - Alternar quebra de linha
170
+ - Múltiplos cursores (simulado via seleções)
171
+ - Rolagem sincronizada (gutter + minimapa)
172
+
173
+ Análise:
174
+ - Lint integrado (ESLint, pyflakes, flake8, mypy)
175
+ - Anotações KDocs
176
+ - Documentação JSDoc ao passar o mouse
177
+ - Localizar e substituir embutido
178
+
179
+ Edição avançada:
180
+ - Duplicar linha / mover linha
181
+ - Comentar/descomentar (linha e bloco)
182
+ - Ordenar linhas
183
+ - Transformar maiúsculas/minúsculas
184
+ - Juntar linhas
185
+ - Remover espaços em branco no final
186
+ - Aumentar/Diminuir indentação do bloco
187
+ - Excluir linha
188
+ - Ir para linha
189
+ - Formatar documento (prettier/black/etc.)
190
+
191
+ Persistência:
192
+ - Detecção e conversão de codificação
193
+ - Detecção de final de linha (LF/CRLF/CR)
194
+ - Indicador de modificação
195
+ - Desfazer/Refazer ilimitado
196
+ """
197
+
198
+ def __init__(
199
+ self,
200
+ parent: tk.Widget,
201
+ tmgr: ThemeManager,
202
+ cfg: ConfigManager,
203
+ lint_mgr: LintManager,
204
+ snippets: SnippetEngine,
205
+ on_change: Callable[[], None],
206
+ on_cursor: Callable[[int, int], None],
207
+ on_title: Callable[[str, bool], None],
208
+ on_copy: Callable[[str, str], None] | None = None,
209
+ idx: int = 0,
210
+ ) -> None:
211
+ """Cria o painel de edição principal do Codis.
212
+
213
+ Args:
214
+ parent: Widget pai Tkinter.
215
+ cfg: Instância de ConfigManager.
216
+ i18n: Instância do sistema de internacionalização.
217
+ """
218
+ t = tmgr.theme
219
+ super().__init__(parent, bg=t.editor_bg)
220
+ self._tmgr = tmgr
221
+ self._cfg = cfg
222
+ self._lint_mgr = lint_mgr
223
+ self._snippets = snippets
224
+ self._on_change = on_change
225
+ self._on_cursor = on_cursor
226
+ self._on_title = on_title
227
+ self._on_copy_cb: Callable[[str, str], None] | None = on_copy
228
+ self.idx = idx
229
+
230
+ self.path: Path | None = None
231
+ self.lang: str = "text"
232
+ self.encoding: str = "UTF-8"
233
+ # Codec e BOM do arquivo como foi lido, para regravá-lo igual; None = arquivo novo (vale a config).
234
+ self._file_codec: str | None = None
235
+ self._file_bom: bytes = b""
236
+ self.eol: str = "\n"
237
+ self.modified: bool = False
238
+ self._font_size: int = cfg.get("font_size", FONT_SIZE)
239
+ self._font_family: str = cfg.get("font_family", FONT_MONO)
240
+ self._diags: list[Diag] = []
241
+ self._kdocs: list[KDocsNotes] = []
242
+ self._last_saved_content: str = ""
243
+ self._autocomplete_enabled: bool = cfg.get("autocomplete", True)
244
+ self._word_wrap: bool = cfg.get("word_wrap", False)
245
+ self._show_minimap: bool = cfg.get("minimap", True)
246
+ self._scroll_speed: int = max(1, min(15, cfg.get("scroll_speed", 3)))
247
+ self._ligature_mode: str = "off"
248
+ JSDocParser()
249
+
250
+ self._doc_symbols: dict = {}
251
+
252
+ self._lsp_mgr: LSPManager | None = None
253
+ self._hover_job: str | None = None
254
+ self._hide_job: str | None = None
255
+ self._hl_scroll_job: str | None = None
256
+ self._kdocs_job: str | None = None
257
+ self._symbols_job: str | None = None
258
+ self._lsp_change_job: str | None = None
259
+ self._last_hover_word: str = ""
260
+ self._last_hover_line: int = -1
261
+ self._diag_tip_win: tk.Toplevel | None = None
262
+ self._diag_tip_job: str | None = None
263
+
264
+ self._is_large_mode: bool = False
265
+
266
+ self._is_giant_mode: bool = False
267
+ self._vfb: object | None = None
268
+ self._viewport_start: int = 0
269
+ self._window_len: int = 0 # linhas que a janela do modo gigante tinha ao ser carregada
270
+ self._vp_shift_job: str | None = None
271
+ self._is_loading: bool = False
272
+ self._load_chunks: list[str] = []
273
+ self._load_total: int = 0
274
+ self._load_mb: float = 0.0
275
+ self._vfb_total: int | None = None
276
+ self._sanitize_stats: tuple[int, int] = (0, 0)
277
+ self._loading_overlay: tk.Frame | None = None
278
+ self._loading_label: tk.Label | None = None
279
+ self._giant_status: tk.Label | None = None
280
+
281
+ self._code_line_count: int = 0
282
+ self._perf_banner: tk.Label | None = None
283
+
284
+ self.sticky_scroll: StickyScroll | None = None
285
+ self.code_folding: CodeFolding | None = None
286
+ self.inline_blame: InlineBlame | None = None
287
+ self.color_preview: ColorPreview | None = None
288
+ self.inlay_hints: InlayHints | None = None
289
+ self.smart_selection: SmartSelection | None = None
290
+ self.ligature_engine: LigatureEngine | None = None
291
+ self.file_watcher: FileWatcher | None = None
292
+ self.complexity_lens: ComplexityLens | None = None
293
+ self.focus_block: FocusBlock | None = None
294
+ self.sticky_notes: StickyNoteGutter | None = None
295
+
296
+ self._sticky_enabled: bool = cfg.get("sticky_scroll", True)
297
+ self._folding_enabled: bool = cfg.get("code_folding", True)
298
+ self._blame_enabled: bool = cfg.get("inline_blame", False)
299
+ self._color_preview_enabled: bool = cfg.get("color_preview", True)
300
+ self._inlay_hints_enabled: bool = cfg.get("inlay_hints", False)
301
+ self._blame_mode: str = cfg.get("inline_blame_mode", "cursor")
302
+
303
+ self._build_ui()
304
+ self._bind_events()
305
+ self._apply_config()
306
+
307
+ def _build_ui(self) -> None:
308
+ """Constrói todos os widgets do editor: canvas, scrollbars e sobreposições."""
309
+ t = self._tmgr.theme
310
+
311
+ self._main = tk.Frame(self, bg=t.editor_bg)
312
+ self._main.pack(fill="both", expand=True)
313
+
314
+ self._gutter_frame = tk.Frame(self._main, bg=t.gutter_bg)
315
+ self._gutter_frame.pack(side="left", fill="y")
316
+
317
+ self._editor_frame = tk.Frame(self._main, bg=t.editor_bg)
318
+ self._editor_frame.pack(side="left", fill="both", expand=True)
319
+
320
+ self.text = tk.Text(
321
+ self._editor_frame,
322
+ bg=t.editor_bg,
323
+ fg=t.fg,
324
+ insertbackground=t.cursor,
325
+ selectbackground=t.sel_bg,
326
+ selectforeground=t.sel_fg,
327
+ inactiveselectbackground=t.sel_bg,
328
+ relief="flat",
329
+ bd=0,
330
+ font=(self._font_family, self._font_size),
331
+ undo=True,
332
+ maxundo=-1,
333
+ tabs=(self._calc_tab_pixels(),),
334
+ wrap="word" if self._word_wrap else "none",
335
+ highlightthickness=0,
336
+ padx=8,
337
+ pady=0,
338
+ spacing1=4,
339
+ spacing3=4,
340
+ )
341
+ from src.ui.ui_scale import exclude_from_scale
342
+
343
+ exclude_from_scale(self.text)
344
+ self.text.pack(side="left", fill="both", expand=True)
345
+
346
+ self._vsb = ttk.Scrollbar(
347
+ self._editor_frame,
348
+ orient="vertical",
349
+ command=self._yview_dispatch,
350
+ style="Thin.Vertical.TScrollbar",
351
+ )
352
+ self._vsb.pack(side="right", fill="y")
353
+ self.text.config(yscrollcommand=self._sync_scroll_y)
354
+
355
+ self._hsb = ttk.Scrollbar(
356
+ self._main,
357
+ orient="horizontal",
358
+ command=self.text.xview,
359
+ style="Thin.Horizontal.TScrollbar",
360
+ )
361
+ self.text.config(xscrollcommand=self._hsb_set)
362
+
363
+ self.gutter = LineNumbers(
364
+ self._gutter_frame,
365
+ self.text,
366
+ self._tmgr.theme,
367
+ bg=t.gutter_bg,
368
+ )
369
+ self.gutter.pack(fill="both", expand=True)
370
+ self._multicursor_lines: set[int] = set()
371
+ self._multicursor_active: bool = False
372
+ self.gutter.set_on_marked_change(self._on_marked_lines_change)
373
+ self._heatmap: EditHeatmap | None = (
374
+ EditHeatmap(on_update=self.gutter.redraw) if _HEATMAP_OK else None
375
+ )
376
+ self._rhythm: CodeRhythm | None = CodeRhythm() if _RHYTHM_OK else None
377
+
378
+ self._minimap_frame = tk.Frame(
379
+ self._main, bg=t.minimap_bg, width=MINIMAP_WIDTH)
380
+ self.minimap = MiniMap(self._minimap_frame, self.text, self._tmgr)
381
+ self.minimap.pack(fill="both", expand=True)
382
+ if self._show_minimap:
383
+ self._minimap_frame.pack(side="right", fill="y")
384
+ self._minimap_frame.pack_propagate(False)
385
+
386
+ self.hl = SyntaxHL(self.text, self.lang, self._tmgr)
387
+ self.hl.set_config(self._cfg)
388
+
389
+ self.autocomplete = AutocompletePopup(
390
+ self,
391
+ self.text,
392
+ self._tmgr,
393
+ )
394
+ self.autocomplete.set_lang(self.lang)
395
+ self.autocomplete.set_snippets(self._snippets)
396
+
397
+ self._hover_tip: tk.Toplevel | None = None
398
+ self._balloon: KDocsBalloon | None = None
399
+
400
+ if _STICKY_AVAILABLE and self._sticky_enabled:
401
+ self.sticky_scroll = StickyScroll(
402
+ self._editor_frame,
403
+ self.text,
404
+ self._tmgr.theme,
405
+ font_family=self._font_family,
406
+ font_size=self._font_size,
407
+ on_goto=self.goto_line,
408
+ )
409
+
410
+ self.sticky_scroll.pack(fill="x", side="top", before=self.text)
411
+
412
+ if _FOLDING_AVAILABLE and self._folding_enabled:
413
+ self.code_folding = CodeFolding(
414
+ self.text,
415
+ self._tmgr.theme,
416
+ on_gutter_update=self._on_fold_gutter_update,
417
+ lang=self.lang,
418
+ )
419
+ self.gutter.set_on_fold_toggle(self._on_gutter_fold_click)
420
+
421
+ if _COMPLEXITY_LENS_OK:
422
+ self.complexity_lens = ComplexityLens(self.text, self._tmgr.theme)
423
+
424
+ if _FOCUS_BLOCK_OK:
425
+ self.focus_block = FocusBlock(self.text, self._tmgr.theme)
426
+
427
+ if _STICKY_NOTES_OK:
428
+ self.sticky_notes = StickyNoteGutter(
429
+ self.text,
430
+ self.gutter,
431
+ self._tmgr.theme,
432
+ self._cfg,
433
+ )
434
+
435
+ if _BLAME_AVAILABLE:
436
+ self.inline_blame = InlineBlame(
437
+ self.text,
438
+ self._tmgr.theme,
439
+ mode=self._blame_mode,
440
+ )
441
+ if self._blame_enabled:
442
+ self.inline_blame.set_enabled(True)
443
+
444
+ if _COLOR_PREVIEW_AVAILABLE and self._color_preview_enabled:
445
+ self.color_preview = ColorPreview(
446
+ self.text,
447
+ self._tmgr.theme,
448
+ on_edit_callback=self._on_color_edit,
449
+ )
450
+ self.color_preview.set_enabled(True)
451
+
452
+ if _INLAY_AVAILABLE and self._inlay_hints_enabled:
453
+ self.inlay_hints = InlayHints(
454
+ self.text,
455
+ self._tmgr.theme,
456
+ lang=self.lang,
457
+ )
458
+ self.inlay_hints.set_enabled(True)
459
+
460
+ if _SMART_SEL_AVAILABLE:
461
+ self.smart_selection = SmartSelection(self.text)
462
+
463
+ if _LIGATURE_OK:
464
+ accent = getattr(self._tmgr.theme, "accent", "#cba6f7")
465
+ self.ligature_engine = LigatureEngine(
466
+ self.text, accent_color=accent)
467
+ lig_enabled = self._cfg.get("font_ligatures", False)
468
+ lig_mode = self._cfg.get("ligature_mode", "pseudo")
469
+ if lig_enabled and lig_mode in ("pseudo", "both"):
470
+ self.ligature_engine.set_enabled(True)
471
+
472
+ if _FILEWATCHER_OK:
473
+ self.file_watcher = FileWatcher(
474
+ self,
475
+ on_changed=self._on_file_changed_externally,
476
+ interval_ms=2000,
477
+ )
478
+
479
+ def _calc_tab_pixels(self) -> int:
480
+ """Calcula o tamanho do tab em pixels com base na fonte e no tab_size configurados."""
481
+ ts = self._cfg.get("tab_size", TAB_SIZE)
482
+ try:
483
+ f = tkfont.Font(family=self._font_family, size=self._font_size)
484
+ return max(1, f.measure("0") * ts)
485
+ except tk.TclError:
486
+ return ts * 8
487
+
488
+ def _hsb_set(self, first: str, last: str) -> None:
489
+ """Exibe a barra de rolagem horizontal apenas quando o conteúdo ultrapassa a borda."""
490
+ self._hsb.set(first, last)
491
+ if float(first) <= 0.0 and float(last) >= 1.0:
492
+ self._hsb.pack_forget()
493
+ elif not self._hsb.winfo_ismapped():
494
+ self._hsb.pack(side="bottom", fill="x")
495
+
496
+ def _bind_events(self) -> None:
497
+ """Registra todos os bindings de teclado, mouse e clipboard do editor."""
498
+ txt = self.text
499
+
500
+ txt.bind("<<Modified>>", self._on_modified)
501
+
502
+ txt.bind("<KeyRelease>", self._on_key)
503
+ txt.bind("<ButtonRelease-1>", self._on_click)
504
+ txt.bind("<ButtonRelease-3>", self._on_right_click)
505
+
506
+ txt.bind("<B1-Motion>", self._on_drag_select)
507
+
508
+ txt.bind("<Return>", self._on_return)
509
+
510
+ txt.bind("<Tab>", self._on_tab)
511
+
512
+ txt.bind("<Shift-Tab>", self._on_shift_tab)
513
+
514
+ txt.bind("<BackSpace>", self._on_backspace)
515
+
516
+ txt.bind("<Delete>", self._on_delete_key)
517
+
518
+ txt.bind("<Up>", self._on_up)
519
+ txt.bind("<Down>", self._on_down)
520
+ txt.bind("<Escape>", self._on_escape)
521
+
522
+ for opener in AUTO_CLOSE:
523
+ txt.bind(opener, self._make_auto_pair(opener))
524
+
525
+ txt.bind("<Control-equal>", lambda _: self.zoom(+1))
526
+ txt.bind("<Control-minus>", lambda _: self.zoom(-1))
527
+ txt.bind("<Control-0>", lambda _: self.zoom(0))
528
+ txt.bind("<Control-KP_Add>", lambda _: self.zoom(+1))
529
+ txt.bind("<Control-KP_Subtract>", lambda _: self.zoom(-1))
530
+
531
+ txt.bind("<Control-slash>", lambda _: self.toggle_comment())
532
+ txt.bind("<Control-d>", lambda _: self.duplicate_line())
533
+ txt.bind("<Alt-Up>", lambda _: self.move_line(-1))
534
+ txt.bind("<Alt-Down>", lambda _: self.move_line(+1))
535
+ txt.bind("<Control-l>", lambda _: self.select_line())
536
+ txt.bind("<Control-BackSpace>", lambda _: self.delete_word_left())
537
+ txt.bind("<Control-Delete>", lambda _: self.delete_word_right())
538
+
539
+ txt.bind("<Control-c>", self._on_copy)
540
+ txt.bind("<Control-x>", self._on_cut)
541
+ txt.bind("<Control-v>", self._on_paste)
542
+
543
+ def _safe_undo(_e):
544
+ with contextlib.suppress(tk.TclError):
545
+ self.text.edit_undo()
546
+ return "break"
547
+
548
+ def _safe_redo(_e):
549
+ with contextlib.suppress(tk.TclError):
550
+ self.text.edit_redo()
551
+ return "break"
552
+
553
+ txt.bind("<Control-z>", _safe_undo)
554
+ txt.bind("<Control-Z>", _safe_redo)
555
+ txt.bind("<Control-y>", _safe_redo)
556
+
557
+ txt.bind("<Control-a>", self._on_select_all)
558
+
559
+ txt.bind("<KeyPress-Control_L>", lambda _: self._set_ctrl(True))
560
+ txt.bind("<KeyPress-Control_R>", lambda _: self._set_ctrl(True))
561
+ txt.bind("<KeyRelease-Control_L>", lambda _: self._set_ctrl(False))
562
+ txt.bind("<KeyRelease-Control_R>", lambda _: self._set_ctrl(False))
563
+ txt.bind("<FocusOut>", lambda _: self._set_ctrl(False), add=True)
564
+
565
+ txt.bind("<Motion>", self._on_mouse_motion)
566
+ txt.bind("<Leave>", self._hide_hover)
567
+ txt.bind("<Motion>", self._on_mouse_motion_diag, add=True)
568
+ txt.bind("<Leave>", self._hide_diag_tip, add=True)
569
+
570
+ txt.bind("<F12>", lambda _: self.lsp_goto_definition())
571
+ txt.bind("<Control-F12>", lambda _: self.lsp_goto_implementation())
572
+ txt.bind("<Control-period>", lambda _: self.lsp_code_action())
573
+ txt.bind("<Shift-F12>", lambda _: self.lsp_find_references())
574
+ txt.bind("<Control-Button-1>", self._on_ctrl_click)
575
+ txt.bind("<F6>", lambda _: self.lsp_rename_symbol())
576
+
577
+ txt.bind("<MouseWheel>", self._on_mousewheel)
578
+ txt.bind("<Button-4>", self._on_button4)
579
+ txt.bind("<Button-5>", self._on_button5)
580
+
581
+ txt.bind("<Alt-Shift-Right>", lambda _: self._smart_expand())
582
+ txt.bind("<Alt-Shift-Left>", lambda _: self._smart_shrink())
583
+
584
+ txt.bind("<Control-Shift-bracketleft>",
585
+ lambda _: self._fold_at_cursor())
586
+ txt.bind("<Control-Shift-bracketright>",
587
+ lambda _: self._unfold_at_cursor())
588
+
589
+ txt.bind("<Control-k>", self._on_ctrl_k_prefix)
590
+
591
+ txt.bind("<Control-j>", lambda _: self.join_lines())
592
+ txt.bind("<Control-Shift-k>", lambda _: self.delete_line())
593
+
594
+ txt.bind("<ButtonRelease-1>",
595
+ lambda _: self._reset_smart_history(), add=True)
596
+ txt.bind("<KeyRelease-Left>",
597
+ lambda _: self._reset_smart_history(), add=True)
598
+ txt.bind("<KeyRelease-Right>",
599
+ lambda _: self._reset_smart_history(), add=True)
600
+ txt.bind("<KeyRelease-Up>",
601
+ lambda _: self._reset_smart_history(), add=True)
602
+ txt.bind("<KeyRelease-Down>",
603
+ lambda _: self._reset_smart_history(), add=True)
604
+
605
+ _MOD_KEYS: frozenset[str] = frozenset(
606
+ {
607
+ "Shift_L",
608
+ "Shift_R",
609
+ "Control_L",
610
+ "Control_R",
611
+ "Alt_L",
612
+ "Alt_R",
613
+ "Meta_L",
614
+ "Meta_R",
615
+ "Super_L",
616
+ "Super_R",
617
+ "Caps_Lock",
618
+ "Num_Lock",
619
+ "Scroll_Lock",
620
+ "F1",
621
+ "F2",
622
+ "F3",
623
+ "F4",
624
+ "F5",
625
+ "F6",
626
+ "F7",
627
+ "F8",
628
+ "F9",
629
+ "F10",
630
+ "F11",
631
+ "F12",
632
+ }
633
+ )
634
+
635
+ def _on_key(self, e: tk.Event) -> None:
636
+ """Após a inserção: atualiza tudo. Intercepta teclas em modo multicursor."""
637
+ sym = getattr(e, "keysym", "")
638
+ if sym in self._MOD_KEYS:
639
+ return
640
+
641
+ if self._multicursor_active and self._multicursor_lines:
642
+ ch = getattr(e, "char", "")
643
+ if sym == "Escape":
644
+ self.gutter.clear_marked()
645
+ return
646
+ if ch and ch.isprintable() and len(ch) == 1:
647
+ self._multicursor_insert(ch)
648
+ elif sym == "BackSpace":
649
+ self._multicursor_delete_col(0)
650
+
651
+ if self._heatmap is not None:
652
+ with contextlib.suppress(tk.TclError, ValueError):
653
+ cur_ln = int(self.text.index(tk.INSERT).split(".")[0])
654
+ self._heatmap.record_edit(cur_ln)
655
+ if self._rhythm is not None:
656
+ char = getattr(e, "char", "") or ""
657
+ self._rhythm.record_keystroke(char)
658
+ self.hl.schedule()
659
+ self.hl.hl_current_line()
660
+ self.hl.match_brackets()
661
+ self._update_cursor()
662
+ self.gutter._schedule_redraw()
663
+ if not (self._is_large_mode or self._is_giant_mode):
664
+ self.minimap._schedule_redraw()
665
+
666
+ if not (self._is_large_mode or self._is_giant_mode):
667
+ with contextlib.suppress(tk.TclError):
668
+ if self.color_preview:
669
+ self.color_preview.notify_change()
670
+ with contextlib.suppress(tk.TclError):
671
+ if self.inlay_hints:
672
+ self.inlay_hints.notify_change()
673
+ with contextlib.suppress(tk.TclError):
674
+ if self.code_folding:
675
+ self.code_folding._schedule_scan()
676
+
677
+ if sym in ("Return", "BackSpace", "Delete", "space"):
678
+ if self._kdocs_job:
679
+ with contextlib.suppress(tk.TclError):
680
+ self.after_cancel(self._kdocs_job)
681
+ self._kdocs_job = self.after(250, self._run_kdocs_debounced)
682
+
683
+ if self.lang in ("javascript", "typescript"):
684
+ if self._symbols_job:
685
+ with contextlib.suppress(tk.TclError):
686
+ self.after_cancel(self._symbols_job)
687
+ self._symbols_job = self.after(
688
+ 500, self._run_symbols_debounced)
689
+
690
+ if not (self._is_large_mode or self._is_giant_mode) and sym not in (
691
+ "Left",
692
+ "Right",
693
+ "Up",
694
+ "Down",
695
+ "Home",
696
+ "End",
697
+ "Prior",
698
+ "Next",
699
+ ):
700
+ self._lint_mgr.schedule(
701
+ self.path, self.text.get("1.0", "end-1c"), self.lang
702
+ )
703
+ if self._lsp_mgr and self.path:
704
+ _content = self.text.get("1.0", "end-1c")
705
+ if self._lsp_change_job:
706
+ with contextlib.suppress(tk.TclError):
707
+ self.after_cancel(self._lsp_change_job)
708
+ self._lsp_change_job = self.after(
709
+ 350, lambda c=_content: self._run_lsp_change_debounced(c)
710
+ )
711
+
712
+ if self._autocomplete_enabled:
713
+ if sym and (
714
+ (len(sym) == 1 and (sym.isalnum() or sym in "_$"))
715
+ or sym in ("BackSpace", "Delete", "period")
716
+ ):
717
+ self.autocomplete.trigger()
718
+ elif sym not in (
719
+ "Up",
720
+ "Down",
721
+ "Return",
722
+ "Tab",
723
+ "Escape",
724
+ "Left",
725
+ "Right",
726
+ "Shift_L",
727
+ "Shift_R",
728
+ "Control_L",
729
+ "Control_R",
730
+ "Alt_L",
731
+ "Alt_R",
732
+ "Meta_L",
733
+ "Meta_R",
734
+ ):
735
+ self.autocomplete.hide()
736
+
737
+ def _on_click(self, _e: tk.Event) -> None:
738
+ self.autocomplete.hide()
739
+ self.hl.hl_current_line()
740
+ self.hl.match_brackets()
741
+ self._update_cursor()
742
+
743
+ def _on_right_click(self, e: tk.Event) -> None:
744
+ self._show_context_menu(e)
745
+
746
+ def _on_return(self, _e: tk.Event) -> str:
747
+
748
+ if self.autocomplete.is_visible() and self.autocomplete.accept():
749
+ return "break"
750
+ try:
751
+ pos = self.text.index(tk.INSERT)
752
+ line_num = int(pos.split(".", maxsplit=1)[0])
753
+ cur_line = self.text.get(f"{line_num}.0", f"{line_num}.end")
754
+ stripped = cur_line.lstrip()
755
+ indent = len(cur_line) - len(stripped)
756
+
757
+ opened_block = False
758
+ if (
759
+ stripped
760
+ and stripped[-1] in "{(["
761
+ or self.lang == "python"
762
+ and stripped.endswith(":")
763
+ ):
764
+ indent += self._cfg.get("tab_size", TAB_SIZE)
765
+ opened_block = True
766
+
767
+ closer_on_cursor = self.text.get(tk.INSERT)
768
+ if opened_block and closer_on_cursor in ")]}":
769
+ tab_size = self._cfg.get("tab_size", TAB_SIZE)
770
+ outer_indent = max(0, indent - tab_size)
771
+
772
+ self.text.insert(
773
+ tk.INSERT, "\n" + " " * indent + "\n" + " " * outer_indent
774
+ )
775
+ self.text.mark_set(tk.INSERT, f"{line_num + 1}.{indent}")
776
+ return "break"
777
+
778
+ self.text.insert(tk.INSERT, "\n" + " " * indent)
779
+ except tk.TclError:
780
+ return "break"
781
+ return "break"
782
+
783
+ def _on_tab(self, _e: tk.Event) -> str:
784
+
785
+ if self.autocomplete.is_visible():
786
+ self.autocomplete.accept()
787
+ return "break"
788
+
789
+ with contextlib.suppress(tk.TclError):
790
+ pos = self.text.index(tk.INSERT)
791
+ line = int(pos.split(".", maxsplit=1)[0])
792
+ line_text = self.text.get(f"{line}.0", pos)
793
+ m = re.search(r"[\w$]+$", line_text)
794
+ if m:
795
+ prefix = m.group()
796
+ snip = self._snippets.find_prefix(self.lang, prefix)
797
+ if snip:
798
+ self._snippets.expand(snip, self.text, self.path)
799
+ return "break"
800
+
801
+ with contextlib.suppress(tk.TclError):
802
+ if self.text.tag_ranges(tk.SEL):
803
+ start = int(self.text.index(
804
+ tk.SEL_FIRST).split(".", maxsplit=1)[0])
805
+ end = int(self.text.index(
806
+ tk.SEL_LAST).split(".", maxsplit=1)[0])
807
+ ts = self._cfg.get("tab_size", TAB_SIZE)
808
+ for ln in range(start, end + 1):
809
+ self.text.insert(f"{ln}.0", " " * ts)
810
+ else:
811
+ ts = self._cfg.get("tab_size", TAB_SIZE)
812
+ self.text.insert(tk.INSERT, " " * ts)
813
+ return "break"
814
+
815
+ def _on_shift_tab(self, _e: tk.Event) -> str:
816
+
817
+ with contextlib.suppress(tk.TclError):
818
+ ts = self._cfg.get("tab_size", TAB_SIZE)
819
+ if self.text.tag_ranges(tk.SEL):
820
+ start = int(self.text.index(
821
+ tk.SEL_FIRST).split(".", maxsplit=1)[0])
822
+ end = int(self.text.index(
823
+ tk.SEL_LAST).split(".", maxsplit=1)[0])
824
+ for ln in range(start, end + 1):
825
+ line = self.text.get(f"{ln}.0", f"{ln}.end")
826
+ spaces = len(line) - len(line.lstrip(" "))
827
+ remove = min(spaces, ts)
828
+ if remove:
829
+ self.text.delete(f"{ln}.0", f"{ln}.{remove}")
830
+ else:
831
+ pos = self.text.index(tk.INSERT)
832
+ line_num = pos.split(".", maxsplit=1)[0]
833
+ line = self.text.get(f"{line_num}.0", pos)
834
+ spaces = len(line) - len(line.lstrip(" "))
835
+ remove = min(spaces, ts)
836
+ if remove:
837
+ self.text.delete(f"{line_num}.0", f"{line_num}.{remove}")
838
+ return "break"
839
+
840
+ def _on_backspace(self, _e: tk.Event) -> str | None:
841
+
842
+ with contextlib.suppress(tk.TclError):
843
+ if self.text.tag_ranges(tk.SEL):
844
+ return None
845
+ pos = self.text.index(tk.INSERT)
846
+ col = int(pos.split(".", maxsplit=1)[1])
847
+ line = self.text.get(f"{pos} linestart", pos)
848
+ ts = self._cfg.get("tab_size", TAB_SIZE)
849
+ if line and all(c == " " for c in line) and col > 0:
850
+ remove = col % ts or ts
851
+ self.text.delete(f"{pos} - {remove}c", pos)
852
+ return "break"
853
+ return None
854
+
855
+ def _on_delete_key(self, _e: tk.Event) -> str | None:
856
+
857
+ with contextlib.suppress(tk.TclError):
858
+ if self.text.tag_ranges(tk.SEL):
859
+ return None
860
+ pos = self.text.index(tk.INSERT)
861
+ rest = self.text.get(pos, f"{pos} lineend")
862
+ ts = self._cfg.get("tab_size", TAB_SIZE)
863
+ if rest and all(c == " " for c in rest) and len(rest) > 0:
864
+ remove = len(rest) % ts or ts
865
+ self.text.delete(pos, f"{pos}+{remove}c")
866
+ return "break"
867
+ return None
868
+
869
+ def _on_up(self, _: tk.Event) -> str | None:
870
+ if self.autocomplete.navigate(-1):
871
+ return "break"
872
+ return None
873
+
874
+ def _on_down(self, _: tk.Event) -> str | None:
875
+ if self.autocomplete.navigate(+1):
876
+ return "break"
877
+ return None
878
+
879
+ def _on_escape(self, _: tk.Event) -> str | None:
880
+ if self.autocomplete.is_visible():
881
+ self.autocomplete.hide()
882
+ return "break"
883
+ return None
884
+
885
+ def _on_copy(self, _e: tk.Event) -> str:
886
+ """Copia a seleção para o clipboard e retorna 'break' para suprimir o evento padrão."""
887
+ with contextlib.suppress(tk.TclError):
888
+ if self.text.tag_ranges(tk.SEL):
889
+ text = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
890
+ self.text.clipboard_clear()
891
+ self.text.clipboard_append(text)
892
+ if text and self._on_copy_cb:
893
+ self._on_copy_cb(text, "copy")
894
+ return "break"
895
+
896
+ def _on_cut(self, _e: tk.Event) -> str:
897
+ """Recorta a seleção para o clipboard e retorna 'break' para suprimir o evento padrão."""
898
+ with contextlib.suppress(tk.TclError):
899
+ if self.text.tag_ranges(tk.SEL):
900
+ text = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
901
+ self.text.clipboard_clear()
902
+ self.text.clipboard_append(text)
903
+ self.text.delete(tk.SEL_FIRST, tk.SEL_LAST)
904
+ if text and self._on_copy_cb:
905
+ self._on_copy_cb(text, "cut")
906
+ return "break"
907
+
908
+ def _on_paste(self, _e: tk.Event) -> str:
909
+ """Colar: insere o conteúdo da área de transferência e reagenda o realce."""
910
+ with contextlib.suppress(tk.TclError):
911
+ content = self.text.clipboard_get()
912
+ if self.text.tag_ranges(tk.SEL):
913
+ self.text.delete(tk.SEL_FIRST, tk.SEL_LAST)
914
+ self.text.insert(tk.INSERT, content)
915
+ self.text.after(50, self.hl.schedule)
916
+ return "break"
917
+
918
+ def _on_select_all(self, _: tk.Event) -> str:
919
+ """Seleciona todo o conteúdo do editor e retorna 'break' para suprimir o evento padrão."""
920
+ self.text.tag_add(tk.SEL, "1.0", "end")
921
+ self.text.mark_set(tk.INSERT, "end")
922
+ return "break"
923
+
924
+ def _on_drag_select(self, e: tk.Event) -> str | None:
925
+
926
+ with contextlib.suppress(tk.TclError):
927
+ pos = self.text.index(f"@{e.x},{e.y}")
928
+ sel_start = tk.SEL_FIRST if self.text.tag_ranges(
929
+ tk.SEL) else tk.INSERT
930
+ self.text.tag_add(tk.SEL, sel_start, pos)
931
+ self.text.mark_set(tk.INSERT, pos)
932
+
933
+ def _on_mousewheel(self, e: tk.Event) -> str | None:
934
+ """Rolagem com Ctrl+Roda do mouse = zoom; roda normal = scroll com sensibilidade configurável."""
935
+ if e.state & 0x4:
936
+ delta = 1 if e.delta > 0 else -1
937
+ self.zoom(delta)
938
+ return "break"
939
+ if e.delta:
940
+ speed = getattr(self, "_scroll_speed", 3)
941
+ steps = -1 * (e.delta // 120) * speed
942
+ self.text.yview_scroll(int(steps), "units")
943
+ return "break"
944
+ return None
945
+
946
+ def _on_button4(self, e: tk.Event) -> str | None:
947
+ """Linux: rolagem para cima - Ctrl+Botão-4 = aumentar zoom."""
948
+ if e.state & 0x4:
949
+ self.zoom(1)
950
+ return "break"
951
+ speed = getattr(self, "_scroll_speed", 3)
952
+ self.text.yview_scroll(-speed, "units")
953
+ if getattr(self, "ligature_engine", None):
954
+ self.ligature_engine.on_scroll()
955
+ return None
956
+
957
+ def _on_button5(self, e: tk.Event) -> str | None:
958
+ """Linux: rolagem para baixo - Ctrl+Botão-5 = diminuir zoom."""
959
+ if e.state & 0x4:
960
+ self.zoom(-1)
961
+ return "break"
962
+ speed = getattr(self, "_scroll_speed", 3)
963
+ self.text.yview_scroll(speed, "units")
964
+ if getattr(self, "ligature_engine", None):
965
+ self.ligature_engine.on_scroll()
966
+ return None
967
+
968
+ def _on_mouse_motion(self, e: tk.Event) -> None:
969
+ """Hover para JSDoc e KDocs (estilo VSCode).
970
+
971
+ Proteção: NÃO acionar hover durante arrasto com o botão 1 do mouse (seleção).
972
+ O bit 0x0100 de e.state indica Botão-1 pressionado.
973
+ """
974
+ if e.state & 0x0100:
975
+ return
976
+ if self._hover_job:
977
+ with contextlib.suppress(tk.TclError):
978
+ self.after_cancel(self._hover_job)
979
+
980
+ self._hover_job = self.after(400, lambda: self._show_hover(e.x, e.y))
981
+
982
+ def set_content(self, text: str, preserve_pos: bool = True) -> None:
983
+ """Substitui o conteúdo do editor, preservando a posição do cursor se solicitado."""
984
+ with contextlib.suppress(tk.TclError):
985
+ text, _r, _t = self._sanitize_for_display(text)
986
+ pos = self.text.index(tk.INSERT) if preserve_pos else "1.0"
987
+ self.text.delete("1.0", "end")
988
+ self.text.insert("1.0", text)
989
+ if preserve_pos:
990
+ with contextlib.suppress(tk.TclError):
991
+ self.text.mark_set(tk.INSERT, pos)
992
+ self.hl.schedule()
993
+
994
+ def deliver_diags(self, diags: list[Diag]) -> None:
995
+ """Recebe diagnósticos do LintManager e aplica."""
996
+ self._diags = diags
997
+ self.hl.apply_lint(diags)
998
+ self.gutter.set_lint_lines(diags)
999
+ self.minimap.set_lint_lines(diags)
1000
+
1001
+ def fix_all(self) -> None:
1002
+ """Aplica todas as correções automáticas do ESLint num único passo atômico.
1003
+
1004
+ Usa ``apply_all_eslint_fixes`` do LintManager, que implementa o algoritmo
1005
+ oficial do ESLint: ordena os fixes por posição de início, descarta os que
1006
+ se sobrepõem e aplica os restantes numa única varredura do conteúdo.
1007
+ Isso garante que os offsets originais permaneçam válidos durante toda
1008
+ a operação - ao contrário da abordagem sequencial, que corrompe o arquivo
1009
+ quando dois fixes estão na mesma região.
1010
+ """
1011
+ if self.lang in LINT_JS and self.path:
1012
+ content = self.text.get("1.0", "end-1c")
1013
+ fixed = self._lint_mgr.apply_all_eslint_fixes(
1014
+ self.path, content, self._diags
1015
+ )
1016
+ if fixed != content:
1017
+ self.set_content(fixed)
1018
+
1019
+ def _run_kdocs_debounced(self) -> None:
1020
+ """Executa _update_kdocs após debounce; limpa o job id."""
1021
+ self._kdocs_job = None
1022
+ self._update_kdocs()
1023
+
1024
+ def _run_symbols_debounced(self) -> None:
1025
+ """Executa _refresh_doc_symbols após debounce; limpa o job id."""
1026
+ self._symbols_job = None
1027
+ self._refresh_doc_symbols()
1028
+
1029
+ def _run_lsp_change_debounced(self, c: str) -> None:
1030
+ """Executa _lsp_did_change após debounce; limpa o job id."""
1031
+ self._lsp_change_job = None
1032
+ self._lsp_did_change(c)
1033
+
1034
+ def _update_kdocs(self) -> None:
1035
+ """Atualiza 'kdocs' - ignorado em modo large/giant (operação O(n) sobre o arquivo inteiro)."""
1036
+ if self._is_large_mode or self._is_giant_mode:
1037
+ return
1038
+ content = self.text.get("1.0", "end-1c")
1039
+ self._kdocs = KDocsParser.parse(content)
1040
+ self.hl.apply_kdocs(self._kdocs)
1041
+ self.gutter.set_kdocs_lines(self._kdocs)
1042
+
1043
+ def _refresh_doc_symbols(self) -> None:
1044
+ """Reanalisa símbolos JSDoc - ignorado em modo large/giant."""
1045
+ if self._is_large_mode or self._is_giant_mode:
1046
+ return
1047
+ content = self.text.get("1.0", "end-1c")
1048
+ self._doc_symbols = JSDocParser.parse(content)
1049
+
1050
+ def refresh_custom_keywords(self) -> None:
1051
+ """Reaplica as keywords customizadas do config no highlighter.
1052
+
1053
+ Chamado após o usuário modificar uma entry no CustomKeywordsPanel,
1054
+ ou quando o config é recarregado.
1055
+ """
1056
+ if hasattr(self, "hl") and self.hl is not None:
1057
+ self.hl._setup_custom_kw_tags()
1058
+ self.hl.schedule()
1059
+
1060
+ def apply_theme(self, t: Theme) -> None:
1061
+ """Aplica o tema ao editor (cores, fontes, balão)."""
1062
+
1063
+ self._balloon = None
1064
+ self.config(bg=t.editor_bg)
1065
+ self._main.config(bg=t.editor_bg)
1066
+ self._editor_frame.config(bg=t.editor_bg)
1067
+ self.text.config(
1068
+ bg=t.editor_bg,
1069
+ fg=t.fg,
1070
+ insertbackground=t.cursor,
1071
+ selectbackground=t.sel_bg,
1072
+ selectforeground=t.sel_fg,
1073
+ inactiveselectbackground=t.sel_bg,
1074
+ )
1075
+ self._gutter_frame.config(bg=t.gutter_bg)
1076
+ self.gutter.update_theme(t)
1077
+ self.minimap.update_theme()
1078
+ self._minimap_frame.config(bg=t.minimap_bg)
1079
+ self.hl.reconfigure()
1080
+
1081
+ with contextlib.suppress(tk.TclError):
1082
+ if self.sticky_scroll:
1083
+ self.sticky_scroll.apply_theme(t)
1084
+ with contextlib.suppress(tk.TclError):
1085
+ if self.code_folding:
1086
+ self.code_folding.apply_theme(t)
1087
+ with contextlib.suppress(tk.TclError):
1088
+ if self.inline_blame:
1089
+ self.inline_blame.apply_theme(t)
1090
+ with contextlib.suppress(tk.TclError):
1091
+ if self.color_preview:
1092
+ self.color_preview.apply_theme(t)
1093
+ with contextlib.suppress(tk.TclError):
1094
+ if self.inlay_hints:
1095
+ self.inlay_hints.apply_theme(t)
1096
+ with contextlib.suppress(tk.TclError):
1097
+ if self.complexity_lens:
1098
+ self.complexity_lens.apply_theme(t)
1099
+ with contextlib.suppress(tk.TclError):
1100
+ if self.focus_block:
1101
+ self.focus_block.apply_theme(t)
1102
+ with contextlib.suppress(tk.TclError):
1103
+ if self.sticky_notes:
1104
+ self.sticky_notes.apply_theme(t)
1105
+
1106
+ def _apply_config(self) -> None:
1107
+ """Relê as configurações e as aplica ao widget de edição (fonte, tabs, etc.)."""
1108
+ self._autocomplete_enabled = self._cfg.get("autocomplete", True)
1109
+ if self._cfg.get("line_numbers", True):
1110
+ self._gutter_frame.pack(side="left", fill="y")
1111
+ else:
1112
+ self._gutter_frame.pack_forget()
1113
+
1114
+ def apply_config(self, cfg: ConfigManager) -> None:
1115
+ """Aplica as configurações ao editor (fonte, indentação, minimapa, autocompletar, etc.)."""
1116
+ self._cfg = cfg
1117
+ self._font_size = cfg.get("font_size", FONT_SIZE)
1118
+ self._font_family = cfg.get("font_family", FONT_MONO)
1119
+ self.text.config(font=(self._font_family, self._font_size))
1120
+ self.gutter.update_font(self._font_family, self._font_size)
1121
+
1122
+ lig_enabled = cfg.get("font_ligatures", False)
1123
+ lig_mode = cfg.get("ligature_mode", "pseudo")
1124
+ self._ligature_mode = lig_mode if lig_enabled else "off"
1125
+
1126
+ if lig_enabled and lig_mode in ("native", "both"):
1127
+ with contextlib.suppress(Exception):
1128
+ f = tkfont.Font(family=self._font_family, size=self._font_size)
1129
+ with contextlib.suppress(tk.TclError):
1130
+ f.configure(features="liga")
1131
+ self.text.config(font=f)
1132
+
1133
+ self._scroll_speed = max(1, min(15, cfg.get("scroll_speed", 3)))
1134
+
1135
+ self._autocomplete_enabled = cfg.get("autocomplete", True)
1136
+ self._word_wrap = cfg.get("word_wrap", False)
1137
+ self.text.config(wrap="word" if self._word_wrap else "none")
1138
+ self.text.config(tabs=(self._calc_tab_pixels(),))
1139
+ if cfg.get("minimap", True):
1140
+ if not self._show_minimap:
1141
+ self.toggle_minimap()
1142
+ elif self._show_minimap:
1143
+ self.toggle_minimap()
1144
+ self.hl.reconfigure()
1145
+ with contextlib.suppress(Exception):
1146
+ self.hl.set_idle_ms(cfg.get("hl_idle_ms", 60))
1147
+
1148
+ with contextlib.suppress(tk.TclError):
1149
+ if self.sticky_scroll:
1150
+ self.sticky_scroll.update_font(
1151
+ self._font_family, self._font_size)
1152
+ self.sticky_scroll.set_enabled(cfg.get("sticky_scroll", True))
1153
+ with contextlib.suppress(tk.TclError):
1154
+ if self.code_folding:
1155
+ enabled = cfg.get("code_folding", True)
1156
+ self._folding_enabled = enabled
1157
+ with contextlib.suppress(tk.TclError):
1158
+ if self.inline_blame:
1159
+ self._blame_enabled = cfg.get("inline_blame", False)
1160
+ self._blame_mode = cfg.get("inline_blame_mode", "cursor")
1161
+ self.inline_blame.set_mode(self._blame_mode)
1162
+ self.inline_blame.set_enabled(self._blame_enabled)
1163
+ with contextlib.suppress(tk.TclError):
1164
+ if self.color_preview:
1165
+ enabled = cfg.get("color_preview", True)
1166
+ self._color_preview_enabled = enabled
1167
+ self.color_preview.set_enabled(enabled)
1168
+ with contextlib.suppress(tk.TclError):
1169
+ if self.inlay_hints:
1170
+ enabled = cfg.get("inlay_hints", False)
1171
+ self._inlay_hints_enabled = enabled
1172
+ self.inlay_hints.set_enabled(enabled)
1173
+
1174
+ with contextlib.suppress(Exception):
1175
+ if self.ligature_engine:
1176
+ lig_enabled = cfg.get("font_ligatures", False)
1177
+ lig_mode = cfg.get("ligature_mode", "pseudo")
1178
+ pseudo_on = lig_enabled and lig_mode in ("pseudo", "both")
1179
+ self.ligature_engine.set_enabled(pseudo_on)
1180
+ accent = getattr(self._tmgr.theme, "accent", "#cba6f7")
1181
+ self.ligature_engine.update_accent(accent)
1182
+
1183
+ def _smart_expand(self) -> str:
1184
+ """Expande a seleção para o próximo nível semântico (Alt+Shift+ -> ).
1185
+
1186
+ Returns:
1187
+ str: 'break' para suprimir o comportamento padrão do Tkinter.
1188
+ """
1189
+ if self.smart_selection:
1190
+ self.smart_selection.expand()
1191
+ return "break"
1192
+
1193
+ def _smart_shrink(self) -> str:
1194
+ """Contrai a seleção para o nível semântico anterior (Alt+Shift+ <- ).
1195
+
1196
+ Returns:
1197
+ str: 'break' para suprimir o comportamento padrão do Tkinter.
1198
+ """
1199
+ if self.smart_selection:
1200
+ self.smart_selection.shrink()
1201
+ return "break"
1202
+
1203
+ def _reset_smart_history(self) -> None:
1204
+ """Reinicia o histórico de posições do cursor para navegação inteligente."""
1205
+ if self.smart_selection:
1206
+ self.smart_selection.reset_history()
1207
+
1208
+ def _fold_at_cursor(self) -> str:
1209
+ """Dobra o bloco de código na linha atual do cursor.
1210
+
1211
+ Returns:
1212
+ str: 'break' para suprimir o comportamento padrão do Tkinter.
1213
+ """
1214
+ if self.code_folding:
1215
+ with contextlib.suppress(tk.TclError, ValueError):
1216
+ idx = self.text.index(tk.INSERT)
1217
+ ln = int(idx.split(".", 1)[0])
1218
+ self.code_folding.toggle_fold(ln)
1219
+ return "break"
1220
+
1221
+ def _unfold_at_cursor(self) -> str:
1222
+ """Expande o bloco de código na linha atual do cursor.
1223
+
1224
+ Returns:
1225
+ str: 'break' para suprimir o comportamento padrão do Tkinter.
1226
+ """
1227
+ if self.code_folding:
1228
+ with contextlib.suppress(tk.TclError, ValueError, AttributeError):
1229
+ idx = self.text.index(tk.INSERT)
1230
+ ln = int(idx.split(".", 1)[0])
1231
+ region = self.code_folding._find_region_at(ln)
1232
+ if region and region.folded:
1233
+ self.code_folding.unfold(region)
1234
+ return "break"
1235
+
1236
+ def _on_ctrl_k_prefix(self, _event: tk.Event) -> None:
1237
+ """Captura o prefixo Ctrl+K para atalhos compostos.
1238
+
1239
+ Segunda tecla:
1240
+ 0 = dobrar tudo
1241
+ J = expandir tudo
1242
+ L = alternar dobramento na linha atual
1243
+ U = MAIÚSCULAS (seleção)
1244
+ D = minúsculas (seleção)
1245
+ T = title Case (seleção)
1246
+ C = camelCase (seleção)
1247
+ S = snake_case (seleção)
1248
+ B = Base64 encode (seleção)
1249
+ W = word count rápido (tooltip no cursor)
1250
+ I = inserir UUID
1251
+ N = inserir timestamp ISO
1252
+ X = deletar linha
1253
+ R = reverter arquivo
1254
+ """
1255
+
1256
+ def _handle_second_key(event: tk.Event) -> str:
1257
+ """Processa a segunda tecla do atalho Ctrl+K+X."""
1258
+ self.text.unbind("<KeyPress>")
1259
+ sym = getattr(event, "keysym", "").lower()
1260
+
1261
+ if sym == "0" and self.code_folding:
1262
+ self.code_folding.fold_all()
1263
+ elif sym == "j" and self.code_folding:
1264
+ self.code_folding.unfold_all()
1265
+ elif sym == "l" and self.code_folding:
1266
+ with contextlib.suppress(tk.TclError, ValueError):
1267
+ ln = int(self.text.index(tk.INSERT).split(".", 1)[0])
1268
+ self.code_folding.toggle_fold(ln)
1269
+
1270
+ elif sym == "u":
1271
+ self.transform_case("upper")
1272
+ elif sym == "d":
1273
+ self.transform_case("lower")
1274
+ elif sym == "t":
1275
+ self.transform_case("title")
1276
+ elif sym == "c":
1277
+ self.transform_case("camel")
1278
+ elif sym == "s":
1279
+ self.transform_case("snake")
1280
+
1281
+ elif sym == "b":
1282
+ with contextlib.suppress(ImportError):
1283
+ from src.editor.text_transforms import apply_transform
1284
+
1285
+ apply_transform(self.text, "b64enc")
1286
+
1287
+ elif sym == "i":
1288
+ with contextlib.suppress(ImportError):
1289
+ from src.editor.text_transforms import insert_at_cursor
1290
+
1291
+ insert_at_cursor(self.text, "uuid")
1292
+ elif sym == "n":
1293
+ with contextlib.suppress(ImportError):
1294
+ from src.editor.text_transforms import insert_at_cursor
1295
+
1296
+ insert_at_cursor(self.text, "ts_iso")
1297
+
1298
+ elif sym == "w":
1299
+ self._show_word_count_tip()
1300
+
1301
+ elif sym == "x":
1302
+ self.delete_line()
1303
+
1304
+ elif sym == "r":
1305
+ self.revert()
1306
+
1307
+ return "break"
1308
+
1309
+ self.text.unbind("<KeyPress>")
1310
+ self.text.bind("<KeyPress>", _handle_second_key)
1311
+
1312
+ def _show_word_count_tip(self) -> None:
1313
+ """Mostra contagem de palavras/linhas/chars em um tooltip rápido."""
1314
+ with contextlib.suppress(tk.TclError):
1315
+ if self.text.tag_ranges(tk.SEL):
1316
+ content = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
1317
+ scope = "seleção"
1318
+ else:
1319
+ content = self.text.get("1.0", "end-1c")
1320
+ scope = "arquivo"
1321
+ words = len(re.findall(r"\S+", content))
1322
+ lines = content.count("\n") + (1 if content else 0)
1323
+ chars = len(content)
1324
+ msg = f"{scope}: {words} palavras - {lines} linhas - {chars} chars"
1325
+ self._show_context_info(msg)
1326
+
1327
+ def _on_fold_gutter_update(self, fold_map: dict) -> None:
1328
+ """Atualiza o gutter com ícones de fold/unfold.
1329
+
1330
+ Chamado pelo CodeFolding quando as regiões dobráveis mudam.
1331
+
1332
+ Args:
1333
+ fold_map: Dicionário {linha_1based: está_dobrada}.
1334
+ """
1335
+ self.gutter.set_fold_map(fold_map)
1336
+ logger.debug("CodeFolding gutter update: %d regions", len(fold_map))
1337
+
1338
+ def _on_gutter_fold_click(self, line: int) -> None:
1339
+ """Alterna fold ao clicar no ícone ▸/▾ do gutter.
1340
+
1341
+ Args:
1342
+ line: Número da linha (1-based) clicada.
1343
+ """
1344
+ if self.code_folding:
1345
+ self.code_folding.toggle_fold(line)
1346
+
1347
+ def _on_color_edit(
1348
+ self,
1349
+ old_text: str,
1350
+ new_hex: str,
1351
+ line: int,
1352
+ col: int,
1353
+ ) -> None:
1354
+ """Substitui uma cor no editor após edição pelo color picker.
1355
+
1356
+ Chamado pelo ColorPreview quando o usuário escolhe uma nova cor.
1357
+
1358
+ Args:
1359
+ old_text: Texto original da cor (ex: '#ff0000').
1360
+ new_hex: Nova cor em formato hex (ex: '#00ff00').
1361
+ line: Número da linha (1-based) onde a cor está.
1362
+ col: Coluna (0-based) de início do valor de cor.
1363
+ """
1364
+ with contextlib.suppress(tk.TclError):
1365
+ line_text = self.text.get(f"{line}.0", f"{line}.end")
1366
+ pos = line_text.find(old_text, col)
1367
+ if pos >= 0:
1368
+ start = f"{line}.{pos}"
1369
+ end = f"{line}.{pos + len(old_text)}"
1370
+ self.text.delete(start, end)
1371
+ self.text.insert(start, new_hex)
1372
+ self.modified = True
1373
+
1374
+ @staticmethod
1375
+ def _detect_git_root(path: Path) -> Path | None:
1376
+ """Detecta a raiz do repositório Git para um arquivo.
1377
+
1378
+ Percorre os diretórios pais buscando um diretório `.git`.
1379
+
1380
+ Args:
1381
+ path: Caminho do arquivo aberto no editor.
1382
+
1383
+ Returns:
1384
+ Path | None: Caminho da raiz do repositório ou None.
1385
+ """
1386
+ with contextlib.suppress(OSError):
1387
+ current = path.parent if path.is_file() else path
1388
+ for parent in (current, *current.parents):
1389
+ if (parent / ".git").exists():
1390
+ return parent
1391
+ return None
1392
+
1393
+ _BOMS = (
1394
+ (b"\xff\xfe\x00\x00", "utf-32-le", "UTF-32-LE"),
1395
+ (b"\x00\x00\xfe\xff", "utf-32-be", "UTF-32-BE"),
1396
+ (b"\xef\xbb\xbf", "utf-8", "UTF-8 BOM"),
1397
+ (b"\xff\xfe", "utf-16-le", "UTF-16-LE"),
1398
+ (b"\xfe\xff", "utf-16-be", "UTF-16-BE"),
1399
+ )
1400
+
1401
+ def _decode_bytes(self, raw: bytes) -> str:
1402
+ """Detecta a codificação e decodifica os bytes, guardando como regravar o arquivo.
1403
+
1404
+ Ordem de tentativa:
1405
+ 1. BOM (UTF-32, UTF-8, UTF-16)
1406
+ 2. UTF-8 estrito: texto que decodifica como UTF-8 praticamente nunca é outra codificação.
1407
+ Os detectores erram em arquivos curtos (um UTF-8 com emoji chegou a ser lido como
1408
+ GB18030), então só entram depois.
1409
+ 3. charset_normalizer / chardet, se instalados
1410
+ 4. Lista de codificações comuns
1411
+ """
1412
+ self._file_codec, self._file_bom = None, b""
1413
+ for bom, codec, label in self._BOMS:
1414
+ if raw.startswith(bom):
1415
+ with contextlib.suppress(UnicodeDecodeError):
1416
+ content = raw[len(bom):].decode(codec)
1417
+ self.encoding, self._file_codec, self._file_bom = label, codec, bom
1418
+ return content
1419
+
1420
+ with contextlib.suppress(UnicodeDecodeError):
1421
+ content = raw.decode("utf-8")
1422
+ self.encoding, self._file_codec = "UTF-8", "utf-8"
1423
+ return content
1424
+
1425
+ detected: str | None = None
1426
+ with contextlib.suppress(ImportError, Exception):
1427
+ import charset_normalizer as _cn
1428
+
1429
+ result = _cn.from_bytes(raw).best()
1430
+ if result and result.encoding:
1431
+ detected = str(result.encoding)
1432
+ if detected is None:
1433
+ with contextlib.suppress(ImportError, Exception):
1434
+ import chardet as _cd
1435
+
1436
+ guess = _cd.detect(raw)
1437
+ if guess and guess.get("confidence", 0) > 0.7:
1438
+ detected = guess["encoding"]
1439
+
1440
+ candidates = [detected] if detected else []
1441
+ candidates += ["cp1252", "cp1250", "iso-8859-2", "shift-jis", "gb2312", "euc-kr"]
1442
+ for enc in candidates:
1443
+ with contextlib.suppress(UnicodeDecodeError, LookupError):
1444
+ content = raw.decode(enc)
1445
+ self.encoding, self._file_codec = enc.upper(), enc
1446
+ return content
1447
+
1448
+ self.encoding, self._file_codec = "LATIN-1", "latin-1"
1449
+ return raw.decode("latin-1")
1450
+
1451
+ _SAVE_ENCODINGS: dict[str, tuple[str, bytes]] = {
1452
+ "UTF-8": ("utf-8", b""),
1453
+ "UTF-8 BOM": ("utf-8", b"\xef\xbb\xbf"),
1454
+ "UTF-16": ("utf-16-le", b"\xff\xfe"),
1455
+ "UTF-16-LE": ("utf-16-le", b""),
1456
+ "UTF-16-BE": ("utf-16-be", b""),
1457
+ }
1458
+
1459
+ def set_save_encoding(self, label: str) -> bool:
1460
+ """Define a codificação em que o arquivo será gravado (seletor da barra de status).
1461
+
1462
+ Devolve ``False`` se o nome não corresponde a um codec conhecido.
1463
+ """
1464
+ name = label.strip().upper().replace("_", "-")
1465
+ if name == "UTF-8-BOM":
1466
+ name = "UTF-8 BOM"
1467
+ if name in self._SAVE_ENCODINGS:
1468
+ codec, bom = self._SAVE_ENCODINGS[name]
1469
+ else:
1470
+ codec, bom = name.lower(), b""
1471
+ try:
1472
+ "".encode(codec)
1473
+ except LookupError:
1474
+ return False
1475
+ self.encoding, self._file_codec, self._file_bom = name, codec, bom
1476
+ return True
1477
+
1478
+ def _save_codec(self) -> tuple[str, bytes]:
1479
+ """Codec e BOM para gravar: os do arquivo como foi aberto, ou a config em arquivo novo."""
1480
+ if self._file_codec:
1481
+ return self._file_codec, self._file_bom
1482
+ wanted = str(self._cfg.get("encoding", "utf-8") or "utf-8").lower()
1483
+ if wanted in ("utf-8-bom", "utf-8-sig", "utf8-bom"):
1484
+ return "utf-8", b"\xef\xbb\xbf"
1485
+ return wanted.replace("_", "-"), b""
1486
+
1487
+ def _encode_for_save(self, text: str) -> bytes:
1488
+ """Codifica ``text`` na codificação do arquivo.
1489
+
1490
+ Se o texto passou a ter caracteres que a codificação original não guarda (um emoji
1491
+ digitado em um arquivo Windows-1252, por exemplo), pergunta antes de converter para
1492
+ UTF-8 em vez de falhar ou de perder os caracteres.
1493
+ """
1494
+ codec, bom = self._save_codec()
1495
+ try:
1496
+ return bom + text.encode(codec)
1497
+ except UnicodeEncodeError:
1498
+ label = self.encoding or codec.upper()
1499
+ if not messagebox.askyesno(
1500
+ _t("err.title"), _t("err.encoding_lossy", enc=label), icon="warning", parent=self
1501
+ ):
1502
+ raise SaveDeclined from None
1503
+ self.encoding, self._file_codec, self._file_bom = "UTF-8", "utf-8", b""
1504
+ return text.encode("utf-8")
1505
+ except LookupError as exc:
1506
+ raise UnicodeError(f"codificação desconhecida: {codec}") from exc
1507
+
1508
+ def _sanitize_for_display(self, content: str) -> tuple[str, int, int]:
1509
+ """Remove/substitui caracteres invisíveis que destroem a performance do Tk.
1510
+
1511
+ Usa str.translate() com tabela pré-computada - O(n) único passo, muito
1512
+ mais rápido que múltiplos .replace() em loop.
1513
+
1514
+ Também trunca linhas individuais que excedem MAX_LINE_RENDER_CHARS para
1515
+ evitar que o layout engine do Tk trave em linhas monstruosas.
1516
+
1517
+ Returns:
1518
+ (content_sanitizado, n_chars_removidos, n_linhas_truncadas)
1519
+ """
1520
+ original_len = len(content)
1521
+
1522
+ sanitized = content.translate(_SANITIZE_TABLE)
1523
+ n_removed = original_len - len(sanitized)
1524
+
1525
+ n_truncated = 0
1526
+ lines = sanitized.split("\n")
1527
+ if max(map(len, lines)) > MAX_LINE_RENDER_CHARS:
1528
+ for i, ln in enumerate(lines):
1529
+ if len(ln) > MAX_LINE_RENDER_CHARS:
1530
+ lines[i] = (
1531
+ ln[:MAX_LINE_RENDER_CHARS]
1532
+ + f" [...+{len(ln) - MAX_LINE_RENDER_CHARS} chars truncados]"
1533
+ )
1534
+ n_truncated += 1
1535
+ sanitized = "\n".join(lines)
1536
+
1537
+ return sanitized, n_removed, n_truncated
1538
+
1539
+ def _show_sanitize_banner(self, n_removed: int, n_truncated: int) -> None:
1540
+ """Exibe banner informativo quando o arquivo foi sanitizado."""
1541
+ parts: list[str] = []
1542
+ if n_removed:
1543
+ parts.append(
1544
+ f"{n_removed:,} caractere(s) invisível(is) removido(s)")
1545
+ if n_truncated:
1546
+ parts.append(
1547
+ f"{n_truncated} linha(s) truncada(s) (>{MAX_LINE_RENDER_CHARS:,} chars)"
1548
+ )
1549
+ if not parts:
1550
+ return
1551
+ msg = (
1552
+ "Sanitizacao aplicada: " +
1553
+ ", ".join(parts) + " (arquivo original intacto)"
1554
+ )
1555
+ with contextlib.suppress(tk.TclError):
1556
+ t = self._tmgr.theme
1557
+ lbl = tk.Label(
1558
+ self._editor_frame,
1559
+ text=msg,
1560
+ bg=getattr(t, "warn_bg", "#332b00"),
1561
+ fg=getattr(t, "warn_fg", "#f9e2af"),
1562
+ font=(FONT_UI, 8),
1563
+ anchor="w",
1564
+ padx=8,
1565
+ cursor="hand2",
1566
+ )
1567
+ lbl.pack(side="bottom", fill="x")
1568
+ lbl.bind(
1569
+ "<Button-1>", lambda _e: lbl.destroy() if lbl.winfo_exists() else None
1570
+ )
1571
+ self.after(12_000, lambda: lbl.destroy()
1572
+ if lbl.winfo_exists() else None)
1573
+
1574
+ def _normalize_eol(self, content: str) -> tuple[str, str]:
1575
+ """Detecta e normaliza final de linha; retorna (content_lf, eol_original)."""
1576
+ crlf = "\r\n"
1577
+ cr = "\r"
1578
+ lf = "\n"
1579
+ if crlf in content:
1580
+ return content.replace(crlf, lf), crlf
1581
+ if cr in content:
1582
+ return content.replace(cr, lf), cr
1583
+ return content, lf
1584
+
1585
+ def _sniff_encoding_eol(self, header: bytes) -> tuple[str, str]:
1586
+ """Detecta encoding e EOL a partir dos primeiros bytes do arquivo."""
1587
+ bom8 = bytes([0xEF, 0xBB, 0xBF])
1588
+ bom16le = bytes([0xFF, 0xFE])
1589
+ bom16be = bytes([0xFE, 0xFF])
1590
+ if header.startswith(bom8):
1591
+ enc = "UTF-8 BOM"
1592
+ elif header.startswith(bom16le) or header.startswith(bom16be):
1593
+ enc = "UTF-16"
1594
+ else:
1595
+ enc = "UTF-8"
1596
+ crlf_b = bytes([0x0D, 0x0A])
1597
+ cr_b = bytes([0x0D])
1598
+ if crlf_b in header:
1599
+ eol = chr(0x0D) + chr(0x0A)
1600
+ elif cr_b in header:
1601
+ eol = chr(0x0D)
1602
+ else:
1603
+ eol = chr(0x0A)
1604
+ return enc, eol
1605
+
1606
+ def _disable_heavy_features(self) -> None:
1607
+ """Desativa funcionalidades pesadas para melhorar performance em arquivos grandes."""
1608
+
1609
+ self._is_loading = False
1610
+ self._load_chunks = []
1611
+ with contextlib.suppress(tk.TclError):
1612
+ self.hl.disable_large_file()
1613
+ with contextlib.suppress(tk.TclError):
1614
+ if self.sticky_scroll:
1615
+ self.sticky_scroll.set_enabled(False)
1616
+ with contextlib.suppress(tk.TclError):
1617
+ if self.code_folding:
1618
+ self.code_folding.unfold_all()
1619
+ self.code_folding.suspend(True)
1620
+ with contextlib.suppress(tk.TclError):
1621
+ if self.inline_blame:
1622
+ self.inline_blame.set_enabled(False)
1623
+ with contextlib.suppress(tk.TclError):
1624
+ if self.color_preview:
1625
+ self.color_preview.set_enabled(False)
1626
+ with contextlib.suppress(tk.TclError):
1627
+ if self.inlay_hints:
1628
+ self.inlay_hints.set_enabled(False)
1629
+ with contextlib.suppress(tk.TclError):
1630
+ if self.complexity_lens:
1631
+ self.complexity_lens.set_enabled(False)
1632
+ with contextlib.suppress(Exception):
1633
+ self._lint_mgr.schedule(None, "", "text")
1634
+
1635
+ def _restore_full_features(self) -> None:
1636
+ """Reativa os recursos suspensos; só chamar depois que o conteúdo correto já está no widget."""
1637
+ if self.code_folding:
1638
+ self.code_folding.suspend(False)
1639
+ if self.complexity_lens:
1640
+ self.complexity_lens.set_enabled(True)
1641
+ with contextlib.suppress(tk.TclError):
1642
+ if self.sticky_scroll and self._cfg.get("sticky_scroll", True):
1643
+ self.after(
1644
+ 50,
1645
+ lambda: (
1646
+ self.sticky_scroll.set_enabled(True)
1647
+ if self.sticky_scroll
1648
+ else None
1649
+ ),
1650
+ )
1651
+ with contextlib.suppress(tk.TclError):
1652
+ if self.inline_blame:
1653
+ self.inline_blame.set_enabled(
1654
+ self._cfg.get("inline_blame", False))
1655
+ with contextlib.suppress(tk.TclError):
1656
+ if self.color_preview:
1657
+ self.color_preview.set_enabled(
1658
+ self._cfg.get("color_preview", True))
1659
+ with contextlib.suppress(tk.TclError):
1660
+ if self.inlay_hints:
1661
+ self.inlay_hints.set_enabled(
1662
+ self._cfg.get("inlay_hints", False))
1663
+ with contextlib.suppress(tk.TclError):
1664
+ self.text.config(undo=True, maxundo=-1)
1665
+
1666
+ def _post_load_common(self, path: Path) -> None:
1667
+ """Rotinas comuns executadas após qualquer tipo de carga."""
1668
+ self._on_title(path.name, False)
1669
+ self._on_cursor(1, 1)
1670
+ with contextlib.suppress(tk.TclError):
1671
+ self.text.mark_set(tk.INSERT, "1.0")
1672
+ self.text.see("1.0")
1673
+ _git_root = self._detect_git_root(path)
1674
+ if not (self._is_large_mode or self._is_giant_mode):
1675
+ with contextlib.suppress(tk.TclError):
1676
+ if self.inline_blame:
1677
+ self.inline_blame.set_file(path, _git_root)
1678
+ with contextlib.suppress(tk.TclError):
1679
+ if self.color_preview:
1680
+ self.color_preview.notify_change()
1681
+ with contextlib.suppress(tk.TclError):
1682
+ if self.inlay_hints:
1683
+ self.inlay_hints.set_lang(self.lang)
1684
+ self.inlay_hints.notify_change()
1685
+ with contextlib.suppress(tk.TclError):
1686
+ if self.code_folding:
1687
+ self.code_folding._scan_regions()
1688
+ with contextlib.suppress(tk.TclError):
1689
+ if self.sticky_notes:
1690
+ self.sticky_notes.set_file(str(path))
1691
+ with contextlib.suppress(tk.TclError, AttributeError):
1692
+ if self.sticky_scroll:
1693
+ self.sticky_scroll.notify_scroll()
1694
+ with contextlib.suppress(tk.TclError):
1695
+ self.after(300, self._check_indent_style)
1696
+
1697
+ with contextlib.suppress(Exception):
1698
+ if self.file_watcher:
1699
+ self.file_watcher.watch(path)
1700
+
1701
+ with contextlib.suppress(tk.TclError):
1702
+ self.text.edit_modified(False)
1703
+ self.modified = False
1704
+
1705
+ def _check_indent_style(self) -> None:
1706
+ """Detecta o estilo de indentação predominante e avisa sobre mistura."""
1707
+ with contextlib.suppress(tk.TclError, Exception):
1708
+ content = self.text.get("1.0", "1000.end")
1709
+ lines = content.splitlines()
1710
+ tab_lines = sum(1 for l_ in lines if l_.startswith("\t"))
1711
+ space_lines = sum(
1712
+ 1 for l_ in lines if l_.startswith(" ") or l_.startswith(" ")
1713
+ )
1714
+ total = tab_lines + space_lines
1715
+ if total < 3:
1716
+ return
1717
+ if tab_lines > 0 and space_lines > 0:
1718
+ minority = min(tab_lines, space_lines)
1719
+ if minority / total > 0.15:
1720
+ self._show_context_info(
1721
+ _t(
1722
+ "editor.mixed_indent_warn",
1723
+ "⚠ Indentação mista: {t} linhas com tab - {s} com espaços",
1724
+ t=tab_lines,
1725
+ s=space_lines,
1726
+ )
1727
+ )
1728
+
1729
+ def _on_file_changed_externally(self, path: Path) -> None:
1730
+ """Notifica o usuário que o arquivo foi modificado por outro programa.
1731
+
1732
+ Oferece opção de recarregar ou manter versão em edição.
1733
+
1734
+ Args:
1735
+ path: Caminho do arquivo que foi alterado externamente.
1736
+ """
1737
+ with contextlib.suppress(tk.TclError, Exception):
1738
+ if not path.exists():
1739
+ self._show_context_info(
1740
+ _t(
1741
+ "editor.file_deleted_extern",
1742
+ "⚠ Arquivo deletado externamente: {name}",
1743
+ name=path.name,
1744
+ )
1745
+ )
1746
+ return
1747
+
1748
+ banner = tk.Frame(
1749
+ self._editor_frame,
1750
+ bg="#8b4513",
1751
+ relief="flat",
1752
+ )
1753
+
1754
+ def _reload(_=None):
1755
+ with contextlib.suppress(tk.TclError):
1756
+ banner.destroy()
1757
+ if self.file_watcher:
1758
+ self.file_watcher.reset_baseline()
1759
+ self.load(path)
1760
+
1761
+ def _dismiss(_=None):
1762
+ with contextlib.suppress(tk.TclError):
1763
+ banner.destroy()
1764
+ if self.file_watcher:
1765
+ self.file_watcher.reset_baseline()
1766
+
1767
+ msg = _t(
1768
+ "editor.file_changed_extern",
1769
+ "{name} foi modificado externamente.",
1770
+ name=path.name,
1771
+ )
1772
+ tk.Label(banner, text=msg, bg="#8b4513", fg="#fff", font=(FONT_UI, 9)).pack(
1773
+ side="left", padx=8, pady=4
1774
+ )
1775
+ for lbl, cmd in (
1776
+ (_t("editor.file_reload", "Recarregar"), _reload),
1777
+ (_t("editor.file_keep", "Manter"), _dismiss),
1778
+ ):
1779
+ btn = tk.Label(
1780
+ banner,
1781
+ text=lbl,
1782
+ bg="#a0522d",
1783
+ fg="#fff",
1784
+ font=(FONT_UI, 8, "bold"),
1785
+ cursor="hand2",
1786
+ padx=6,
1787
+ pady=2,
1788
+ )
1789
+ btn.pack(side="right", padx=4, pady=3)
1790
+ btn.bind("<Button-1>", cmd)
1791
+ btn.bind("<Enter>", lambda _, w=btn: w.config(bg="#c47a45"))
1792
+ btn.bind("<Leave>", lambda _, w=btn: w.config(bg="#a0522d"))
1793
+
1794
+ banner.pack(fill="x", before=self.text)
1795
+ banner.after(
1796
+ 30_000, lambda: banner.destroy() if banner.winfo_exists() else None
1797
+ )
1798
+
1799
+ def _close_vfb(self) -> None:
1800
+ """Fecha e descarta o VirtualFileBuffer atual, limpa estado giant."""
1801
+ if self._vfb is not None:
1802
+ with contextlib.suppress(Exception):
1803
+ self._vfb._cancelled = True
1804
+ self._vfb.close()
1805
+ self._vfb = None
1806
+ if self._vp_shift_job:
1807
+ with contextlib.suppress(tk.TclError):
1808
+ self.after_cancel(self._vp_shift_job)
1809
+ self._vp_shift_job = None
1810
+
1811
+ with contextlib.suppress(tk.TclError, AttributeError):
1812
+ if self._giant_status and self._giant_status.winfo_exists():
1813
+ self._giant_status.pack_forget()
1814
+ self._giant_status.destroy()
1815
+ self._giant_status = None
1816
+ self._is_giant_mode = False
1817
+ self._is_large_mode = False
1818
+
1819
+ def _show_loading_overlay(self, message: str = "") -> None:
1820
+ """Exibe banner de carregamento centralizado sobre o editor."""
1821
+ self._hide_loading_overlay()
1822
+ t = self._tmgr.theme
1823
+ with contextlib.suppress(tk.TclError):
1824
+ overlay = tk.Frame(
1825
+ self._editor_frame,
1826
+ bg=getattr(t, "floating_bg", t.editor_bg),
1827
+ relief="flat",
1828
+ highlightthickness=1,
1829
+ highlightbackground=getattr(t, "floating_border", t.fg_muted),
1830
+ )
1831
+ lbl = tk.Label(
1832
+ overlay,
1833
+ text=message,
1834
+ bg=getattr(t, "floating_bg", t.editor_bg),
1835
+ fg=t.fg,
1836
+ font=(FONT_UI, 11),
1837
+ justify="center",
1838
+ padx=24,
1839
+ pady=16,
1840
+ wraplength=460,
1841
+ )
1842
+ lbl.pack()
1843
+ overlay.place(relx=0.5, rely=0.5, anchor="center")
1844
+ self._loading_overlay = overlay
1845
+ self._loading_label = lbl
1846
+
1847
+ def _update_loading_overlay(self, text: str) -> None:
1848
+ """Atualiza o texto do banner de carregamento."""
1849
+ with contextlib.suppress(tk.TclError):
1850
+ if self._loading_label and self._loading_label.winfo_exists():
1851
+ self._loading_label.config(text=text)
1852
+
1853
+ def _hide_loading_overlay(self) -> None:
1854
+ """Remove o banner de carregamento."""
1855
+ with contextlib.suppress(tk.TclError):
1856
+ if self._loading_overlay and self._loading_overlay.winfo_exists():
1857
+ self._loading_overlay.place_forget()
1858
+ self._loading_overlay.destroy()
1859
+ self._loading_overlay = None
1860
+ self._loading_label = None
1861
+
1862
+ def _show_perf_banner(self, reason: str, n_lines: int) -> None:
1863
+ """Exibe faixa informativa quando features são reduzidas por arquivo denso.
1864
+
1865
+ Args:
1866
+ reason: Descrição curta do que foi desativado (ex: 'highlight parcial').
1867
+ n_lines: Número de linhas do arquivo atual.
1868
+ """
1869
+ self._hide_perf_banner()
1870
+ with contextlib.suppress(tk.TclError):
1871
+ t = self._tmgr.theme
1872
+ msg = (
1873
+ f"Arquivo com {n_lines:,} linhas - {reason} ativo. "
1874
+ "Lint e LSP operam sob demanda. "
1875
+ "[Limpar memória]"
1876
+ )
1877
+ self._perf_banner = tk.Label(
1878
+ self._editor_frame,
1879
+ text=msg,
1880
+ bg=getattr(t, "warn_bg", "#3a2a00"),
1881
+ fg=getattr(t, "warn_fg", "#ffd740"),
1882
+ font=(FONT_UI, 8),
1883
+ anchor="w",
1884
+ padx=8,
1885
+ cursor="hand2",
1886
+ )
1887
+ self._perf_banner.pack(side="bottom", fill="x")
1888
+ self._perf_banner.bind(
1889
+ "<Button-1>", lambda _e: self.purge_memory())
1890
+
1891
+ def _hide_perf_banner(self) -> None:
1892
+ """Remove o banner de performance se estiver visível."""
1893
+ with contextlib.suppress(tk.TclError):
1894
+ if self._perf_banner and self._perf_banner.winfo_exists():
1895
+ self._perf_banner.destroy()
1896
+ self._perf_banner = None
1897
+
1898
+ def purge_memory(self) -> None:
1899
+ """Libera a memória não essencial da aba atual.
1900
+
1901
+ Desliga o realce de sintaxe, remove as tags, zera o histórico de desfazer e
1902
+ os diagnósticos. O arquivo continua editável, mas sem realce até ser
1903
+ recarregado. Chamado pelo banner de performance e pelo menu.
1904
+ """
1905
+ import gc
1906
+
1907
+ from src import memtrim
1908
+
1909
+ self.hl.disable_large_file()
1910
+ with contextlib.suppress(tk.TclError):
1911
+ for tag in self.text.tag_names():
1912
+ if tag not in (
1913
+ "sel",
1914
+ "current_line",
1915
+ "bracket_match",
1916
+ "find_highlight",
1917
+ "find_current",
1918
+ ):
1919
+ self.text.tag_remove(tag, "1.0", "end")
1920
+ _OM_CACHE.clear()
1921
+ with contextlib.suppress(tk.TclError):
1922
+ self.text.edit_reset()
1923
+ self._diags.clear()
1924
+ self._kdocs.clear()
1925
+ self.gutter.set_lint_lines([])
1926
+ self.gutter.set_kdocs_lines([])
1927
+ gc.collect()
1928
+ memtrim.trim_allocator_async()
1929
+ self._hide_perf_banner()
1930
+
1931
+ with contextlib.suppress(tk.TclError):
1932
+ t = self._tmgr.theme
1933
+ lbl = tk.Label(
1934
+ self._editor_frame,
1935
+ text=_t("pane.memory_freed"),
1936
+ bg=getattr(t, "ok_bg", "#002200"),
1937
+ fg=getattr(t, "ok_fg", "#69ff47"),
1938
+ font=(FONT_UI, 8),
1939
+ anchor="w",
1940
+ padx=8,
1941
+ )
1942
+ lbl.pack(side="bottom", fill="x")
1943
+ self.after(4000, lambda: lbl.destroy()
1944
+ if lbl.winfo_exists() else None)
1945
+
1946
+ def _show_giant_status_label(self) -> None:
1947
+ """Cria a faixa de posição exibida em modo giant."""
1948
+ with contextlib.suppress(tk.TclError):
1949
+ if self._giant_status and self._giant_status.winfo_exists():
1950
+ self._giant_status.destroy()
1951
+ t = self._tmgr.theme
1952
+ self._giant_status = tk.Label(
1953
+ self._editor_frame,
1954
+ text="",
1955
+ bg=getattr(t, "activity_bg", t.editor_bg),
1956
+ fg=getattr(t, "fg_muted", t.fg),
1957
+ font=(FONT_UI, 8),
1958
+ anchor="w",
1959
+ padx=8,
1960
+ )
1961
+ self._giant_status.pack(side="bottom", fill="x")
1962
+
1963
+ def _update_giant_status(self) -> None:
1964
+ """Atualiza a faixa de posição com a linha atual no arquivo completo."""
1965
+ vfb = self._vfb
1966
+ if not self._is_giant_mode or vfb is None:
1967
+ return
1968
+ with contextlib.suppress(tk.TclError):
1969
+ if not vfb.is_ready:
1970
+ return
1971
+ total = vfb.total_lines
1972
+ start = self._viewport_start + 1
1973
+ end = min(self._viewport_start + self._window_len, total)
1974
+ edits = vfb.edit_count()
1975
+ edit_s = f" - {edits} linha(s) editada(s)" if edits else ""
1976
+ text = (
1977
+ f" 📄 Exibindo linhas {start:,}–{end:,} "
1978
+ f"de {total:,}{edit_s} "
1979
+ "[Modo Arquivo Gigante - scroll para navegar]"
1980
+ )
1981
+ if self._giant_status and self._giant_status.winfo_exists():
1982
+ self._giant_status.config(text=text)
1983
+
1984
+ def _show_large_file_notice(self) -> None:
1985
+ """Exibe brevemente uma mensagem sobre os recursos desativados."""
1986
+ if self._is_giant_mode:
1987
+ msg = (
1988
+ "Modo Arquivo Gigante ativo - viewport virtual. "
1989
+ "Scroll para navegar. Salvar funciona normalmente."
1990
+ )
1991
+ else:
1992
+ msg = "Modo Arquivo Grande - highlight, lint e autocomplete desativados para performance."
1993
+ self._show_context_info(msg)
1994
+
1995
+ def destroy(self) -> None:
1996
+ """Libera todos os recursos associados ao painel: bindings, after-jobs e overlays."""
1997
+
1998
+ for job_attr in (
1999
+ "_hover_job",
2000
+ "_hide_job",
2001
+ "_vp_shift_job",
2002
+ "_hl_scroll_job",
2003
+ "_kdocs_job",
2004
+ "_symbols_job",
2005
+ "_lsp_change_job",
2006
+ ):
2007
+ job_id = getattr(self, job_attr, None)
2008
+ if job_id:
2009
+ with contextlib.suppress(tk.TclError, ValueError):
2010
+ self.after_cancel(job_id)
2011
+ setattr(self, job_attr, None)
2012
+
2013
+ if hasattr(self, "line_numbers") and self.line_numbers:
2014
+ after_id = getattr(self.line_numbers, "_after_id", None)
2015
+ if after_id:
2016
+ with contextlib.suppress(tk.TclError, ValueError):
2017
+ self.line_numbers.after_cancel(after_id)
2018
+ self.line_numbers._after_id = None
2019
+
2020
+ if self.file_watcher is not None:
2021
+ self.file_watcher.stop()
2022
+ self.file_watcher = None
2023
+
2024
+ self._close_vfb()
2025
+
2026
+ if self._vp_shift_job:
2027
+ with contextlib.suppress(tk.TclError):
2028
+ self.after_cancel(self._vp_shift_job)
2029
+ self._vp_shift_job = None
2030
+
2031
+ with contextlib.suppress(tk.TclError):
2032
+ self._hide_loading_overlay()
2033
+ with contextlib.suppress(tk.TclError):
2034
+ self._hide_perf_banner()
2035
+ with contextlib.suppress(tk.TclError):
2036
+ if self._giant_status and self._giant_status.winfo_exists():
2037
+ self._giant_status.destroy()
2038
+ self._giant_status = None
2039
+
2040
+ if hasattr(self, "autocomplete"):
2041
+ with contextlib.suppress(tk.TclError):
2042
+ self.autocomplete.destroy()
2043
+ with contextlib.suppress(tk.TclError):
2044
+ self._hide_hover()
2045
+ with contextlib.suppress(tk.TclError):
2046
+ self._close_balloon()
2047
+
2048
+ with contextlib.suppress(tk.TclError):
2049
+ if self.sticky_scroll:
2050
+ self.sticky_scroll.destroy()
2051
+ with contextlib.suppress(tk.TclError):
2052
+ if self.code_folding:
2053
+ self.code_folding.destroy()
2054
+ with contextlib.suppress(tk.TclError):
2055
+ if self.inline_blame:
2056
+ self.inline_blame.destroy()
2057
+ with contextlib.suppress(tk.TclError):
2058
+ if self.color_preview:
2059
+ self.color_preview.destroy()
2060
+ with contextlib.suppress(tk.TclError):
2061
+ if self.inlay_hints:
2062
+ self.inlay_hints.destroy()
2063
+ with contextlib.suppress(tk.TclError):
2064
+ if self.complexity_lens:
2065
+ self.complexity_lens.destroy()
2066
+ with contextlib.suppress(tk.TclError):
2067
+ if self.focus_block:
2068
+ self.focus_block.destroy()
2069
+ with contextlib.suppress(tk.TclError):
2070
+ if self.sticky_notes:
2071
+ self.sticky_notes.destroy()
2072
+
2073
+ with contextlib.suppress(tk.TclError):
2074
+ self.text.config(state="normal")
2075
+ self.text.delete("1.0", "end")
2076
+ self.text.edit_reset()
2077
+
2078
+ with contextlib.suppress(Exception):
2079
+ _OM_CACHE.clear()
2080
+
2081
+ with contextlib.suppress(tk.TclError):
2082
+ super().destroy()