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/_app_editor.py ADDED
@@ -0,0 +1,1274 @@
1
+ """Mixin ``_AppEditorMixin`` - operações do editor de texto do Codis.
2
+
3
+ Gerencia abertura, salvamento, fechamento e ciclo de vida dos arquivos no editor,
4
+ bem como tabs, histórico recente e integração com o sistema de arquivos.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import logging
11
+ import tkinter as tk
12
+ from collections.abc import Callable
13
+ from pathlib import Path
14
+ from tkinter import filedialog, messagebox, ttk
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ from src.constants import EXT_LANG
18
+ from src.editor.multi_cursor import MultiCursorManager
19
+ from src.editor.pane import EditorPane
20
+ from src.fs_ops import remap_path
21
+ from src.i18n import _t
22
+ from src.theme.base import THEME_ORDER
23
+ from src.ui.code_runner import CodeRunnerDialog
24
+ from src.ui.key_remapper import KeyRemapperDialog, KeyRemapperManager
25
+ from src.ui.macro_recorder import MacroToolbar
26
+ from src.ui.project_templates import ProjectTemplateDialog
27
+ from src.ui.settings_window import SettingsWindow
28
+ from src.ui.workspace_switcher import WorkspaceSwitcherDialog
29
+ from src.ui.workspace_trust import WorkspaceTrust
30
+ from src.workspace_state import set_restricted
31
+
32
+ try:
33
+ from src.editor.smart_tips import SmartTips as _SmartTips
34
+
35
+ _SMART_TIPS_AVAILABLE = True
36
+ except ImportError:
37
+ _SmartTips = None # type: ignore[assignment,misc]
38
+ _SMART_TIPS_AVAILABLE = False
39
+
40
+ if TYPE_CHECKING:
41
+ pass
42
+
43
+ logger = logging.getLogger("Codis")
44
+
45
+ __all__ = ["_AppEditorMixin"]
46
+
47
+
48
+ def _widget_exists(widget: tk.Widget | None) -> bool:
49
+ """Retorna True se o widget Tkinter ainda existe e não foi destruído."""
50
+ if widget is None:
51
+ return False
52
+ try:
53
+ return bool(widget.winfo_exists())
54
+ except tk.TclError:
55
+ return False
56
+
57
+
58
+ class _AppEditorMixin:
59
+ """Mixin de Editor do CodisApp."""
60
+
61
+ def _clipboard_copy(self, _e: tk.Event) -> str | None:
62
+ """
63
+ Manipulador global de Ctrl+C.
64
+
65
+ Copia o texto selecionado no widget com foco ou, se nenhum widget de texto
66
+ tiver foco, delega ao editor ativo.
67
+ """
68
+ w = self._root.focus_get()
69
+ if isinstance(w, tk.Text):
70
+ with contextlib.suppress(tk.TclError):
71
+ sel = w.selection_get()
72
+ if sel:
73
+ self._record_clipboard(sel)
74
+ return None
75
+ if isinstance(w, (tk.Entry, ttk.Entry)):
76
+ with contextlib.suppress(tk.TclError):
77
+ sel = w.selection_get()
78
+ self._root.clipboard_clear()
79
+ self._root.clipboard_append(sel)
80
+ self._record_clipboard(sel)
81
+ return "break"
82
+
83
+ self._copy()
84
+ return "break"
85
+
86
+ def _clipboard_cut(self, _e: tk.Event) -> str | None:
87
+ """
88
+ Manipulador global de Ctrl+X.
89
+
90
+ Recorta o texto selecionado no widget com foco ou, se nenhum widget de texto
91
+ tiver foco, delega ao editor ativo.
92
+ """
93
+ w = self._root.focus_get()
94
+ if isinstance(w, tk.Text):
95
+ with contextlib.suppress(tk.TclError):
96
+ sel = w.selection_get()
97
+ if sel:
98
+ self._record_clipboard(sel)
99
+ return None
100
+ if isinstance(w, (tk.Entry, ttk.Entry)):
101
+ with contextlib.suppress(tk.TclError):
102
+ sel = w.selection_get()
103
+ self._root.clipboard_clear()
104
+ self._root.clipboard_append(sel)
105
+ self._record_clipboard(sel)
106
+ w.delete(tk.SEL_FIRST, tk.SEL_LAST)
107
+ return "break"
108
+ self._cut()
109
+ return "break"
110
+
111
+ def _clipboard_paste(self, _e: tk.Event) -> str | None:
112
+ """
113
+ Manipulador global de Ctrl+V.
114
+
115
+ Cola o conteúdo da área de transferência no widget com foco ou,
116
+ se nenhum widget de texto tiver foco, delega ao editor ativo.
117
+ """
118
+ w = self._root.focus_get()
119
+ if isinstance(w, tk.Text):
120
+ return None
121
+ if isinstance(w, (tk.Entry, ttk.Entry)):
122
+ with contextlib.suppress(tk.TclError):
123
+ text = self._root.clipboard_get()
124
+ w.insert(tk.INSERT, text)
125
+ return "break"
126
+ self._paste()
127
+ return "break"
128
+
129
+ def _setup_key_manager(self) -> None:
130
+ """Inicializa o KeyRemapperManager e registra todos os handlers de comando."""
131
+ self._key_mgr = KeyRemapperManager(self._root, self._key_store)
132
+
133
+ handlers: dict[str, Any] = {
134
+ "file.new": self.new_file,
135
+ "file.open": self.open_file_dialog,
136
+ "file.save": self.save_file,
137
+ "file.save_as": self.save_as,
138
+ "file.save_all": self.save_all,
139
+ "file.close_tab": self._close_active_tab,
140
+ "file.exit": self._on_exit,
141
+ "edit.undo": self._undo,
142
+ "edit.redo": self._redo,
143
+ "edit.cut": self._cut,
144
+ "edit.copy": self._copy,
145
+ "edit.paste": self._paste,
146
+ "edit.select_all": self._select_all,
147
+ "edit.find": self._show_find,
148
+ "edit.replace": self._show_replace,
149
+ "edit.find_files": self._show_find_files,
150
+ "edit.comment": self._toggle_comment,
151
+ "edit.duplicate": self._duplicate_line,
152
+ "edit.delete_line": self._delete_line,
153
+ "edit.move_up": self._move_line_up,
154
+ "edit.move_down": self._move_line_down,
155
+ "edit.paste_history": self._paste_history_dialog,
156
+ "view.command_palette": self._command_palette,
157
+ "view.quick_open": self._quick_open,
158
+ "view.terminal": lambda: self._show_panel("terminal"),
159
+ "view.problems": lambda: self._show_panel("problems"),
160
+ "view.zoom_in": lambda: self._zoom(+1),
161
+ "view.zoom_out": lambda: self._zoom(-1),
162
+ "view.zoom_reset": lambda: self._zoom(0),
163
+ "view.fullscreen": self._toggle_fullscreen,
164
+ "view.split": self._split_editor,
165
+ "view.settings": lambda: self._activity("settings"),
166
+ "view.color_picker": self._open_color_picker,
167
+ "view.regex": lambda: self._show_panel("regex"),
168
+ "view.ia": lambda: self._activity("ia"),
169
+ "view.scratchpad": lambda: self._activity("scratchpad"),
170
+ "view.snippets": lambda: self._activity("snippets"),
171
+ "go.line": self._goto_line,
172
+ "go.next_tab": self._next_tab,
173
+ "go.prev_tab": self._prev_tab,
174
+ "go.next_problem": self._next_problem,
175
+ "go.prev_problem": self._prev_problem,
176
+ "run.run_file": self._run_file,
177
+ "run.format": self._format_document,
178
+ "tools.bookmark_add": self._add_bookmark,
179
+ "tools.bookmark_next": self._next_bookmark,
180
+ "tools.zen_mode": self._toggle_zen_mode,
181
+ "tools.vim_mode": self._toggle_vim_mode,
182
+ "tools.kui": self._toggle_kui,
183
+ "tools.pomodoro": lambda: self._activity("pomodoro"),
184
+ "tools.macro": self._open_macro_toolbar,
185
+ "tools.multi_cursor": self._toggle_multi_cursor,
186
+ "tools.template": self._open_project_template,
187
+ }
188
+
189
+ for bid, handler in handlers.items():
190
+ self._key_mgr.register(bid, handler)
191
+
192
+ self._key_mgr.apply_all()
193
+
194
+ def _open_key_remapper(self) -> None:
195
+ """Abre o diálogo de remapeamento de atalhos de teclado."""
196
+
197
+ def _on_apply() -> None:
198
+ if self._key_mgr:
199
+ self._key_mgr.apply_all()
200
+ self._status.notify(_t("keyremap.applied"), level="ok")
201
+
202
+ KeyRemapperDialog(self._root, self._tmgr, self._key_store, _on_apply)
203
+
204
+ def _open_workspace_switcher(self) -> None:
205
+ """Abre o Workspace Switcher para trocar rapidamente de projeto."""
206
+ recent_folders = [Path(str(p))
207
+ for p in self._cfg.get("recent_folders", [])]
208
+ if not recent_folders:
209
+ self._status.notify(_t("ws.no_recent"), level="info")
210
+ return
211
+
212
+ def _on_open(path: Path) -> None:
213
+ self._set_workspace(path)
214
+
215
+ def _on_remove(path: Path) -> None:
216
+ folders = self._cfg.get("recent_folders", [])
217
+ folders = [f for f in folders if str(f) != str(path)]
218
+ self._cfg.set("recent_folders", folders)
219
+ self._cfg.save()
220
+
221
+ WorkspaceSwitcherDialog(
222
+ self._root,
223
+ self._tmgr,
224
+ recent_folders,
225
+ on_open=_on_open,
226
+ on_remove=_on_remove,
227
+ on_browse=self.open_folder_dialog,
228
+ )
229
+
230
+ def _open_code_runner_config(self) -> None:
231
+ """Abre o diálogo de configuração dos Code Runners."""
232
+ CodeRunnerDialog(
233
+ self._root,
234
+ self._tmgr,
235
+ self._runner_store,
236
+ on_change=lambda: self._status.notify(
237
+ _t("runner.updated"), level="ok"),
238
+ )
239
+
240
+ def _open_macro_toolbar(self) -> None:
241
+ """Abre o Macro Recorder (toolbar flutuante)."""
242
+ if self._macro_toolbar and self._macro_toolbar.winfo_exists():
243
+ self._macro_toolbar.lift()
244
+ return
245
+
246
+ def _get_text() -> tk.Text | None:
247
+ e = self._e()
248
+ return e.text if e else None
249
+
250
+ self._macro_toolbar = MacroToolbar(
251
+ self._root,
252
+ self._tmgr,
253
+ self._macro_recorder,
254
+ self._macro_store,
255
+ _get_text,
256
+ )
257
+
258
+ def _open_project_template(self) -> None:
259
+ """Abre o diálogo de criação de projeto a partir de template."""
260
+ ProjectTemplateDialog(
261
+ self._root,
262
+ self._tmgr,
263
+ self._template_store,
264
+ on_open=self._set_workspace,
265
+ cfg=self._cfg,
266
+ )
267
+
268
+ def _toggle_multi_cursor(self) -> None:
269
+ """Liga/desliga o Multi-Cursor no editor ativo."""
270
+ e = self._e()
271
+ if not e:
272
+ return
273
+ text = e.text
274
+ if (
275
+ self._multi_cursor
276
+ and self._multi_cursor._text is text
277
+ and self._multi_cursor._active
278
+ ):
279
+ self._multi_cursor.deactivate()
280
+ self._multi_cursor = None
281
+ self._status.notify(_t("mc.status_inactive"), level="info")
282
+ else:
283
+ if self._multi_cursor:
284
+ self._multi_cursor.deactivate()
285
+ self._multi_cursor = MultiCursorManager(text)
286
+ self._multi_cursor.activate()
287
+ self._status.notify(
288
+ _t("mc.status_active"),
289
+ level="ok",
290
+ )
291
+
292
+ def _bind_key(self, key: str, cmd_id: str, when: Callable[[], bool] | None = None) -> None:
293
+ """Vincula ``key`` ao comando ``cmd_id`` (usado pela API de plugins).
294
+
295
+ Um único tratador por sequência consulta a tabela de atalhos; assim o vínculo
296
+ não sobrescreve outros e pode ser desfeito sem mexer no Tk.
297
+ """
298
+ self._plugin_keymap.setdefault(key, []).append((cmd_id, when))
299
+ if key not in self._plugin_key_bound:
300
+ self._plugin_key_bound.add(key)
301
+ with contextlib.suppress(tk.TclError):
302
+ self._root.bind(key, lambda _e, k=key: self._dispatch_plugin_key(k), add="+")
303
+
304
+ def _unbind_key(self, key: str, cmd_id: str) -> None:
305
+ """Desfaz um vínculo criado por :meth:`_bind_key`."""
306
+ entries = self._plugin_keymap.get(key, [])
307
+ self._plugin_keymap[key] = [item for item in entries if item[0] != cmd_id]
308
+
309
+ def _dispatch_plugin_key(self, key: str) -> str | None:
310
+ """Executa o comando mais recente vinculado a ``key`` cujo ``when`` permite."""
311
+ for cmd_id, when in reversed(self._plugin_keymap.get(key, [])):
312
+ if when is not None:
313
+ try:
314
+ if not when():
315
+ continue
316
+ except Exception:
317
+ continue
318
+ info = self._commands.get(cmd_id)
319
+ if info is None or not info.available():
320
+ continue
321
+ self._commands.run(cmd_id)
322
+ return "break"
323
+ return None
324
+
325
+ def _show_settings(self) -> None:
326
+ """Abre a janela flutuante de configurações."""
327
+ win = SettingsWindow(
328
+ self._root,
329
+ self._tmgr,
330
+ self._cfg,
331
+ on_change=self._on_setting_change,
332
+ on_show_settings_panel=self._show_settings_panel,
333
+ )
334
+ win._app_ref = self
335
+
336
+ def _on_activity(self, key: str) -> None:
337
+ """Chamado quando um botão da barra de atividades é clicado."""
338
+ if key == "theme":
339
+ if not THEME_ORDER:
340
+ return
341
+ try:
342
+ idx = THEME_ORDER.index(self._tmgr.theme.name)
343
+ except ValueError:
344
+ idx = -1
345
+ next_name = THEME_ORDER[(idx + 1) % len(THEME_ORDER)]
346
+ self._set_theme(next_name)
347
+ return
348
+ if key == "settings":
349
+ self._show_settings()
350
+ return
351
+
352
+ if key == "remote_ssh":
353
+ self._open_remote_ssh()
354
+ return
355
+
356
+ if key == "chat":
357
+ self._open_chat()
358
+ return
359
+
360
+ if key == "accessibility":
361
+ self._open_accessibility()
362
+ return
363
+
364
+ if key == "collab":
365
+ self._open_collab()
366
+ return
367
+
368
+ if key == "time_tracker":
369
+ self._open_time_tracker()
370
+ return
371
+
372
+ if key == "dep_graph":
373
+ self._open_dependency_graph()
374
+ return
375
+
376
+ if key == "terminal":
377
+ self._show_panel("terminal")
378
+ return
379
+ if key == "run":
380
+ self._show_panel("debug")
381
+ return
382
+
383
+ if key == self._current_sidebar and self._sidebar_visible:
384
+ self._toggle_sidebar()
385
+ return
386
+ self._current_sidebar = key
387
+ if not self._sidebar_visible:
388
+ self._show_sidebar()
389
+
390
+ panel_map: dict[str, tk.Widget | None] = {
391
+ "explorer": (
392
+ self._sidebar_placeholder
393
+ if self._workspace is None
394
+ else self._file_tree
395
+ ),
396
+ "search": self._find_files,
397
+ "git": self._git_sidebar,
398
+ "extensions": self._plugin_panel,
399
+ "settings": self._settings_editor,
400
+ "outline": self._code_outline,
401
+ "bookmarks": self._bookmarks_panel,
402
+ "scratchpad": self._scratchpad_pane,
403
+ "snippets": self._snippets_panel,
404
+ "docs": self._docs_panel,
405
+ "codestats": self._code_stats_panel,
406
+ "todo": self._todo_panel,
407
+ "restclient": self._rest_client_panel,
408
+ "preview": self._render_panel,
409
+ "pomodoro": self._pomodoro_panel,
410
+ "flowchart": self._flowchart_panel,
411
+ "problems": self._sidebar_problems,
412
+ "ia": getattr(self, "_painel_ia", None),
413
+ "sql": getattr(self, "_sql_studio_panel", None),
414
+ "terminal": None,
415
+ "run": None,
416
+ }
417
+
418
+ if hasattr(self, "_plugin_panels"):
419
+ panel_map.update(self._plugin_panels)
420
+
421
+ for w in self._sidebar_stack.winfo_children():
422
+ w.pack_forget()
423
+
424
+ panel = panel_map.get(key)
425
+ if panel is not None:
426
+ panel.pack(fill="both", expand=True)
427
+ elif key == "terminal":
428
+ self._show_panel("terminal")
429
+ elif key == "run":
430
+ self._show_panel("debug")
431
+
432
+ def _activity(self, key: str) -> None:
433
+ """Ativa programaticamente um item da barra de atividades."""
434
+ self._actbar._activate(key)
435
+
436
+ def _toggle_sidebar(self) -> None:
437
+ """Alterna a visibilidade da barra lateral."""
438
+ if self._sidebar_visible:
439
+ self._hide_sidebar()
440
+ else:
441
+ self._show_sidebar()
442
+
443
+ def _animate_sidebar(self, target_x: int, on_done: Callable[[], None]) -> None:
444
+ """Move o sash da sidebar até ``target_x`` com ease-out (~90 ms).
445
+
446
+ Respeita ``a11y_reduce_motion``: nesse caso aplica o destino direto.
447
+ """
448
+ job = getattr(self, "_sidebar_anim_job", None)
449
+ if job is not None:
450
+ with contextlib.suppress(tk.TclError):
451
+ self._root.after_cancel(job)
452
+ self._sidebar_anim_job = None
453
+
454
+ try:
455
+ start_x = int(self._h_paned.sash_coord(1)[0])
456
+ except (tk.TclError, IndexError):
457
+ start_x = target_x
458
+ steps = 6
459
+ if self._cfg.get("a11y_reduce_motion", False) or start_x == target_x:
460
+ steps = 1
461
+
462
+ def _step(i: int) -> None:
463
+ progress = i / steps
464
+ eased = 1 - (1 - progress) ** 3
465
+ x = round(start_x + (target_x - start_x) * eased)
466
+ with contextlib.suppress(tk.TclError):
467
+ self._h_paned.sash_place(1, x, 0)
468
+ if i < steps:
469
+ self._sidebar_anim_job = self._root.after(15, _step, i + 1)
470
+ else:
471
+ self._sidebar_anim_job = None
472
+ on_done()
473
+
474
+ _step(1)
475
+
476
+ def _show_sidebar(self) -> None:
477
+ """Exibe a barra lateral (com transição suave)."""
478
+ dock = getattr(self, "_dock", None)
479
+ if dock is not None and dock.floating:
480
+ self._sidebar_visible = True
481
+ self._update_panel_toggle_arrows()
482
+ dock.show()
483
+ return
484
+ w = max(60, self._cfg.get("sidebar_width", 220))
485
+ self._sidebar_visible = True
486
+ self._update_panel_toggle_arrows()
487
+
488
+ with contextlib.suppress(tk.TclError):
489
+ self._h_paned.paneconfigure(self._sidebar, minsize=60)
490
+
491
+ def _settle() -> None:
492
+ with contextlib.suppress(tk.TclError):
493
+ self._h_paned.paneconfigure(self._sidebar, minsize=60, width=w)
494
+ self._h_paned.sash_place(1, 48 + w, 0)
495
+
496
+ self._root.update_idletasks()
497
+ self._animate_sidebar(48 + w, _settle)
498
+
499
+ def _hide_sidebar(self) -> None:
500
+ """Oculta a barra lateral (com transição suave)."""
501
+ dock = getattr(self, "_dock", None)
502
+ if dock is not None and dock.floating:
503
+ self._sidebar_visible = False
504
+ self._update_panel_toggle_arrows()
505
+ dock.hide()
506
+ return
507
+ self._sidebar_visible = False
508
+ self._update_panel_toggle_arrows()
509
+
510
+ def _settle() -> None:
511
+ with contextlib.suppress(tk.TclError):
512
+ self._h_paned.paneconfigure(self._sidebar, minsize=0, width=0)
513
+ self._h_paned.sash_place(1, 48, 0)
514
+
515
+ self._root.update_idletasks()
516
+ with contextlib.suppress(tk.TclError):
517
+ self._h_paned.paneconfigure(self._sidebar, minsize=0)
518
+ self._animate_sidebar(48, _settle)
519
+
520
+ def _register_plugin_panel(
521
+ self, panel_id: str, icon: str, factory: Callable, tooltip: str
522
+ ) -> None:
523
+ """Registra um painel de plugin na barra de atividades e na sidebar."""
524
+ with contextlib.suppress(tk.TclError):
525
+ widget = factory(self._sidebar_stack)
526
+
527
+ self._actbar.add_plugin_item(panel_id, icon, tooltip or panel_id)
528
+
529
+ if not hasattr(self, "_plugin_panels"):
530
+ self._plugin_panels: dict[str, tk.Widget] = {}
531
+ self._plugin_panels[panel_id] = widget
532
+
533
+ def _unregister_plugin_panel(self, panel_id: str) -> None:
534
+ """Remove o painel de um plugin da barra de atividades e da sidebar."""
535
+ widget = getattr(self, "_plugin_panels", {}).pop(panel_id, None)
536
+ with contextlib.suppress(tk.TclError, AttributeError):
537
+ self._actbar.remove_plugin_item(panel_id)
538
+ if widget is not None:
539
+ with contextlib.suppress(tk.TclError):
540
+ widget.destroy()
541
+
542
+ def _active_editor(self) -> EditorPane | None:
543
+ """Alias estável de ``_e()`` exposto como callable para componentes externos.
544
+
545
+ Usado por SearchBar, IA, plugins e outros que recebem ``get_editor=``
546
+ como parâmetro de construção. Não remover - é a API pública interna.
547
+ """
548
+ return self._e()
549
+
550
+ def _select_tab(self, idx: int) -> None:
551
+ """Seleciona a aba de índice `idx`, tornando seu editor visível."""
552
+ if idx < 0 or idx >= len(self._editors):
553
+ return
554
+ same = idx == self._active_idx
555
+ if not same and 0 <= self._active_idx < len(self._editors):
556
+ with contextlib.suppress(tk.TclError):
557
+ self._editors[self._active_idx].pack_forget()
558
+ with contextlib.suppress(tk.TclError):
559
+ if self._welcome.winfo_ismapped():
560
+ self._welcome.pack_forget()
561
+
562
+ if self._kui and getattr(self._kui, "_enabled", False):
563
+ with contextlib.suppress(tk.TclError):
564
+ self._kui.hide_welcome()
565
+ self._kui.ensure_editor_visible()
566
+
567
+ self._active_idx = idx
568
+ e = self._editors[idx]
569
+ self._active_pane = e
570
+ if not same:
571
+ dual_mode = getattr(self, "_dual_mode", False)
572
+ dual_container = getattr(self, "_dual_left_container", None)
573
+ dual_ok = (
574
+ dual_mode
575
+ and dual_container is not None
576
+ and _widget_exists(dual_container)
577
+ )
578
+ editor_ok = _widget_exists(e)
579
+ if not editor_ok:
580
+ container = dual_container if dual_ok else self._editor_container
581
+ new_e = EditorPane(
582
+ container,
583
+ self._tmgr,
584
+ self._cfg,
585
+ self._lint_mgr,
586
+ self._snippets,
587
+ on_change=self._on_editor_change,
588
+ on_cursor=self._on_cursor_change,
589
+ on_title=self._on_editor_title,
590
+ idx=idx,
591
+ )
592
+ if self._lsp_mgr:
593
+ new_e.set_lsp_manager(self._lsp_mgr)
594
+ new_e.set_goto_callback(self._open_file_at_line)
595
+ new_e.set_workspace_edit_callback(self._apply_edits_to_path)
596
+ self._wire_breakpoint_sync(new_e)
597
+ old_path = getattr(e, "path", None)
598
+ if old_path:
599
+ new_e.load(old_path)
600
+ self._editors[idx] = new_e
601
+ self._active_pane = new_e
602
+ e = new_e
603
+ editor_ok = True
604
+ if editor_ok:
605
+ if dual_ok:
606
+ with contextlib.suppress(tk.TclError):
607
+ e.pack(fill="both", expand=True, in_=dual_container)
608
+ else:
609
+ with contextlib.suppress(tk.TclError):
610
+ e.pack(fill="both", expand=True,
611
+ in_=self._editor_container)
612
+ self._tabbar.set_active(idx)
613
+ with contextlib.suppress(tk.TclError):
614
+ e.text.focus_set()
615
+ self._update_breadcrumb()
616
+ self._update_title()
617
+ if e.lang == "text" and e.path:
618
+ from src.constants import EXT_LANG
619
+
620
+ inferred = EXT_LANG.get(e.path.suffix.lower(), "text")
621
+ if inferred != "text":
622
+ e.lang = inferred
623
+ with contextlib.suppress(Exception):
624
+ e.hl.set_lang(inferred)
625
+ self._status.set_lang(e.lang)
626
+ self._status.set_encoding(e.encoding)
627
+ self._status.set_eol(e.eol)
628
+ if e._diags:
629
+ self._status.set_diags(e._diags)
630
+
631
+ if not same and hasattr(self, "_search_bar"):
632
+ with contextlib.suppress(tk.TclError):
633
+ self._search_bar.notify_editor_change()
634
+
635
+ if e.path:
636
+ self._lint_mgr.schedule(e.path, e.get_content(), e.lang)
637
+
638
+ self._fire_hook("tab_change", idx)
639
+
640
+ self._notify_active_panels(e)
641
+ self._refresh_debug_breakpoints()
642
+
643
+ if self._kui:
644
+ with contextlib.suppress(tk.TclError):
645
+ open_paths = [str(ed.path) for ed in self._editors if ed.path]
646
+ self._kui.notify_open_files(open_paths)
647
+
648
+ with contextlib.suppress(tk.TclError):
649
+ self._snippets_panel.notify_active_lang(e.lang)
650
+
651
+ with contextlib.suppress(tk.TclError):
652
+ if self._vim_enabled and (
653
+ self._vim_mode is None or self._vim_mode.editor_pane is not e
654
+ ):
655
+ if self._vim_mode is not None:
656
+ self._vim_mode.disable()
657
+ self._vim_mode = None
658
+ self._enable_vim_mode()
659
+
660
+ def _notify_active_panels(self, e: EditorPane) -> None:
661
+ """Notifica todos os painéis registrados sobre a mudança de editor ativo."""
662
+ path = e.path if (e and e.path) else None
663
+ path_str = str(path) if path else None
664
+ with contextlib.suppress(tk.TclError):
665
+ self._render_panel.notify_active_file(path)
666
+ with contextlib.suppress(Exception):
667
+ self._web_preview_follow(path)
668
+ with contextlib.suppress(tk.TclError):
669
+ self._flowchart_panel.notify_active_file(path_str)
670
+ with contextlib.suppress(tk.TclError):
671
+ if hasattr(self, "_pomodoro_panel"):
672
+ pass
673
+
674
+ with contextlib.suppress(tk.TclError):
675
+ if hasattr(self, "_code_outline") and e:
676
+ self._code_outline.refresh()
677
+ with contextlib.suppress(tk.TclError):
678
+ if self._current_sidebar == "docs":
679
+ self._docs_panel.refresh()
680
+
681
+ with contextlib.suppress(Exception):
682
+ if hasattr(self, "_tracker_model") and path_str:
683
+ ws = str(self._workspace) if self._workspace else None
684
+ self._tracker_model.on_activity(path_str, ws)
685
+
686
+ if _SMART_TIPS_AVAILABLE and e and e.path:
687
+ with contextlib.suppress(Exception):
688
+ if self._smart_tips is None:
689
+ self._smart_tips = _SmartTips(
690
+ e.text, self._cfg, self._tmgr)
691
+ else:
692
+ self._smart_tips._widget = e.text
693
+ self._smart_tips._cfg = self._cfg
694
+ self._smart_tips._tmgr = self._tmgr
695
+ interval_sec = self._cfg.get("smart_tips_interval", 30)
696
+ self._smart_tips._min_interval_ms = int(interval_sec) * 1000
697
+ self._smart_tips.analyse(
698
+ e.get_content(), e.lang, e.path, delay_ms=1500)
699
+
700
+ def _close_tab(self, idx: int) -> bool:
701
+ """Fecha a aba de índice `idx`, perguntando para salvar se necessário.
702
+
703
+ Devolve ``False`` se a aba continuou aberta (o usuário cancelou ou o salvamento
704
+ falhou), para que quem fecha várias abas pare em vez de insistir.
705
+ """
706
+ if idx < 0 or idx >= len(self._editors):
707
+ return False
708
+ e = self._editors[idx]
709
+ if e.modified:
710
+ name = e.path.name if e.path else _t("ui.tab_untitled")
711
+ ans = messagebox.askyesnocancel(
712
+ _t("file.save"),
713
+ _t("ui.confirm_close") + f"\n\n{name}",
714
+ parent=self._root,
715
+ )
716
+ if ans is None:
717
+ return False
718
+ if ans and not e.save():
719
+ return False
720
+
721
+ self._fire_hook("file_close", e.path)
722
+ closed_path = str(e.path) if e.path else ""
723
+
724
+ if e.path and hasattr(self, "_lsp_mgr") and self._lsp_mgr:
725
+ with contextlib.suppress(Exception):
726
+ self._lsp_mgr.did_close(e.path, getattr(e, "lang", ""))
727
+
728
+ e.pack_forget()
729
+ with contextlib.suppress(Exception):
730
+ e.destroy()
731
+ self._editors.pop(idx)
732
+ self._tabbar.remove_tab(idx)
733
+
734
+ if closed_path:
735
+ self._closed_tabs.append(closed_path)
736
+ del self._closed_tabs[:-20]
737
+ self._schedule_gc()
738
+
739
+ if closed_path:
740
+ self._problems_panel.clear_file_diags(closed_path)
741
+ with contextlib.suppress(tk.TclError):
742
+ self._sidebar_problems.clear_file_diags(closed_path)
743
+
744
+ open_paths = [str(ed.path) for ed in self._editors if ed.path]
745
+ self._problems_panel.set_open_files(open_paths)
746
+ with contextlib.suppress(tk.TclError):
747
+ self._sidebar_problems.set_open_files(open_paths)
748
+ if self._kui:
749
+ with contextlib.suppress(tk.TclError):
750
+ self._kui.notify_open_files(open_paths)
751
+
752
+ if not self._editors:
753
+ self._active_idx = -1
754
+ self._active_pane = None
755
+ self._present_start_screen()
756
+ self._update_title()
757
+ self._status.set_lang("text")
758
+ with contextlib.suppress(tk.TclError):
759
+ self._breadcrumb.set_path(None)
760
+ return True
761
+
762
+ new_idx = min(idx, len(self._editors) - 1)
763
+ self._active_idx = -1
764
+ self._select_tab(new_idx)
765
+ return True
766
+
767
+ def _on_tree_path_renamed(self, old: Path, new: Path) -> None:
768
+ """Um arquivo ou pasta foi renomeado/movido no explorador: ajusta as abas abertas.
769
+
770
+ Sem isso, a aba continuaria apontando para o caminho antigo e o próximo salvamento
771
+ recriaria o arquivo velho ao lado do renomeado.
772
+ """
773
+ for idx, editor in enumerate(self._editors):
774
+ if not editor.path:
775
+ continue
776
+ mapped = remap_path(editor.path, old, new)
777
+ if mapped is None:
778
+ continue
779
+ with contextlib.suppress(Exception):
780
+ editor.set_path(mapped)
781
+ with contextlib.suppress(Exception):
782
+ self._tabbar.update_tab(idx, mapped.name, editor.modified)
783
+ with contextlib.suppress(Exception):
784
+ self._update_title()
785
+
786
+ def _close_active_tab(self) -> None:
787
+ """Fecha a aba ativa."""
788
+ if self._active_idx >= 0:
789
+ self._close_tab(self._active_idx)
790
+
791
+ def _close_all_tabs(self) -> None:
792
+ """Fecha todas as abas abertas."""
793
+ while self._editors:
794
+ if not self._close_tab(0):
795
+ break
796
+
797
+ def _schedule_gc(self, delay_ms: int = 400) -> None:
798
+ """Agenda um ``gc.collect()`` fora do caminho crítico da interface.
799
+
800
+ Fechar várias abas em sequência dispara apenas uma coleta, evitando
801
+ pausas perceptíveis (50-200 ms) a cada fechamento.
802
+ """
803
+ if self._gc_job is not None:
804
+ with contextlib.suppress(tk.TclError):
805
+ self._root.after_cancel(self._gc_job)
806
+
807
+ def _run() -> None:
808
+ import gc
809
+
810
+ from src import memtrim
811
+
812
+ self._gc_job = None
813
+ gc.collect()
814
+ memtrim.trim_allocator_async()
815
+
816
+ self._gc_job = self._root.after(delay_ms, _run)
817
+
818
+ def _goto_tab_number(self, number: int) -> None:
819
+ """Vai para a aba ``number`` (1-8); 9 sempre seleciona a última aba."""
820
+ if not self._editors:
821
+ return
822
+ idx = len(self._editors) - 1 if number >= 9 else number - 1
823
+ self._select_tab(idx)
824
+
825
+ def _reopen_closed_tab(self) -> None:
826
+ """Reabre o último arquivo fechado que ainda existe no disco."""
827
+ while self._closed_tabs:
828
+ path = Path(self._closed_tabs.pop())
829
+ if not path.is_file():
830
+ continue
831
+ existing = self._find_editor_for_path(path)
832
+ if existing is not None:
833
+ self._select_tab(existing)
834
+ else:
835
+ self.open_file(path)
836
+ return
837
+
838
+ def _next_tab(self) -> None:
839
+ """Ativa a próxima aba (direita)."""
840
+ if self._editors:
841
+ self._select_tab((self._active_idx + 1) % len(self._editors))
842
+
843
+ def _prev_tab(self) -> None:
844
+ """Ativa a aba anterior (esquerda)."""
845
+ if self._editors:
846
+ self._select_tab((self._active_idx - 1) % len(self._editors))
847
+
848
+ def _find_editor_for_path(self, path: Path) -> int | None:
849
+ """Retorna o índice do editor que contém o arquivo `path`, se existir."""
850
+ for i, e in enumerate(self._editors):
851
+ if e.path and e.path.resolve() == path.resolve():
852
+ return i
853
+ return None
854
+
855
+ def _show_file_diff_with_content(
856
+ self, original: str, modified: str, orig_name: str, mod_name: str
857
+ ) -> None:
858
+ """Exibe o diff entre dois conteúdos no painel de diff."""
859
+ self._diff_pane.show(
860
+ original or "", modified or "", orig_name, mod_name)
861
+ self._show_panel("diff")
862
+
863
+ def new_file(self) -> EditorPane:
864
+ """Cria um novo arquivo (aba em branco)."""
865
+ return self._create_editor()
866
+
867
+ def _create_tab_with_text(self, text: str) -> None:
868
+ """Cria nova aba com conteúdo de texto pré-preenchido (usado pela IA)."""
869
+ editor = self._create_editor()
870
+ with contextlib.suppress(tk.TclError):
871
+ editor.text.insert("1.0", text)
872
+
873
+ def _create_editor(self, path: Path | None = None) -> EditorPane:
874
+ """
875
+ Cria um novo editor (aba) e o adiciona à lista.
876
+
877
+ Se `path` for fornecido, tenta carregar o arquivo.
878
+ Retorna o editor criado.
879
+ """
880
+ if path:
881
+ existing = self._find_editor_for_path(path)
882
+ if existing is not None:
883
+ self._select_tab(existing)
884
+ return self._editors[existing]
885
+
886
+ e = EditorPane(
887
+ self._editor_container,
888
+ self._tmgr,
889
+ self._cfg,
890
+ self._lint_mgr,
891
+ self._snippets,
892
+ on_change=self._on_editor_change,
893
+ on_cursor=self._on_cursor_change,
894
+ on_title=self._on_editor_title,
895
+ on_copy=self._on_copy_event,
896
+ idx=len(self._editors),
897
+ )
898
+
899
+ if self._lsp_mgr:
900
+ e.set_lsp_manager(self._lsp_mgr)
901
+ e.set_goto_callback(self._open_file_at_line)
902
+ e.set_workspace_edit_callback(self._apply_edits_to_path)
903
+ self._wire_breakpoint_sync(e)
904
+ self._editors.append(e)
905
+ tab_idx = len(self._editors) - 1
906
+ title = path.name if path else _t("ui.tab_untitled")
907
+ self._tabbar.add_tab(title, path)
908
+
909
+ if self._kui:
910
+ with contextlib.suppress(tk.TclError):
911
+ open_paths = [str(ed.path) for ed in self._editors if ed.path]
912
+ self._kui.notify_open_files(open_paths)
913
+
914
+ if self._welcome.winfo_ismapped():
915
+ self._welcome.pack_forget()
916
+
917
+ if self._kui and getattr(self._kui, "_enabled", False):
918
+ with contextlib.suppress(tk.TclError):
919
+ self._kui.hide_welcome()
920
+ self._kui.ensure_editor_visible()
921
+ if 0 <= self._active_idx < len(self._editors) - 1:
922
+ self._editors[self._active_idx].pack_forget()
923
+
924
+ self._active_idx = tab_idx
925
+ self._active_pane = e
926
+ _dual_mode = getattr(self, "_dual_mode", False)
927
+ _dual_c = getattr(self, "_dual_left_container", None)
928
+ if _dual_mode and _widget_exists(_dual_c):
929
+ with contextlib.suppress(tk.TclError):
930
+ e.pack(fill="both", expand=True, in_=_dual_c)
931
+ else:
932
+ with contextlib.suppress(tk.TclError):
933
+ e.pack(fill="both", expand=True, in_=self._editor_container)
934
+ self._tabbar.set_active(tab_idx)
935
+ with contextlib.suppress(tk.TclError):
936
+ e.text.focus_set()
937
+ self._refresh_debug_breakpoints()
938
+ return e
939
+
940
+ def _wire_breakpoint_sync(self, editor: EditorPane) -> None:
941
+ """Conecta o gutter de um editor ao painel de debug.
942
+
943
+ Sempre que um breakpoint é adicionado/removido clicando no gutter,
944
+ a lista é empurrada para ``DebugPanel.set_breakpoints`` - que, por
945
+ sua vez, repassa ao vivo a uma sessão DAP ativa para o mesmo
946
+ arquivo, se houver. Sem esta conexão, breakpoints marcados na UI
947
+ nunca chegavam ao depurador de fato.
948
+ """
949
+ debug_panel = getattr(self, "_debug_panel", None)
950
+ if debug_panel is None:
951
+ return
952
+
953
+ def _on_toggle(lines: set[int], ed: EditorPane = editor) -> None:
954
+ if ed is not self._active_editor():
955
+ return
956
+ path_str = str(ed.path) if ed.path else ""
957
+ with contextlib.suppress(Exception):
958
+ debug_panel.set_breakpoints(sorted(lines), path_str)
959
+
960
+ with contextlib.suppress(Exception):
961
+ editor.gutter.set_on_breakpoint_toggle(_on_toggle)
962
+
963
+ def _refresh_debug_breakpoints(self) -> None:
964
+ """Reenvia ao painel de debug os breakpoints do editor ativo.
965
+
966
+ Chamado ao trocar de aba/editor para que o painel sempre reflita
967
+ os breakpoints do arquivo atualmente em foco, e não os da aba
968
+ anterior.
969
+ """
970
+ debug_panel = getattr(self, "_debug_panel", None)
971
+ editor = self._active_editor()
972
+ if debug_panel is None or editor is None:
973
+ return
974
+ with contextlib.suppress(Exception):
975
+ lines = sorted(editor.gutter.get_breakpoints())
976
+ path_str = str(editor.path) if editor.path else ""
977
+ debug_panel.set_breakpoints(lines, path_str)
978
+
979
+ def _open_file(self, path_or_str: Any, *, adopt_workspace: bool = True) -> None:
980
+ """Abre um arquivo (Path ou string) no editor.
981
+
982
+ ``adopt_workspace=False`` impede que um arquivo fora do workspace troque
983
+ a pasta aberta (usado por arquivos baixados de servidores remotos, cuja
984
+ pasta é temporária).
985
+
986
+ Se o modo dual estiver ativo E o foco estiver no painel direito,
987
+ abre no lado direito via _dual_open_file para evitar que todos os
988
+ arquivos abertos no modo split caiam sempre no painel esquerdo.
989
+ """
990
+ path = (
991
+ Path(str(path_or_str)) if not isinstance(
992
+ path_or_str, Path) else path_or_str
993
+ )
994
+ if not path.exists():
995
+ messagebox.showerror(
996
+ _t("ui.file_not_found"),
997
+ _t("ui.could_not_open", path=str(path)),
998
+ parent=self._root,
999
+ )
1000
+ return
1001
+
1002
+ if getattr(self, "_dual_mode", False) and getattr(
1003
+ self, "_dual_right_active", False
1004
+ ):
1005
+ self._dual_open_file(path)
1006
+ return
1007
+
1008
+ editor = self._create_editor(path)
1009
+ if editor.load(path):
1010
+ self._cfg.add_recent_file(path)
1011
+ self._cfg.save()
1012
+ self._rebuild_recent_menu()
1013
+ if adopt_workspace and (
1014
+ self._workspace is None
1015
+ or (
1016
+ not str(path).startswith(str(self._workspace))
1017
+ and path.parent != self._workspace
1018
+ )
1019
+ ):
1020
+ self._set_workspace(path.parent)
1021
+ self._update_breadcrumb()
1022
+ self._fire_hook("file_open", path)
1023
+ self._status.notify(
1024
+ f"Opened: {path.name}", duration=2000, level="ok")
1025
+ self._output_panel.write(
1026
+ f"📂 Aberto: {path}", "Codis", "info", timestamp=True
1027
+ )
1028
+
1029
+ self._status.set_lang(editor.lang)
1030
+ self._status.set_encoding(editor.encoding)
1031
+ self._status.set_eol(editor.eol)
1032
+ self._notify_active_panels(editor)
1033
+
1034
+ def _open_file_at_line(self, path: Path, line: int) -> None:
1035
+ """Abre um arquivo e posiciona o cursor na linha especificada."""
1036
+ self._open_file(path)
1037
+ e = self._active_editor()
1038
+ if e:
1039
+ e.goto_line(line)
1040
+
1041
+ def open_file_dialog(self) -> None:
1042
+ """Abre um diálogo para selecionar arquivos e abri-los."""
1043
+ paths = filedialog.askopenfilenames(
1044
+ title=_t("file.open"),
1045
+ filetypes=[
1046
+ ("All supported", " ".join(f"*{ext}" for ext in EXT_LANG)),
1047
+ ("Python", "*.py *.pyw"),
1048
+ ("JavaScript", "*.js *.mjs *.jsx"),
1049
+ ("TypeScript", "*.ts *.tsx"),
1050
+ ("Web", "*.html *.css *.scss"),
1051
+ ("Data", "*.json *.yaml *.toml *.csv"),
1052
+ ("All files", "*.*"),
1053
+ ],
1054
+ parent=self._root,
1055
+ )
1056
+ for p in paths:
1057
+ self._open_file(Path(p))
1058
+
1059
+ def open_folder_dialog(self) -> None:
1060
+ """Abre um diálogo para selecionar uma pasta e definir como workspace."""
1061
+ folder = filedialog.askdirectory(
1062
+ title=_t("file.open_folder"), parent=self._root
1063
+ )
1064
+ if folder:
1065
+ self._set_workspace(Path(folder))
1066
+
1067
+ def _apply_workspace_trust(self, path: Path) -> None:
1068
+ """Pergunta se a pasta é confiável e restringe execução de código se não for.
1069
+
1070
+ Em modo restrito o LSP é desligado e as ferramentas de IA que executam
1071
+ comandos ficam bloqueadas. Se a opção ``workspace_trust`` estiver
1072
+ desligada, nenhuma restrição é aplicada.
1073
+ """
1074
+ if not self._cfg.get("workspace_trust", True):
1075
+ set_restricted(False)
1076
+ return
1077
+ trust = WorkspaceTrust()
1078
+ try:
1079
+ trusted = trust.prompt_if_needed(self._root, path, self._tmgr.theme)
1080
+ except tk.TclError:
1081
+ trusted = trust.is_trusted(path)
1082
+ set_restricted(not trusted)
1083
+ if self._lsp_mgr:
1084
+ self._lsp_mgr.set_enabled(trusted and bool(self._cfg.get("lsp_enabled", True)))
1085
+ if not trusted:
1086
+ logger.info("Workspace em modo restrito: %s", path)
1087
+
1088
+ def _set_workspace(self, path: Path) -> None:
1089
+ """Define o workspace atual e notifica os componentes."""
1090
+ previous = self._workspace
1091
+ if previous is not None and previous != path:
1092
+ self._fire_hook("workspace_close", previous)
1093
+ self._workspace = path
1094
+ self._apply_workspace_trust(path)
1095
+ self._file_tree.set_root(path)
1096
+ self._fire_hook("workspace_set", path)
1097
+
1098
+ with contextlib.suppress(tk.TclError):
1099
+ if (
1100
+ self._sidebar_current is self._sidebar_placeholder
1101
+ or self._current_sidebar == "explorer"
1102
+ ):
1103
+ self._sidebar_placeholder.pack_forget()
1104
+ self._file_tree.pack(fill="both", expand=True)
1105
+ self._sidebar_current = self._file_tree
1106
+ self._current_sidebar = "explorer"
1107
+
1108
+ if not self._sidebar_visible:
1109
+ self._show_sidebar()
1110
+ self._git_sidebar.set_root(path)
1111
+ self._git_bottom.set_root(path)
1112
+ with contextlib.suppress(AttributeError):
1113
+ self._terminal.set_cwd(str(path))
1114
+
1115
+ with contextlib.suppress(tk.TclError):
1116
+ self._code_stats_panel.set_workspace(path)
1117
+ with contextlib.suppress(tk.TclError):
1118
+ self._todo_panel.set_workspace(path)
1119
+ with contextlib.suppress(Exception):
1120
+ dw = getattr(self, "_depgraph_win", None)
1121
+ if dw is not None and dw.winfo_exists():
1122
+ for w in dw.winfo_children():
1123
+ if hasattr(w, "set_workspace"):
1124
+ w.set_workspace(path)
1125
+ break
1126
+
1127
+ with contextlib.suppress(tk.TclError):
1128
+ if self._kui:
1129
+ self._kui.notify_workspace_opened()
1130
+
1131
+ if self._lsp_mgr:
1132
+ with contextlib.suppress(tk.TclError):
1133
+ self._lsp_mgr.set_root(path)
1134
+ self._cfg.add_recent_folder(path)
1135
+ self._cfg.save()
1136
+ self._update_title()
1137
+ self._output_panel.write(
1138
+ f"Workspace: {path}", "Codis", "info", timestamp=True)
1139
+ if self._bus is not None:
1140
+ self._bus.emit(
1141
+ "workspace.open",
1142
+ {"path": str(path)},
1143
+ source="CodisApp",
1144
+ )
1145
+
1146
+ def _attach_log_handler(self) -> None:
1147
+ """Conecta um handler de logging para exibir mensagens no painel de saída."""
1148
+ panel = self._output_panel
1149
+
1150
+ class _PanelHandler(logging.Handler):
1151
+ LEVEL_MAP = {
1152
+ logging.DEBUG: "info",
1153
+ logging.INFO: "info",
1154
+ logging.WARNING: "warn",
1155
+ logging.ERROR: "error",
1156
+ logging.CRITICAL: "error",
1157
+ }
1158
+
1159
+ def emit(self, record: logging.LogRecord) -> None:
1160
+ """Formata e escreve o log record no painel de output, agendando no Tk thread."""
1161
+ try:
1162
+ msg = self.format(record)
1163
+ lvl = self.LEVEL_MAP.get(record.levelno, "info")
1164
+
1165
+ panel.write(msg, "Codis", lvl, timestamp=True)
1166
+ except Exception:
1167
+ logger.debug(
1168
+ "_PanelHandler: falha ao escrever no painel de output",
1169
+ exc_info=True,
1170
+ )
1171
+
1172
+ handler = _PanelHandler()
1173
+ handler.setLevel(logging.WARNING)
1174
+ handler.setFormatter(logging.Formatter("%(name)s: %(message)s"))
1175
+ logging.getLogger("Codis").addHandler(handler)
1176
+
1177
+ root_handler = _PanelHandler()
1178
+ root_handler.setLevel(logging.ERROR)
1179
+ root_handler.setFormatter(logging.Formatter("[%(name)s] %(message)s"))
1180
+ logging.getLogger().addHandler(root_handler)
1181
+
1182
+ def save_file(self) -> bool:
1183
+ """Salva o arquivo ativo. Retorna True se bem‑sucedido."""
1184
+ e = self._active_editor()
1185
+ if e:
1186
+ if self._fire_hook("before_save", e.path, cancellable=True):
1187
+ return False
1188
+ ok = e.save()
1189
+ if ok:
1190
+ self._fire_hook("file_save", e.path)
1191
+ self._fire_hook("after_save", e.path)
1192
+ if self._bus is not None and e.path:
1193
+ self._bus.emit(
1194
+ "editor.save",
1195
+ {"path": str(e.path), "lang": getattr(e, "lang", "")},
1196
+ source="CodisApp",
1197
+ )
1198
+
1199
+ self._bus.emit(
1200
+ "file.save",
1201
+ {"path": str(e.path)},
1202
+ source="CodisApp",
1203
+ )
1204
+
1205
+ if e.path:
1206
+ with contextlib.suppress(tk.TclError):
1207
+ self._todo_panel.notify_file_saved(e.path)
1208
+ with contextlib.suppress(tk.TclError):
1209
+ self._render_panel.notify_file_saved(e.path)
1210
+ with contextlib.suppress(Exception):
1211
+ self._web_preview_on_saved(e.path)
1212
+ with contextlib.suppress(tk.TclError):
1213
+ self._flowchart_panel.notify_file_saved(str(e.path))
1214
+ if _SMART_TIPS_AVAILABLE and self._smart_tips is not None:
1215
+ with contextlib.suppress(Exception):
1216
+ self._smart_tips._widget = e.text
1217
+ self._smart_tips._state.last_shown_ms = 0
1218
+ self._smart_tips.analyse(
1219
+ e.get_content(), e.lang, e.path, delay_ms=2000
1220
+ )
1221
+ return ok
1222
+ return False
1223
+
1224
+ def save_as(self) -> bool:
1225
+ """Abre diálogo para salvar o arquivo ativo com novo nome e caminho."""
1226
+ e = self._active_editor()
1227
+ return e.save_as() if e else False
1228
+
1229
+ def save_all(self) -> None:
1230
+ """Salva todos os arquivos abertos com modificações pendentes."""
1231
+ failed: list[str] = []
1232
+ for e in self._editors:
1233
+ if e.modified:
1234
+ try:
1235
+ ok = e.save() is not False
1236
+ except Exception as exc:
1237
+ logger.warning("Falha ao salvar '%s': %s", e.path, exc)
1238
+ ok = False
1239
+ if not ok:
1240
+ failed.append(e.path.name if e.path else _t("ui.tab_untitled"))
1241
+ if failed:
1242
+ self._status.notify(_t("msg.autosave_failed", names=", ".join(failed),
1243
+ default="Falha ao salvar: {names}"), level="warn")
1244
+ else:
1245
+ self._status.notify(_t("msg.all_files_saved"), level="ok")
1246
+
1247
+ def revert_file(self) -> None:
1248
+ """Reverte o arquivo ativo para a versão salva em disco."""
1249
+ e = self._active_editor()
1250
+ if e:
1251
+ e.revert()
1252
+
1253
+ def _rebuild_recent_menu(self) -> None:
1254
+ """Reconstrói o menu de arquivos recentes."""
1255
+ self._recent_menu.delete(0, "end")
1256
+ files = self._cfg.get_recent_files()
1257
+ for p in files[:20]:
1258
+ self._recent_menu.add_command(
1259
+ label=str(p), command=lambda f=p: self._open_file(f)
1260
+ )
1261
+ if not files:
1262
+ self._recent_menu.add_command(
1263
+ label=_t("hc.app.no_recent_files"), state="disabled"
1264
+ )
1265
+ self._recent_menu.add_separator()
1266
+ self._recent_menu.add_command(
1267
+ label=_t("hc.app.clear_recent"), command=self._clear_recent
1268
+ )
1269
+
1270
+ def _clear_recent(self) -> None:
1271
+ """Limpa a lista de arquivos recentes."""
1272
+ self._cfg.set("recent_files", [])
1273
+ self._cfg.save()
1274
+ self._rebuild_recent_menu()