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_tools.py ADDED
@@ -0,0 +1,2471 @@
1
+ """Mixin ``_AppToolsMixin`` - ferramentas auxiliares e painéis integrados do Codis.
2
+
3
+ Agrupa a lógica de abertura e gerenciamento dos painéis opcionais: terminal,
4
+ colaboração, gerenciador de pacotes, runner de código, SQL Studio, entre outros.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import json
11
+ import logging
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+ import time
18
+ import tkinter as tk
19
+ import webbrowser
20
+ from collections.abc import Callable
21
+ from pathlib import Path
22
+ from tkinter import filedialog, messagebox, ttk
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ from src import proc_registry
26
+ from src.constants import (
27
+ APP_CODENAME,
28
+ APP_NAME,
29
+ APP_VERSION,
30
+ DISCORD_URL,
31
+ FONT_MONO,
32
+ FONT_UI,
33
+ LANG_LABEL,
34
+ PLUGINS_DIR,
35
+ REPO_URL,
36
+ SESSIONS_FILE,
37
+ )
38
+ from src.editor.pane import EditorPane
39
+ from src.i18n import _t
40
+ from src.pyexec import spawn_codis
41
+ from src.theme.base import THEMES
42
+ from src.ui.color_picker import ColorPickerPopup, detect_colors_in_line
43
+ from src.ui.file_timeline import FileTimeline
44
+ from src.ui.grab_safe import safe_grab_set
45
+ from src.ui.welcome import WelcomeScreen, existing_recent_folders
46
+ from src.updater import UpdateManager
47
+ from src.updater.dialog import open_update_dialog
48
+
49
+ if TYPE_CHECKING:
50
+ pass
51
+
52
+ logger = logging.getLogger("Codis")
53
+
54
+ __all__ = ["_AppToolsMixin"]
55
+
56
+
57
+ class _AppToolsMixin:
58
+ """Mixin de Tools do CodisApp."""
59
+
60
+ def _open_file_timeline(self) -> None:
61
+ """Abre a linha do tempo (backups) do arquivo atual."""
62
+ e = self._e()
63
+ if e is None or e.path is None:
64
+ return
65
+ tw = getattr(self, "_timeline_win", None)
66
+ if tw is not None:
67
+ with contextlib.suppress(tk.TclError):
68
+ if tw.winfo_exists():
69
+ tw.deiconify()
70
+ tw.focus_force()
71
+ return
72
+ content = (
73
+ e.get_content()
74
+ if hasattr(e, "get_content")
75
+ else e.text.get("1.0", "end-1c")
76
+ )
77
+ win = FileTimeline(
78
+ self._root,
79
+ self._tmgr,
80
+ filepath=str(e.path),
81
+ current_content=content,
82
+ on_restore=lambda c: self._restore_from_timeline(e, c),
83
+ )
84
+ self._timeline_win = win
85
+
86
+ @staticmethod
87
+ def _restore_from_timeline(editor: EditorPane, content: str) -> None:
88
+ """Restaura o conteúdo do editor a partir de uma versão do timeline."""
89
+ editor.text.delete("1.0", "end")
90
+ editor.text.insert("1.0", content)
91
+ editor.text.edit_modified(True)
92
+ editor.modified = True
93
+
94
+ def _setup_autosave(self) -> None:
95
+ """Configura o temporizador de autosave."""
96
+ if self._autosave_job:
97
+ with contextlib.suppress(tk.TclError):
98
+ self._root.after_cancel(self._autosave_job)
99
+ self._autosave_job = None
100
+ if self._cfg.get("autosave", False):
101
+ ms = max(5, self._cfg.get("autosave_delay", 30)) * 1000
102
+ self._autosave_job = self._root.after(ms, self._autosave_tick)
103
+
104
+ def _setup_tracker_heartbeat(self) -> None:
105
+ """Inicia o loop de heartbeat do Code Time Tracker (10 s)."""
106
+ try:
107
+ if not hasattr(self, "_tracker_model") or self._tracker_model is None:
108
+ return
109
+ ms = 10_000
110
+
111
+ def _tick():
112
+ try:
113
+ e = (
114
+ self._active_editor()
115
+ if hasattr(self, "_active_editor")
116
+ else None
117
+ )
118
+ path = str(e.path) if (e and e.path) else None
119
+ ws = str(self._workspace) if self._workspace else None
120
+ self._tracker_model.on_activity(path, ws)
121
+ self._tracker_model.save()
122
+ tw = getattr(self, "_tracker_win", None)
123
+ if tw is not None:
124
+ try:
125
+ if tw.winfo_exists():
126
+ for child in tw.winfo_children():
127
+ if hasattr(child, "_refresh"):
128
+ child._refresh()
129
+ break
130
+ except Exception:
131
+ logger.debug(
132
+ "Falha ao atualizar time tracker widget.", exc_info=True
133
+ )
134
+ except Exception:
135
+ logger.debug(
136
+ "Falha no tick do timer da barra de status.", exc_info=True
137
+ )
138
+ self._root.after(ms, _tick)
139
+
140
+ self._root.after(ms, _tick)
141
+ except Exception as exc:
142
+ logger.debug("tracker heartbeat: %s", exc)
143
+
144
+ def _autosave_tick(self) -> None:
145
+ """Executa o autosave a cada intervalo."""
146
+ failed: list[str] = []
147
+ for e in self._editors:
148
+ if e.modified and e.path:
149
+ try:
150
+ ok = e.save() is not False
151
+ except Exception as exc:
152
+ logger.warning("Autosave falhou em '%s': %s", e.path, exc)
153
+ ok = False
154
+ if not ok:
155
+ failed.append(e.path.name)
156
+ if failed:
157
+ with contextlib.suppress(Exception):
158
+ self._status.notify(_t("msg.autosave_failed", names=", ".join(failed),
159
+ default="Autosave falhou: {names}"), level="warn")
160
+ self._setup_autosave()
161
+
162
+ def _toggle_autosave(self) -> None:
163
+ """Alterna a configuração de autosave."""
164
+ self._cfg.set("autosave", self._autosave_var.get())
165
+ self._cfg.save()
166
+ self._setup_autosave()
167
+
168
+ def _restore_session_or_welcome(self) -> None:
169
+ """Restaura a sessão anterior ou exibe a tela de boas-vindas."""
170
+ if not self._cfg.get("session_restore", True):
171
+ self._show_start_content()
172
+ return
173
+
174
+ session: dict[str, Any] = {}
175
+ try:
176
+ if SESSIONS_FILE.exists():
177
+ parsed = json.loads(SESSIONS_FILE.read_text(encoding="utf-8"))
178
+ if isinstance(parsed, dict):
179
+ session = parsed
180
+ else:
181
+ raise ValueError("session.json com estrutura inválida")
182
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
183
+ logger.debug("Sessão inválida (%s) - iniciando limpo.", exc)
184
+ with contextlib.suppress(OSError):
185
+ if SESSIONS_FILE.exists():
186
+ SESSIONS_FILE.rename(
187
+ SESSIONS_FILE.with_suffix(".json.bak"))
188
+
189
+ if session.get("workspace"):
190
+ p = Path(session["workspace"])
191
+ if p.is_dir():
192
+ with contextlib.suppress(tk.TclError):
193
+ self._set_workspace(p)
194
+
195
+ restored = False
196
+ for fpath in session.get("files", []):
197
+ p = Path(fpath)
198
+ if p.is_file():
199
+ with contextlib.suppress(tk.TclError):
200
+ self._open_file(p)
201
+ restored = True
202
+
203
+ active = self._session_active_index(session)
204
+ if restored and active is not None:
205
+ with contextlib.suppress(tk.TclError):
206
+ self._select_tab(active)
207
+ elif not restored:
208
+ self._show_start_content()
209
+
210
+ def _show_start_content(self) -> None:
211
+ """Conteúdo inicial quando não há nada a restaurar.
212
+
213
+ A tela de boas-vindas já nasce visível na construção da janela; com
214
+ ``show_welcome`` desligado ela é escondida e abre-se uma aba em branco.
215
+ """
216
+ if self._cfg.get("show_welcome", True):
217
+ self._show_welcome()
218
+ return
219
+ self._hide_classic_welcome()
220
+ self.new_file()
221
+
222
+ def _active_session_file(self) -> str | None:
223
+ """Caminho do arquivo da aba ativa, para reativá-la pelo nome e não pela posição."""
224
+ if 0 <= self._active_idx < len(self._editors):
225
+ path = self._editors[self._active_idx].path
226
+ return str(path) if path else None
227
+ return None
228
+
229
+ def _session_active_index(self, session: dict[str, Any]) -> int | None:
230
+ """Índice da aba a ativar ao restaurar a sessão.
231
+
232
+ A posição salva não vale quando há abas sem nome ou arquivos que sumiram (os índices
233
+ deslocam), então o arquivo ativo tem prioridade; a posição só serve a sessões antigas.
234
+ """
235
+ target = session.get("active_file")
236
+ if target:
237
+ found = self._find_editor_for_path(Path(target))
238
+ if found is not None:
239
+ return found
240
+ elif "active_file" not in session:
241
+ index = session.get("active_tab", 0)
242
+ if isinstance(index, int) and 0 <= index < len(self._editors):
243
+ return index
244
+ return 0 if self._editors else None
245
+
246
+ def _save_session(self) -> None:
247
+ """Salva a sessão atual (arquivos abertos, workspace, etc.) no disco."""
248
+ try:
249
+ data = {
250
+ "workspace": str(self._workspace) if self._workspace else None,
251
+ "files": [str(e.path) for e in self._editors if e.path],
252
+ "active_tab": max(0, self._active_idx),
253
+ "active_file": self._active_session_file(),
254
+ "codis_ver": APP_VERSION,
255
+ }
256
+ SESSIONS_FILE.parent.mkdir(parents=True, exist_ok=True)
257
+ tmp = SESSIONS_FILE.with_suffix(".json.tmp")
258
+ tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
259
+ tmp.replace(SESSIONS_FILE)
260
+ except OSError as exc:
261
+ logger.debug("Erro ao salvar sessão: %s", exc)
262
+
263
+ def _load_plugins(self) -> None:
264
+ """Carrega todos os plugins instalados e registra suas contribuições."""
265
+ try:
266
+ PLUGINS_DIR.mkdir(parents=True, exist_ok=True)
267
+ self._plugin_loader.load_all()
268
+ try:
269
+ self._ext_runtime.activate_all()
270
+ except Exception:
271
+ logger.warning("Falha ao ativar extensões importadas", exc_info=True)
272
+ try:
273
+ self._ext_code_manager().restore()
274
+ except Exception:
275
+ logger.warning("Falha ao restaurar extensões com código", exc_info=True)
276
+ n = len(self._plugin_loader.plugins)
277
+ errs = len(self._plugin_loader.errors)
278
+ if n:
279
+ self._output_panel.write(
280
+ f"Plugins carregados: {n}", "Extensions", "info", timestamp=True
281
+ )
282
+ if errs:
283
+ self._output_panel.write(
284
+ f"Plugins com falha: {errs} - verifique o log",
285
+ "Extensions",
286
+ "warn",
287
+ timestamp=True,
288
+ )
289
+ for pid, tb in self._plugin_loader.errors.items():
290
+ logger.warning("Plugin '%s':\n%s", pid, tb)
291
+ except (OSError, ImportError, RuntimeError) as exc:
292
+ logger.warning("Plugin load error: %s", exc)
293
+ if not getattr(self, "_plugins_started", False):
294
+ self._plugins_started = True
295
+ self._bind_pane_providers()
296
+ self._root.after_idle(self._finish_plugin_startup)
297
+
298
+ def _plugin_context_items(self, context: str, target: Any) -> list[tuple[str, Callable[[], None]]]:
299
+ """Itens que plugins adicionaram ao menu de contexto ``context``."""
300
+ items: list[tuple[str, Callable[[], None]]] = []
301
+ for ext in self._extensions.get("context_menu", context):
302
+ if ext.when is not None:
303
+ try:
304
+ if not ext.when():
305
+ continue
306
+ except Exception:
307
+ continue
308
+ handler = ext.fn
309
+
310
+ def action(h=handler, owner=ext.owner) -> None:
311
+ try:
312
+ h() if target is None else h(target)
313
+ except Exception as exc:
314
+ logger.warning("Item de menu de contexto de %s falhou: %s", owner, exc)
315
+
316
+ items.append((ext.label, action))
317
+ return items
318
+
319
+ def _bind_pane_providers(self) -> None:
320
+ from src.editor.pane import EditorPane
321
+ from src.ui.file_tree import FileTree
322
+
323
+ EditorPane.format_provider = lambda pane: self._plugin_formatted(pane)
324
+ EditorPane.context_provider = self._plugin_context_items
325
+ FileTree.context_provider = self._plugin_context_items
326
+
327
+ def _finish_plugin_startup(self) -> None:
328
+ """Executa o script de inicialização do usuário e avisa que o app está pronto."""
329
+ from src.plugins import startup
330
+
331
+ startup.run(self)
332
+ self._fire_hook("app_ready")
333
+
334
+ def _ext_code_manager(self) -> Any:
335
+ """Gerenciador da execução de código de extensões (nada roda até o usuário liberar)."""
336
+ if self._ext_code is None:
337
+ from src.extcompat.code import CodeManager, CodeState
338
+ from src.ui.extcode_bridge import AppCommandSink, TkBridge
339
+
340
+ state = CodeState(self._ext_store.root.parent / "extension_code.json")
341
+ self._ext_code = CodeManager(state, self._ext_store, AppCommandSink(self), TkBridge(self))
342
+ return self._ext_code
343
+
344
+ def _open_ext_compat(self) -> None:
345
+ """Abre o diálogo de extensões de outros editores (VS Code, Zed, Vim/Neovim)."""
346
+ from src.ui.extcompat_dialog import open_dialog
347
+
348
+ existing = getattr(self, "_ext_compat_dialog", None)
349
+ with contextlib.suppress(tk.TclError, AttributeError):
350
+ if existing is not None and existing.winfo_exists():
351
+ existing.lift()
352
+ return
353
+ self._ext_compat_dialog = open_dialog(
354
+ self._root, self._tmgr, self._ext_store, self._ext_runtime, self, self._ext_code_manager()
355
+ )
356
+
357
+ def _install_plugin(self) -> None:
358
+ """Delega a instalação ao PluginPanel (que possui o fluxo de sandbox)."""
359
+ with contextlib.suppress(AttributeError):
360
+ self._plugin_panel._install()
361
+ return
362
+
363
+ paths = filedialog.askopenfilenames(
364
+ title=_t("hc.app.instalar_plugin"),
365
+ filetypes=[("Plugins Codis", "*.py *.zip"), ("Todos", "*.*")],
366
+ parent=self._root,
367
+ )
368
+ for p in paths:
369
+ try:
370
+ self._plugin_loader.install_from_path(Path(p))
371
+ except (OSError, ValueError) as exc:
372
+ messagebox.showerror(_t("err.install_plugin"), str(exc))
373
+ with contextlib.suppress(AttributeError, tk.TclError):
374
+ self._plugin_panel.refresh()
375
+
376
+ def _hook_lang(self, event: str, data: Any) -> str:
377
+ """Linguagem associada ao evento, para handlers registrados com ``lang=``."""
378
+ if event == "lang_change":
379
+ return str(data or "")
380
+ lang = getattr(data, "lang", None)
381
+ if isinstance(lang, str):
382
+ return lang
383
+ if isinstance(data, Path):
384
+ from src.constants import EXT_LANG
385
+
386
+ return EXT_LANG.get(data.suffix.lower(), "")
387
+ return ""
388
+
389
+ def _fire_hook(self, event: str, data: Any = None, *, cancellable: bool = False) -> bool:
390
+ """Dispara ``event`` para os plugins e publica no EventBus.
391
+
392
+ Cada handler roda isolado: a exceção de um é registrada no log (e aparece no painel
393
+ Output) sem impedir os outros. Com ``cancellable``, um handler que devolve ``False``
394
+ interrompe a cadeia e o retorno é ``True``, sinal para quem chamou desistir da ação.
395
+ """
396
+ kui = getattr(self, "_kui", None)
397
+ if kui is not None:
398
+ with contextlib.suppress(Exception):
399
+ kui.on_app_event(event, data)
400
+ args = () if data is None else (data,)
401
+ lang = self._hook_lang(event, data)
402
+ if cancellable:
403
+ return self._plugin_hooks.veto(event, *args, lang=lang)
404
+ self._plugin_hooks.fire(event, *args, lang=lang)
405
+ return False
406
+
407
+ def _emit_bus_metrics(self) -> None:
408
+ """Emite métricas do EventBus no canal PERF e reagenda a próxima emissão."""
409
+ if self._bus is None:
410
+ return
411
+ try:
412
+ metrics = self._bus.metrics()
413
+ if metrics:
414
+ self._bus.emit(
415
+ "perf.metric",
416
+ {"bus_metrics": metrics},
417
+ source="CodisApp",
418
+ )
419
+ except Exception:
420
+ logger.debug("_emit_bus_metrics: erro ignorado", exc_info=True)
421
+ finally:
422
+ self._root.after(30_000, self._emit_bus_metrics)
423
+
424
+ def _hide_classic_welcome(self) -> None:
425
+ """Esconde a WelcomeScreen clássica (com o K-UI ativo só a KWelcome existe)."""
426
+ w = getattr(self, "_welcome", None)
427
+ if w is None:
428
+ return
429
+ with contextlib.suppress(tk.TclError):
430
+ if w.winfo_exists() and w.winfo_manager():
431
+ w.pack_forget()
432
+
433
+ def _present_start_screen(self) -> None:
434
+ """Mostra a tela inicial do modo atual (K-UI ou clássico) - ponto único."""
435
+ if self._kui and getattr(self._kui, "_enabled", False):
436
+ self._show_welcome()
437
+ return
438
+ with contextlib.suppress(tk.TclError):
439
+ self._welcome.pack(fill="both", expand=True)
440
+
441
+ def _new_welcome(self) -> WelcomeScreen:
442
+ """Cria a tela de boas-vindas clássica com os callbacks do app."""
443
+ return WelcomeScreen(
444
+ self._editor_container,
445
+ self._tmgr,
446
+ self._cfg,
447
+ on_new=self.new_file,
448
+ on_open_file=self.open_file_dialog,
449
+ on_open_folder=self.open_folder_dialog,
450
+ on_open_recent=self._open_file,
451
+ recent_files=[str(p) for p in self._cfg.get_recent_files()[:12]],
452
+ on_clone_success=self._on_clone_success,
453
+ on_log=lambda msg, ch, lv: self._output_panel.write(
454
+ msg, channel=ch, level=lv, timestamp=True
455
+ ),
456
+ on_shortcuts=self._keybindings_dialog,
457
+ on_settings=lambda: self._activity("settings"),
458
+ recent_folders=existing_recent_folders(self._cfg),
459
+ on_open_recent_folder=lambda p: self._set_workspace(Path(p)),
460
+ )
461
+
462
+ def _show_welcome(self) -> None:
463
+ """Exibe a tela de boas-vindas.
464
+
465
+ Se o K-UI estiver ativo, usa a KWelcome cosmica (cosmos pleno).
466
+ Caso contrario, usa a WelcomeScreen classica.
467
+ """
468
+ if self._kui and getattr(self._kui, "_enabled", False):
469
+ self._hide_classic_welcome()
470
+ for e in self._editors:
471
+ with contextlib.suppress(tk.TclError):
472
+ e.pack_forget()
473
+ self._active_idx = -1
474
+ self._active_pane = None
475
+ with contextlib.suppress(tk.TclError):
476
+ self._tabbar.set_active(-1)
477
+ self._update_title()
478
+
479
+ self._kui.show_welcome(
480
+ on_new=self.new_file,
481
+ on_open=self.open_file_dialog,
482
+ on_folder=self.open_folder_dialog,
483
+ on_recent=self._open_file,
484
+ recent_files=[str(p) for p in self._cfg.get_recent_files()[:12]],
485
+ )
486
+ return
487
+
488
+ if hasattr(self, "_welcome") and self._welcome.winfo_exists():
489
+ self._welcome.destroy()
490
+ self._welcome = self._new_welcome()
491
+ for e in self._editors:
492
+ e.pack_forget()
493
+ self._active_idx = -1
494
+ self._active_pane = None
495
+ self._welcome.pack(fill="both", expand=True)
496
+ self._tabbar.set_active(-1)
497
+ self._update_title()
498
+
499
+ def _on_clone_success(self, dest: Path) -> None:
500
+ """Chamado quando um clone de repositório é concluído com sucesso."""
501
+ with contextlib.suppress(tk.TclError, AttributeError):
502
+ self._show_panel("output")
503
+ self._output_panel.add_channel("Git Clone")
504
+ if dest.is_dir():
505
+ self._set_workspace(dest)
506
+
507
+ def _about_dialog(self) -> None:
508
+ """Exibe o diálogo 'Sobre' com design completo, links e info do sistema."""
509
+ t = self._tmgr.theme
510
+ win = tk.Toplevel(self._root)
511
+ win.title(_t("about.title"))
512
+ win.resizable(True, True)
513
+ win.config(bg=t.floating_bg)
514
+ win.wm_attributes("-topmost", True)
515
+ safe_grab_set(win)
516
+ win.minsize(520, 540)
517
+
518
+ hero = tk.Frame(win, bg=t.activity_bg, highlightthickness=0)
519
+ hero.pack(fill="x")
520
+
521
+ inner_hero = tk.Frame(hero, bg=t.activity_bg)
522
+ inner_hero.pack(padx=32, pady=(28, 22))
523
+
524
+ logo_lbl = tk.Label(
525
+ inner_hero, text="⬡", bg=t.activity_bg, fg=t.btn_primary, font=(FONT_UI, 36)
526
+ )
527
+ logo_lbl.pack()
528
+ tk.Label(
529
+ inner_hero,
530
+ text=APP_NAME,
531
+ bg=t.activity_bg,
532
+ fg=t.fg,
533
+ font=(FONT_UI, 26, "bold"),
534
+ ).pack(pady=(2, 0))
535
+
536
+ ver_frame = tk.Frame(inner_hero, bg=t.activity_bg)
537
+ ver_frame.pack(pady=(6, 0))
538
+ tk.Label(
539
+ ver_frame,
540
+ text=f" v{APP_VERSION} ",
541
+ bg=t.btn_primary,
542
+ fg="#000",
543
+ font=(FONT_UI, 8, "bold"),
544
+ padx=6,
545
+ pady=2,
546
+ ).pack(side="left")
547
+ tk.Label(
548
+ ver_frame,
549
+ text=f" {APP_CODENAME}",
550
+ bg=t.activity_bg,
551
+ fg=t.fg_muted,
552
+ font=(FONT_UI, 9),
553
+ ).pack(side="left")
554
+
555
+ tk.Label(
556
+ inner_hero,
557
+ text=_t("about.tagline"),
558
+ bg=t.activity_bg,
559
+ fg=t.fg_muted,
560
+ font=(FONT_UI, 9),
561
+ ).pack(pady=(8, 0))
562
+ tk.Label(
563
+ inner_hero,
564
+ text=f"{_t('about.author')} - {_t('about.license')}",
565
+ bg=t.activity_bg,
566
+ fg=t.fg_muted,
567
+ font=(FONT_UI, 8),
568
+ ).pack(pady=(3, 0))
569
+
570
+ color_bar = tk.Frame(hero, bg=t.activity_bg, height=4)
571
+ color_bar.pack(fill="x")
572
+ accent_colors = [
573
+ t.btn_primary,
574
+ getattr(t, "ok_fg", "#4ade80"),
575
+ getattr(t, "warn_fg", "#facc15"),
576
+ getattr(t, "err_fg", "#f87171"),
577
+ t.btn_primary,
578
+ ]
579
+ for clr in accent_colors:
580
+ tk.Frame(color_bar, bg=clr, height=4).pack(
581
+ side="left", fill="both", expand=True
582
+ )
583
+
584
+ body_canvas = tk.Canvas(win, bg=t.floating_bg,
585
+ highlightthickness=0, bd=0)
586
+ body_scroll = tk.Scrollbar(
587
+ win, orient="vertical", command=body_canvas.yview)
588
+ body_canvas.configure(yscrollcommand=body_scroll.set)
589
+ body_scroll.pack(side="right", fill="y")
590
+ body_canvas.pack(fill="both", expand=True)
591
+
592
+ body = tk.Frame(body_canvas, bg=t.floating_bg)
593
+ body_win = body_canvas.create_window((0, 0), window=body, anchor="nw")
594
+
595
+ def _on_body_resize(evt=None):
596
+ body_canvas.configure(scrollregion=body_canvas.bbox("all"))
597
+
598
+ def _on_canvas_resize(evt):
599
+ body_canvas.itemconfig(body_win, width=evt.width)
600
+
601
+ def _on_mwheel(evt):
602
+ body_canvas.yview_scroll(int(-1 * evt.delta / 120), "units")
603
+
604
+ body.bind("<Configure>", _on_body_resize)
605
+ body_canvas.bind("<Configure>", _on_canvas_resize)
606
+ body_canvas.bind("<MouseWheel>", _on_mwheel)
607
+
608
+ def _section_hdr(txt: str) -> None:
609
+ frm = tk.Frame(body, bg=t.floating_bg)
610
+ frm.pack(fill="x", padx=24, pady=(18, 6))
611
+ tk.Label(
612
+ frm, text=txt, bg=t.floating_bg, fg=t.fg, font=(
613
+ FONT_UI, 10, "bold")
614
+ ).pack(side="left")
615
+ tk.Frame(frm, bg=t.border, height=1).pack(
616
+ side="left", fill="x", expand=True, padx=(10, 0), pady=5
617
+ )
618
+
619
+ def _link_btn(parent, label: str, url: str, primary: bool = False) -> tk.Label:
620
+ bg = t.btn_primary if primary else t.activity_bg
621
+ fg = "#000" if primary else t.fg
622
+ lbl = tk.Label(
623
+ parent,
624
+ text=label,
625
+ bg=bg,
626
+ fg=fg,
627
+ font=(FONT_UI, 9, "bold" if primary else "normal"),
628
+ padx=16,
629
+ pady=7,
630
+ cursor="hand2",
631
+ highlightthickness=1 if not primary else 0,
632
+ highlightbackground=t.border if not primary else bg,
633
+ )
634
+ lbl.bind("<Button-1>", lambda _: webbrowser.open(url))
635
+ lbl.bind(
636
+ "<Enter>",
637
+ lambda _: lbl.config(
638
+ bg=(
639
+ t.btn_primary
640
+ if primary
641
+ else t.sel_bg if hasattr(t, "sel_bg") else t.border
642
+ ),
643
+ fg="#000" if primary else t.btn_primary,
644
+ ),
645
+ )
646
+ lbl.bind("<Leave>", lambda _: lbl.config(bg=bg, fg=fg))
647
+ return lbl
648
+
649
+ _section_hdr(_t("about.links"))
650
+
651
+ links_grid = tk.Frame(body, bg=t.floating_bg)
652
+ links_grid.pack(fill="x", padx=24)
653
+ links_grid.columnconfigure(0, weight=1)
654
+ links_grid.columnconfigure(1, weight=1)
655
+
656
+ LINKS = [
657
+ (_t("about.github_codis"), REPO_URL, True),
658
+ (_t("about.github_dev"), "https://github.com/KillovSky", False),
659
+ (_t("about.linktree"), "https://linktr.ee/killovsky", False),
660
+ (_t("about.npm"), "https://www.npmjs.com/~killovsky", False),
661
+ (_t("about.discord"), DISCORD_URL, False),
662
+ ]
663
+ for i, (label, url, primary) in enumerate(LINKS):
664
+ r, c = divmod(i, 2)
665
+ btn = _link_btn(links_grid, label, url, primary)
666
+ btn.grid(row=r, column=c, padx=4, pady=4, sticky="ew")
667
+
668
+ _section_hdr(_t("about.sysinfo"))
669
+
670
+ sysinfo_grid = tk.Frame(body, bg=t.floating_bg)
671
+ sysinfo_grid.pack(fill="x", padx=24, pady=(0, 8))
672
+ sysinfo_grid.columnconfigure(0, weight=1)
673
+ sysinfo_grid.columnconfigure(1, weight=1)
674
+
675
+ sysinfo_items = [
676
+ ("🐍 Python", sys.version.split()[0]),
677
+ ("🪟 Tkinter", str(tk.TkVersion)),
678
+ ("🖥 Platform", sys.platform),
679
+ ("Themes", str(len(THEMES))),
680
+ ("🌐 Languages", str(len(LANG_LABEL))),
681
+ ("🔌 Plugins", str(len(self._plugin_loader.plugins))),
682
+ ]
683
+ for i, (k, v) in enumerate(sysinfo_items):
684
+ r, c = divmod(i, 2)
685
+ cell = tk.Frame(
686
+ sysinfo_grid,
687
+ bg=t.activity_bg,
688
+ highlightthickness=1,
689
+ highlightbackground=t.border,
690
+ )
691
+ cell.grid(row=r, column=c, padx=4, pady=3, sticky="ew")
692
+ inn = tk.Frame(cell, bg=t.activity_bg, padx=10, pady=6)
693
+ inn.pack(fill="x")
694
+ tk.Label(
695
+ inn,
696
+ text=k,
697
+ bg=t.activity_bg,
698
+ fg=t.fg_muted,
699
+ font=(FONT_UI, 7),
700
+ anchor="w",
701
+ ).pack(fill="x")
702
+ tk.Label(
703
+ inn,
704
+ text=v,
705
+ bg=t.activity_bg,
706
+ fg=t.fg,
707
+ font=(FONT_UI, 9, "bold"),
708
+ anchor="w",
709
+ ).pack(fill="x")
710
+
711
+ tk.Frame(body, bg=t.floating_bg, height=10).pack()
712
+
713
+ footer = tk.Frame(win, bg=t.floating_bg, highlightthickness=0)
714
+ footer.pack(fill="x")
715
+ tk.Frame(footer, bg=t.border, height=1).pack(fill="x")
716
+ btn_row = tk.Frame(footer, bg=t.floating_bg)
717
+ btn_row.pack(fill="x", padx=20, pady=10)
718
+
719
+ close_btn = tk.Label(
720
+ btn_row,
721
+ text=_t("about.close"),
722
+ bg=t.btn_bg,
723
+ fg=t.fg,
724
+ font=(FONT_UI, 9),
725
+ padx=20,
726
+ pady=6,
727
+ cursor="hand2",
728
+ )
729
+ close_btn.pack(side="right")
730
+ close_btn.bind("<Button-1>", lambda _: win.destroy())
731
+
732
+ mit_lbl = tk.Label(
733
+ btn_row,
734
+ text=_t("about.mit_credit"),
735
+ bg=t.floating_bg,
736
+ fg=t.fg_muted,
737
+ font=(FONT_UI, 8),
738
+ )
739
+ mit_lbl.pack(side="left")
740
+
741
+ win.update_idletasks()
742
+ sw = win.winfo_screenwidth()
743
+ sh = win.winfo_screenheight()
744
+ w = min(620, int(sw * 0.45))
745
+ h = min(660, int(sh * 0.80))
746
+ win.minsize(480, 520)
747
+ rx = self._root.winfo_rootx() + self._root.winfo_width() // 2
748
+ ry = self._root.winfo_rooty() + self._root.winfo_height() // 2
749
+ win.geometry(f"{w}x{h}+{rx - w // 2}+{ry - h // 2}")
750
+
751
+ def _check_for_updates(self) -> None:
752
+ """Abre o diálogo de atualização do Codis (uma única janela por vez)."""
753
+ existing = getattr(self, "_update_dialog", None)
754
+ if existing is not None and existing.winfo_exists():
755
+ existing.lift()
756
+ existing.focus_force()
757
+ return
758
+ self._update_dialog = open_update_dialog(
759
+ self._root,
760
+ UpdateManager.from_config(self._cfg, APP_VERSION),
761
+ tmgr=self._tmgr,
762
+ on_restart=self._restart_process,
763
+ )
764
+
765
+ def _keybindings_dialog(self) -> None:
766
+ """Exibe o diálogo de atalhos de teclado."""
767
+ t = self._tmgr.theme
768
+ win = tk.Toplevel(self._root)
769
+ win.title(_t("ui.keybindings_title"))
770
+ win.geometry("560x520")
771
+ win.config(bg=t.floating_bg)
772
+ safe_grab_set(win)
773
+
774
+ tk.Label(
775
+ win,
776
+ text=_t("ui.keybindings_title"),
777
+ bg=t.floating_bg,
778
+ fg=t.fg,
779
+ font=(FONT_UI, 13, "bold"),
780
+ ).pack(pady=8)
781
+
782
+ txt = tk.Text(
783
+ win,
784
+ bg=t.floating_bg,
785
+ fg=t.fg,
786
+ font=(FONT_MONO, 9),
787
+ relief="flat",
788
+ bd=0,
789
+ state="disabled",
790
+ padx=16,
791
+ pady=8,
792
+ )
793
+ vsb = ttk.Scrollbar(
794
+ win, orient="vertical", command=txt.yview, style="Thin.Vertical.TScrollbar"
795
+ )
796
+ vsb.pack(side="right", fill="y")
797
+ txt.config(yscrollcommand=vsb.set)
798
+ txt.pack(fill="both", expand=True)
799
+
800
+ sections = [
801
+ (
802
+ _t("keybind.sec.general"),
803
+ [
804
+ ("Ctrl+Shift+P", _t("keybind.cmd.palette")),
805
+ ("Ctrl+P", _t("keybind.quick_open")),
806
+ ("Ctrl+,", _t("keybind.settings")),
807
+ ("F11", _t("keybind.fullscreen")),
808
+ ("Ctrl+`", _t("keybind.terminal")),
809
+ ("F5", _t("keybind.run")),
810
+ ],
811
+ ),
812
+ (
813
+ _t("keybind.sec.file"),
814
+ [
815
+ ("Ctrl+N", _t("keybind.new_file")),
816
+ ("Ctrl+O", _t("keybind.open_file")),
817
+ ("Ctrl+S", _t("keybind.save")),
818
+ ("Ctrl+Shift+S", _t("keybind.save_as")),
819
+ ("Ctrl+W", _t("keybind.close_tab")),
820
+ ("Ctrl+Tab", _t("keybind.next_tab")),
821
+ ],
822
+ ),
823
+ (
824
+ _t("keybind.sec.edit"),
825
+ [
826
+ ("Ctrl+Z", _t("keybind.undo")),
827
+ ("Ctrl+Y", _t("keybind.redo")),
828
+ ("Ctrl+/", _t("keybind.comment")),
829
+ ("Ctrl+D", _t("keybind.duplicate")),
830
+ ("Ctrl+Shift+K", _t("keybind.delete_line")),
831
+ ("Alt+Up/Down", _t("keybind.move_line")),
832
+ ("Ctrl+F", _t("keybind.find")),
833
+ ("Ctrl+H", _t("keybind.replace")),
834
+ ("Ctrl+Shift+F", _t("keybind.find_files")),
835
+ ("Ctrl+Alt+M", _t("keybind.multi_cursor")),
836
+ ("Shift+Alt+F", _t("keybind.format")),
837
+ ],
838
+ ),
839
+ (
840
+ _t("keybind.sec.nav"),
841
+ [
842
+ ("Ctrl+G", _t("keybind.go_line")),
843
+ ("F8", _t("keybind.next_problem")),
844
+ ("Shift+F8", _t("keybind.prev_problem")),
845
+ ("F7", _t("keybind.next_diff")),
846
+ ("F3", _t("keybind.next_match")),
847
+ ],
848
+ ),
849
+ (
850
+ _t("keybind.sec.view"),
851
+ [
852
+ ("Ctrl++", _t("keybind.zoom_in")),
853
+ ("Ctrl+-", _t("keybind.zoom_out")),
854
+ ("Ctrl+0", _t("keybind.zoom_reset")),
855
+ ("Ctrl+Shift+E", _t("actbar.explorer")),
856
+ ("Ctrl+Shift+G", _t("actbar.git")),
857
+ ("Ctrl+Shift+D", _t("actbar.run")),
858
+ ("Ctrl+Shift+X", _t("actbar.extensions")),
859
+ ("Ctrl+Shift+B", _t("actbar.bookmarks")),
860
+ ("Ctrl+Shift+M", _t("actbar.problems")),
861
+ ("Ctrl+Alt+L", _t("actbar.chat")),
862
+ ("Ctrl+\\", _t("keybind.split_editor")),
863
+ ],
864
+ ),
865
+ ]
866
+
867
+ txt.config(state="normal")
868
+ for title, items in sections:
869
+ txt.insert("end", f"\n {title}\n")
870
+ start = txt.index("end - 2 lines")
871
+ end = txt.index("end - 1 char")
872
+ tag = f"sec_{title}"
873
+ txt.tag_configure(tag, foreground=t.t_keyword,
874
+ font=(FONT_UI, 9, "bold"))
875
+ txt.tag_add(tag, start, end)
876
+ for key, desc in items:
877
+ txt.insert("end", f" {key:<24} {desc}\n")
878
+ txt.config(state="disabled")
879
+
880
+ @staticmethod
881
+ def _open_extern(path: Path) -> None:
882
+ """Abre uma pasta no explorador de arquivos do sistema."""
883
+ path.mkdir(parents=True, exist_ok=True)
884
+ with contextlib.suppress(OSError):
885
+ if sys.platform == "win32":
886
+ os.startfile(str(path))
887
+ elif sys.platform == "darwin":
888
+ with subprocess.Popen(["open", str(path)]):
889
+ pass
890
+ else:
891
+ with subprocess.Popen(["xdg-open", str(path)]):
892
+ pass
893
+
894
+ @staticmethod
895
+ def _open_home() -> None:
896
+ """Abre a tela inicial (área de trabalho com atalhos) em outro processo."""
897
+ try:
898
+ spawn_codis(["--home"])
899
+ except OSError as exc:
900
+ messagebox.showerror(_t("err.new_window"), str(exc))
901
+
902
+ @staticmethod
903
+ def _new_window() -> None:
904
+ """Abre uma nova janela do Codis."""
905
+ try:
906
+ spawn_codis(["--editor"])
907
+ except OSError as exc:
908
+ messagebox.showerror(_t("err.new_window"), str(exc))
909
+
910
+ def _purge_active_tab_memory(self) -> None:
911
+ """Libera a memória não-essencial da aba ativa (highlight, undo, caches)."""
912
+ e = self._e()
913
+ if e:
914
+ e.purge_memory()
915
+ else:
916
+ messagebox.showinfo("Liberar memória", _t("ui.no_open_tab"))
917
+
918
+ def _global_gc(self) -> None:
919
+ """Libera caches e memória do processo e mostra quanto foi recuperado."""
920
+ from src import memtrim
921
+
922
+ before, after = memtrim.release_memory()
923
+ if before is None or after is None:
924
+ detail = "Caches limpos e memória devolvida ao sistema."
925
+ else:
926
+ detail = (
927
+ f"Memória do processo: {before:.0f} MB → {after:.0f} MB "
928
+ f"({max(before - after, 0):.0f} MB liberados)."
929
+ )
930
+ messagebox.showinfo(_t("menu.clear_cache", "Limpar cache"), detail, parent=self._root)
931
+
932
+ def _word_count_dialog(self) -> None:
933
+ """Exibe a contagem de palavras, linhas e caracteres."""
934
+ e = self._e()
935
+ if not e:
936
+ return
937
+ t = self._tmgr.theme
938
+ try:
939
+ text = e.text.get(tk.SEL_FIRST, tk.SEL_LAST)
940
+ scope = "selection"
941
+ except tk.TclError:
942
+ text = e.get_content()
943
+ scope = "file"
944
+
945
+ words = len(re.findall(r"\S+", text))
946
+ lines = text.count("\n") + (1 if text else 0)
947
+ chars = len(text)
948
+ chars_ns = len(text.replace(" ", "").replace(
949
+ "\n", "").replace("\t", ""))
950
+
951
+ dlg = tk.Toplevel(self._root)
952
+ dlg.title(_t("ui.word_count_title"))
953
+ dlg.configure(bg=t.floating_bg)
954
+ dlg.resizable(False, False)
955
+ dlg.transient(self._root)
956
+ safe_grab_set(dlg)
957
+
958
+ tk.Label(
959
+ dlg,
960
+ text=f"📊 {_t('ui.word_count_title')} ({scope})",
961
+ bg=t.floating_bg,
962
+ fg=t.fg,
963
+ font=(FONT_UI, 12, "bold"),
964
+ ).pack(padx=20, pady=(14, 6))
965
+
966
+ body = _t("ui.word_count_body", w=words, l=lines, c=chars, cs=chars_ns)
967
+ tk.Label(
968
+ dlg,
969
+ text=body,
970
+ bg=t.editor_bg,
971
+ fg=t.fg,
972
+ font=(FONT_MONO, 10),
973
+ justify="left",
974
+ padx=16,
975
+ pady=10,
976
+ ).pack(fill="x", padx=12, pady=4)
977
+
978
+ tk.Label(
979
+ dlg,
980
+ text=_t("ui.ok"),
981
+ bg=t.btn_primary,
982
+ fg="#000",
983
+ font=(FONT_UI, 9, "bold"),
984
+ padx=20,
985
+ pady=4,
986
+ cursor="hand2",
987
+ ).pack(pady=(4, 14))
988
+ dlg.bind("<Return>", lambda _: dlg.destroy())
989
+ dlg.bind("<Escape>", lambda _: dlg.destroy())
990
+ dlg.winfo_children()[-1].bind("<Button-1>", lambda _: dlg.destroy())
991
+ self._center_dialog(dlg)
992
+
993
+ def _remove_duplicate_lines(self) -> None:
994
+ """Remove linhas duplicadas do arquivo ou seleção."""
995
+ e = self._e()
996
+ if not e:
997
+ return
998
+ content = e.get_content()
999
+ lines = content.splitlines()
1000
+ seen: set = set()
1001
+ unique = []
1002
+ for line in lines:
1003
+ if line not in seen:
1004
+ seen.add(line)
1005
+ unique.append(line)
1006
+ removed = len(lines) - len(unique)
1007
+ e.text.delete("1.0", "end")
1008
+ e.text.insert("1.0", "\n".join(unique))
1009
+ self._status.notify(_t("msg.dupes_removed", n=removed))
1010
+
1011
+ def _apply_codec(self, mode: str) -> None:
1012
+ """Aplica encode/decode (base64 ou url) à seleção do editor ativo.
1013
+
1014
+ Args:
1015
+ mode: ``"b64_enc"``, ``"b64_dec"``, ``"url_enc"`` ou ``"url_dec"``.
1016
+ """
1017
+ import base64
1018
+ from urllib.parse import quote, unquote
1019
+
1020
+ e = self._e()
1021
+ if not e:
1022
+ return
1023
+ try:
1024
+ sel = e.text.get(tk.SEL_FIRST, tk.SEL_LAST)
1025
+ except tk.TclError:
1026
+ self._status.notify(_t("msg.no_selection"), level="warn")
1027
+ return
1028
+
1029
+ try:
1030
+ if mode == "b64_enc":
1031
+ result = base64.b64encode(sel.encode()).decode()
1032
+ label = "encode"
1033
+ elif mode == "b64_dec":
1034
+ result = base64.b64decode(sel.encode()).decode()
1035
+ label = "decode"
1036
+ elif mode == "url_enc":
1037
+ result = quote(sel, safe="")
1038
+ label = "URL-encode"
1039
+ else:
1040
+ result = unquote(sel)
1041
+ label = "URL-decode"
1042
+ except (ValueError, UnicodeDecodeError):
1043
+ key = "err.invalid_base64" if mode.startswith(
1044
+ "b64") else "err.invalid_url"
1045
+ self._status.notify(_t(key), level="error")
1046
+ return
1047
+
1048
+ e.text.replace(tk.SEL_FIRST, tk.SEL_LAST, result)
1049
+ self._status.notify(_t("msg.base64_done", op=label))
1050
+
1051
+ def _base64_encode(self) -> None:
1052
+ self._apply_codec("b64_enc")
1053
+
1054
+ def _base64_decode(self) -> None:
1055
+ self._apply_codec("b64_dec")
1056
+
1057
+ def _url_encode(self) -> None:
1058
+ self._apply_codec("url_enc")
1059
+
1060
+ def _url_decode(self) -> None:
1061
+ self._apply_codec("url_dec")
1062
+
1063
+ def _hash_selection(self, algo: str) -> None:
1064
+ """Calcula o hash (MD5, SHA256) da seleção e copia para a área de transferência."""
1065
+ import hashlib
1066
+
1067
+ e = self._e()
1068
+ if not e:
1069
+ return
1070
+ try:
1071
+ sel = e.text.get(tk.SEL_FIRST, tk.SEL_LAST)
1072
+ except tk.TclError:
1073
+ sel = e.get_content()
1074
+ h = hashlib.new(algo, sel.encode(), usedforsecurity=False).hexdigest()
1075
+ self._root.clipboard_clear()
1076
+ self._root.clipboard_append(h)
1077
+
1078
+ t = self._tmgr.theme
1079
+ dlg = tk.Toplevel(self._root)
1080
+ dlg.title(f"{algo.upper()} Hash")
1081
+ dlg.configure(bg=t.floating_bg)
1082
+ dlg.resizable(False, False)
1083
+ dlg.transient(self._root)
1084
+ safe_grab_set(dlg)
1085
+ tk.Label(
1086
+ dlg,
1087
+ text=f" {algo.upper()} Hash ",
1088
+ bg=t.floating_bg,
1089
+ fg=t.fg,
1090
+ font=(FONT_UI, 11, "bold"),
1091
+ ).pack(padx=16, pady=(12, 4))
1092
+ tk.Label(
1093
+ dlg,
1094
+ text=h,
1095
+ bg=t.editor_bg,
1096
+ fg=t.t_string,
1097
+ font=(FONT_MONO, 9),
1098
+ padx=12,
1099
+ pady=8,
1100
+ wraplength=440,
1101
+ ).pack(fill="x", padx=12, pady=4)
1102
+ tk.Label(
1103
+ dlg,
1104
+ text=_t("msg.hash_done", algo=algo.upper()),
1105
+ bg=t.floating_bg,
1106
+ fg=t.ok_fg,
1107
+ font=(FONT_UI, 8),
1108
+ ).pack(pady=(0, 8))
1109
+ ok = tk.Label(
1110
+ dlg,
1111
+ text=_t("ui.ok"),
1112
+ bg=t.btn_primary,
1113
+ fg="#000",
1114
+ font=(FONT_UI, 9, "bold"),
1115
+ padx=20,
1116
+ pady=4,
1117
+ cursor="hand2",
1118
+ )
1119
+ ok.pack(pady=(0, 12))
1120
+ ok.bind("<Button-1>", lambda _: dlg.destroy())
1121
+ dlg.bind("<Return>", lambda _: dlg.destroy())
1122
+ dlg.bind("<Escape>", lambda _: dlg.destroy())
1123
+ self._center_dialog(dlg)
1124
+
1125
+ def _insert_sequence_dialog(self) -> None:
1126
+ """Insere uma sequência numérica no local do cursor."""
1127
+ t = self._tmgr.theme
1128
+ e = self._e()
1129
+ if not e:
1130
+ return
1131
+
1132
+ dlg = tk.Toplevel(self._root)
1133
+ dlg.title(_t("tools.insert_seq"))
1134
+ dlg.configure(bg=t.floating_bg)
1135
+ dlg.resizable(False, False)
1136
+ dlg.transient(self._root)
1137
+ safe_grab_set(dlg)
1138
+
1139
+ tk.Label(
1140
+ dlg,
1141
+ text=f" 🔢 {_t('tools.insert_seq')}",
1142
+ bg=t.floating_bg,
1143
+ fg=t.fg,
1144
+ font=(FONT_UI, 12, "bold"),
1145
+ ).pack(padx=16, pady=(12, 6))
1146
+
1147
+ ew = {
1148
+ "bg": t.input_bg,
1149
+ "fg": t.fg,
1150
+ "insertbackground": t.cursor,
1151
+ "relief": "flat",
1152
+ "bd": 0,
1153
+ "highlightthickness": 1,
1154
+ "highlightbackground": t.border,
1155
+ "font": (FONT_MONO, 10),
1156
+ "width": 12,
1157
+ }
1158
+
1159
+ start_var = tk.StringVar(value="1")
1160
+ step_var = tk.StringVar(value="1")
1161
+ count_var = tk.StringVar(value="10")
1162
+ pad_var = tk.BooleanVar(value=False)
1163
+
1164
+ for label_key, var in (
1165
+ (_t("ui.seq_start"), start_var),
1166
+ (_t("ui.seq_step"), step_var),
1167
+ ("Count", count_var),
1168
+ ):
1169
+ row = tk.Frame(dlg, bg=t.floating_bg)
1170
+ row.pack(fill="x", padx=16, pady=3)
1171
+ tk.Label(
1172
+ row,
1173
+ text=label_key + ":",
1174
+ bg=t.floating_bg,
1175
+ fg=t.fg_muted,
1176
+ font=(FONT_UI, 9),
1177
+ width=8,
1178
+ anchor="w",
1179
+ ).pack(side="left")
1180
+ tk.Entry(row, textvariable=var, **ew).pack(side="left")
1181
+
1182
+ pad_row = tk.Frame(dlg, bg=t.floating_bg)
1183
+ pad_row.pack(fill="x", padx=16, pady=3)
1184
+ tk.Checkbutton(
1185
+ pad_row,
1186
+ text=_t("ui.seq_pad"),
1187
+ variable=pad_var,
1188
+ bg=t.floating_bg,
1189
+ fg=t.fg,
1190
+ activebackground=t.floating_bg,
1191
+ selectcolor=t.sel_bg,
1192
+ font=(FONT_UI, 9),
1193
+ ).pack(side="left")
1194
+
1195
+ def _apply():
1196
+ with contextlib.suppress(ValueError):
1197
+ start = int(start_var.get())
1198
+ step = int(step_var.get())
1199
+ count = int(count_var.get())
1200
+ nums = [start + i * step for i in range(count)]
1201
+ if pad_var.get():
1202
+ w_max = len(str(max(abs(n) for n in nums)))
1203
+ strs = [str(n).zfill(w_max) for n in nums]
1204
+ else:
1205
+ strs = [str(n) for n in nums]
1206
+
1207
+ try:
1208
+ e.text.replace(tk.SEL_FIRST, tk.SEL_LAST, "\n".join(strs))
1209
+ except tk.TclError:
1210
+ e.text.insert(tk.INSERT, "\n".join(strs))
1211
+ self._status.notify(_t("msg.seq_inserted", n=count))
1212
+ dlg.destroy()
1213
+
1214
+ btn_row = tk.Frame(dlg, bg=t.floating_bg)
1215
+ btn_row.pack(pady=12)
1216
+ for text, cmd in (("Insert", _apply), ("Cancel", dlg.destroy)):
1217
+ tk.Label(
1218
+ btn_row,
1219
+ text=text,
1220
+ bg=t.btn_primary if text == "Insert" else t.btn_bg,
1221
+ fg="#000" if text == "Insert" else t.fg,
1222
+ font=(FONT_UI, 9, "bold"),
1223
+ padx=14,
1224
+ pady=4,
1225
+ cursor="hand2",
1226
+ ).pack(side="left", padx=4)
1227
+ btn_row.winfo_children(
1228
+ )[-1].bind("<Button-1>", lambda _, c=cmd: c())
1229
+ self._center_dialog(dlg)
1230
+
1231
+ def _open_color_picker(self) -> None:
1232
+ """Abre o seletor de cores com a cor sob o cursor (se houver)."""
1233
+ e = self._e()
1234
+ if not e:
1235
+ return
1236
+
1237
+ try:
1238
+ line_no = int(e.text.index(tk.INSERT).split(".")[0])
1239
+ line = e.text.get(f"{line_no}.0", f"{line_no}.end")
1240
+ col = int(e.text.index(tk.INSERT).split(".")[1])
1241
+ initial = "#4a9eff"
1242
+ for sc, ec, hex_c in detect_colors_in_line(line):
1243
+ if sc <= col <= ec:
1244
+ initial = hex_c
1245
+ break
1246
+ except (tk.TclError, ValueError):
1247
+ initial = "#4a9eff"
1248
+
1249
+ def _on_pick(hex_c: str) -> None:
1250
+ with contextlib.suppress(tk.TclError):
1251
+ e.text.insert(tk.INSERT, hex_c)
1252
+ self._root.clipboard_clear()
1253
+ self._root.clipboard_append(hex_c)
1254
+ self._status.notify(_t("msg.copied"))
1255
+
1256
+ ColorPickerPopup(self._root, self._tmgr, initial, _on_pick)
1257
+
1258
+ def _toggle_zen_mode(self) -> None:
1259
+ """Alterna o modo Zen (tela cheia sem distrações)."""
1260
+ self._zen_mode = not self._zen_mode
1261
+ t = self._tmgr.theme
1262
+
1263
+ if self._zen_mode:
1264
+ self._hide_sidebar()
1265
+ self._hide_bottom_panel()
1266
+ with contextlib.suppress(tk.TclError):
1267
+ if hasattr(self, "_sidebar_toggle_btn"):
1268
+ self._sidebar_toggle_btn.place_forget()
1269
+ if hasattr(self, "_panel_toggle_btn"):
1270
+ self._panel_toggle_btn.place_forget()
1271
+
1272
+ with contextlib.suppress(tk.TclError):
1273
+ self._h_paned.paneconfigure(self._actbar, minsize=0, width=0)
1274
+ self._h_paned.sash_place(0, 0, 0)
1275
+
1276
+ with contextlib.suppress(tk.TclError):
1277
+ self._root.attributes("-fullscreen", True)
1278
+
1279
+ self._zen_lbl = tk.Label(
1280
+ self._root,
1281
+ text=_t("ui.zen_mode") + " [Esc to exit]",
1282
+ bg=t.editor_bg,
1283
+ fg=t.fg_muted,
1284
+ font=(FONT_UI, 8),
1285
+ )
1286
+
1287
+ self._zen_lbl.place(relx=0.5, rely=1.0, anchor="s", y=-4)
1288
+ self._zen_lbl.lift()
1289
+ self._status.notify(_t("msg.zen_on"))
1290
+ self._root.bind("<Escape>", lambda _: self._toggle_zen_mode())
1291
+ with contextlib.suppress(tk.TclError):
1292
+ self._zen_media_autoplay()
1293
+ else:
1294
+ with contextlib.suppress(tk.TclError):
1295
+ self._root.attributes("-fullscreen", False)
1296
+ self._show_sidebar()
1297
+ self._show_bottom_panel()
1298
+
1299
+ with contextlib.suppress(tk.TclError):
1300
+ self._h_paned.paneconfigure(self._actbar, minsize=48, width=48)
1301
+ self._h_paned.sash_place(0, 48, 0)
1302
+
1303
+ with contextlib.suppress(tk.TclError):
1304
+ if hasattr(self, "_sidebar_toggle_btn"):
1305
+ self._sidebar_toggle_btn.place(x=48, rely=0.5, anchor="w")
1306
+ self._sidebar_toggle_btn.lift()
1307
+ if hasattr(self, "_panel_toggle_btn"):
1308
+ self._panel_toggle_btn.place(
1309
+ relx=1.0, rely=1.0, anchor="se", x=-2, y=-26
1310
+ )
1311
+ self._panel_toggle_btn.lift()
1312
+ if hasattr(self, "_zen_lbl") and self._zen_lbl.winfo_exists():
1313
+ self._zen_lbl.destroy()
1314
+ self._status.notify(_t("msg.zen_off"))
1315
+ self._root.bind("<Escape>", self._on_escape)
1316
+ with contextlib.suppress(tk.TclError):
1317
+ self._zen_media_stop_hud()
1318
+
1319
+ def _toggle_focus_mode(self) -> None:
1320
+ """Alterna o modo foco (escurece abas inativas)."""
1321
+ self._focus_mode = not self._focus_mode
1322
+ self._apply_focus_mode()
1323
+ msg = _t("msg.focus_on") if self._focus_mode else _t("msg.focus_off")
1324
+ self._status.notify(msg)
1325
+
1326
+ def _apply_focus_mode(self) -> None:
1327
+ """Aplica o efeito visual do modo foco."""
1328
+ if not hasattr(self, "_editors"):
1329
+ return
1330
+ t = self._tmgr.theme
1331
+ for i, ed in enumerate(self._editors):
1332
+ active = i == self._active_idx
1333
+ with contextlib.suppress(tk.TclError):
1334
+ bg = t.editor_bg if active or not self._focus_mode else t.bg
1335
+ ed.text.config(bg=bg)
1336
+
1337
+ def _toggle_read_only(self) -> None:
1338
+ """Alterna o modo somente leitura no editor ativo."""
1339
+ e = self._e()
1340
+ if not e:
1341
+ return
1342
+ current = str(e.text.cget("state")) == "disabled"
1343
+ if current:
1344
+ e.text.config(state="normal")
1345
+ self._status.notify(_t("msg.read_only_off"))
1346
+ else:
1347
+ e.text.config(state="disabled")
1348
+ self._status.notify(_t("msg.read_only_on"))
1349
+ self._update_status_bar()
1350
+
1351
+ def _toggle_overwrite_mode(self) -> None:
1352
+ """Alterna o modo sobrescrita (overwrite) no editor ativo."""
1353
+ e = self._e()
1354
+ if not e:
1355
+ return
1356
+
1357
+ ovr = not getattr(e, "_overwrite", False)
1358
+ e._overwrite = ovr
1359
+
1360
+ if ovr:
1361
+
1362
+ def _ovr_key(event):
1363
+ if event.char and event.char.isprintable():
1364
+ with contextlib.suppress(tk.TclError):
1365
+ e.text.delete(tk.INSERT, f"{tk.INSERT}+1c")
1366
+
1367
+ e.text.bind("<KeyPress>", _ovr_key, add="+")
1368
+ else:
1369
+ e.text.unbind("<KeyPress>")
1370
+ self._update_status_bar()
1371
+
1372
+ def _add_bookmark(self) -> None:
1373
+ """Adiciona um marcador na linha atual."""
1374
+ e = self._e()
1375
+ if not e or not e.path:
1376
+ return
1377
+ t = self._tmgr.theme
1378
+ try:
1379
+ line_no = int(e.text.index(tk.INSERT).split(".")[0])
1380
+ col_no = int(e.text.index(tk.INSERT).split(".")[1])
1381
+ snippet = e.text.get(f"{line_no}.0", f"{line_no}.end").strip()
1382
+ except (tk.TclError, ValueError):
1383
+ return
1384
+
1385
+ dlg = tk.Toplevel(self._root)
1386
+ dlg.title(_t("ui.bookmark_title"))
1387
+ dlg.configure(bg=t.floating_bg)
1388
+ dlg.resizable(False, False)
1389
+ dlg.transient(self._root)
1390
+ safe_grab_set(dlg)
1391
+
1392
+ tk.Label(
1393
+ dlg,
1394
+ text=f" 🔖 {_t('ui.bookmark_title')} - line {line_no}",
1395
+ bg=t.floating_bg,
1396
+ fg=t.fg,
1397
+ font=(FONT_UI, 11, "bold"),
1398
+ ).pack(padx=16, pady=(12, 4))
1399
+ tk.Label(
1400
+ dlg,
1401
+ text=snippet[:60],
1402
+ bg=t.editor_bg,
1403
+ fg=t.fg_muted,
1404
+ font=(FONT_MONO, 9),
1405
+ padx=12,
1406
+ pady=4,
1407
+ ).pack(fill="x", padx=12, pady=2)
1408
+ tk.Label(
1409
+ dlg,
1410
+ text=_t("ui.bookmark_note") + ":",
1411
+ bg=t.floating_bg,
1412
+ fg=t.fg_muted,
1413
+ font=(FONT_UI, 9),
1414
+ ).pack(anchor="w", padx=16, pady=(6, 0))
1415
+
1416
+ note_var = tk.StringVar()
1417
+ note_e = tk.Entry(
1418
+ dlg,
1419
+ textvariable=note_var,
1420
+ bg=t.input_bg,
1421
+ fg=t.fg,
1422
+ insertbackground=t.cursor,
1423
+ relief="flat",
1424
+ bd=0,
1425
+ highlightthickness=1,
1426
+ highlightbackground=t.border,
1427
+ font=(FONT_UI, 10),
1428
+ )
1429
+ note_e.pack(fill="x", padx=16, pady=4)
1430
+ note_e.focus_set()
1431
+
1432
+ def _save():
1433
+ self._bookmark_mgr.add(
1434
+ str(e.path), line_no, col_no, snippet, note_var.get()
1435
+ )
1436
+
1437
+ with contextlib.suppress(tk.TclError):
1438
+ self._bookmarks_panel.refresh()
1439
+ self._status.notify(_t("msg.bookmark_added"))
1440
+ dlg.destroy()
1441
+
1442
+ btn_row = tk.Frame(dlg, bg=t.floating_bg)
1443
+ btn_row.pack(pady=10)
1444
+ for text, cmd in ((_t("ui.bookmark_add"), _save), ("Cancel", dlg.destroy)):
1445
+ btn = tk.Label(
1446
+ btn_row,
1447
+ text=text,
1448
+ bg=t.btn_primary if text != "Cancel" else t.btn_bg,
1449
+ fg="#000" if text != "Cancel" else t.fg,
1450
+ font=(FONT_UI, 9, "bold"),
1451
+ padx=14,
1452
+ pady=4,
1453
+ cursor="hand2",
1454
+ )
1455
+ btn.pack(side="left", padx=4)
1456
+ btn.bind("<Button-1>", lambda _, c=cmd: c())
1457
+ note_e.bind("<Return>", lambda _: _save())
1458
+ dlg.bind("<Escape>", lambda _: dlg.destroy())
1459
+ self._center_dialog(dlg)
1460
+
1461
+ def _next_bookmark(self) -> None:
1462
+ """Vai para o próximo marcador no arquivo atual."""
1463
+ e = self._e()
1464
+ if not e or not e.path:
1465
+ return
1466
+ try:
1467
+ cur = int(e.text.index(tk.INSERT).split(".")[0])
1468
+ except (tk.TclError, ValueError):
1469
+ cur = 0
1470
+ bm = self._bookmark_mgr.next_bookmark(str(e.path), cur)
1471
+ if bm:
1472
+ e.goto_line(bm["line"], bm["col"])
1473
+ self._status.notify(
1474
+ f"🔖 {bm.get('note', '') or bm['snippet'][:40]}")
1475
+
1476
+ def _prev_bookmark(self) -> None:
1477
+ """Vai para o marcador anterior no arquivo atual."""
1478
+ e = self._e()
1479
+ if not e or not e.path:
1480
+ return
1481
+ try:
1482
+ cur = int(e.text.index(tk.INSERT).split(".")[0])
1483
+ except (tk.TclError, ValueError):
1484
+ cur = 99999
1485
+ bm = self._bookmark_mgr.prev_bookmark(str(e.path), cur)
1486
+ if bm:
1487
+ e.goto_line(bm["line"], bm["col"])
1488
+ self._status.notify(
1489
+ f"🔖 {bm.get('note', '') or bm['snippet'][:40]}")
1490
+
1491
+ def _open_session_notes(self) -> None:
1492
+ """Abre uma janela flutuante de notas persistente por workspace."""
1493
+ import hashlib as _hl
1494
+
1495
+ existing = getattr(self, "_notes_win", None)
1496
+ if existing is not None:
1497
+ with contextlib.suppress(tk.TclError):
1498
+ if existing.winfo_exists():
1499
+ existing.deiconify()
1500
+ existing.focus_force()
1501
+ return
1502
+
1503
+ t = self._tmgr.theme
1504
+ ws_key = _hl.md5(
1505
+ str(self._workspace or "global").encode(), usedforsecurity=False
1506
+ ).hexdigest()[:8]
1507
+ notes_file = Path.home() / ".codis" / f"notes_{ws_key}.txt"
1508
+
1509
+ dlg = tk.Toplevel(self._root)
1510
+ self._notes_win = dlg
1511
+ dlg.title(_t("ui.notes_title"))
1512
+ dlg.configure(bg=t.floating_bg)
1513
+ dlg.geometry("360x280")
1514
+ dlg.resizable(True, True)
1515
+
1516
+ tk.Label(
1517
+ dlg,
1518
+ text=f" 📝 {_t('ui.notes_title')}",
1519
+ bg=t.activity_bg,
1520
+ fg=t.fg,
1521
+ font=(FONT_UI, 9, "bold"),
1522
+ anchor="w",
1523
+ height=2,
1524
+ ).pack(fill="x")
1525
+
1526
+ saved_lbl = tk.Label(
1527
+ dlg, text="", bg=t.floating_bg, fg=t.ok_fg, font=(FONT_UI, 7)
1528
+ )
1529
+ saved_lbl.pack(anchor="e", padx=8)
1530
+
1531
+ txt = tk.Text(
1532
+ dlg,
1533
+ bg=t.editor_bg,
1534
+ fg=t.fg,
1535
+ insertbackground=t.cursor,
1536
+ font=(FONT_MONO, 10),
1537
+ relief="flat",
1538
+ bd=0,
1539
+ padx=8,
1540
+ pady=6,
1541
+ wrap="word",
1542
+ undo=True,
1543
+ )
1544
+ txt.pack(fill="both", expand=True, padx=4, pady=4)
1545
+
1546
+ with contextlib.suppress(tk.TclError):
1547
+ if notes_file.exists():
1548
+ txt.insert("1.0", notes_file.read_text(encoding="utf-8"))
1549
+
1550
+ def _do_save():
1551
+ with contextlib.suppress(OSError, tk.TclError):
1552
+ notes_file.parent.mkdir(parents=True, exist_ok=True)
1553
+ notes_file.write_text(
1554
+ txt.get("1.0", "end-1c"), encoding="utf-8")
1555
+ saved_lbl.config(text=_t("ui.notes_saved"))
1556
+
1557
+ from src.ui._perf_utils import debounce_fn
1558
+
1559
+ _autosave = debounce_fn(dlg, _do_save, ms=600)
1560
+
1561
+ def _on_key(*_):
1562
+ saved_lbl.config(text="...")
1563
+ _autosave()
1564
+
1565
+ txt.bind("<KeyRelease>", _on_key)
1566
+
1567
+ def _regex_replace(self, pattern: str, replacement: str, flags_str: str) -> None:
1568
+ """Aplica substituição por expressão regular no conteúdo do editor."""
1569
+ e = self._e()
1570
+ if not e:
1571
+ return
1572
+ flags = 0
1573
+ if "i" in flags_str.lower():
1574
+ flags |= re.IGNORECASE
1575
+ if "m" in flags_str.lower():
1576
+ flags |= re.MULTILINE
1577
+ if "s" in flags_str.lower():
1578
+ flags |= re.DOTALL
1579
+ try:
1580
+ rx = re.compile(pattern, flags)
1581
+ content = e.get_content()
1582
+ new_content, n = rx.subn(replacement, content)
1583
+ if n:
1584
+ e.text.delete("1.0", "end")
1585
+ e.text.insert("1.0", new_content)
1586
+ self._status.notify(f"{n} substituição(ões) realizada(s)")
1587
+ except re.error as err:
1588
+ self._status.notify(
1589
+ _t("err.invalid_regex", err=err), level="error")
1590
+
1591
+ def _paste_history_dialog(self) -> None:
1592
+ """Abre o diálogo de histórico de área de transferência com busca e inserção."""
1593
+ import time as _time
1594
+
1595
+ t = self._tmgr.theme
1596
+ e = self._e()
1597
+ history: list = getattr(self, "_copy_history", [])
1598
+
1599
+ dlg = tk.Toplevel(self._root)
1600
+ dlg.title(_t("ui.copy_history_title"))
1601
+ dlg.configure(bg=t.floating_bg)
1602
+ dlg.geometry("560x380")
1603
+ dlg.transient(self._root)
1604
+ safe_grab_set(dlg)
1605
+
1606
+ tk.Label(
1607
+ dlg,
1608
+ text=f" 📋 {_t('ui.copy_history_title')}",
1609
+ bg=t.activity_bg,
1610
+ fg=t.fg,
1611
+ font=(FONT_UI, 10, "bold"),
1612
+ height=2,
1613
+ ).pack(fill="x")
1614
+
1615
+ frame = tk.Frame(dlg, bg=t.editor_bg)
1616
+ frame.pack(fill="both", expand=True, padx=8, pady=(8, 0))
1617
+
1618
+ scrollbar = tk.Scrollbar(frame, orient="vertical")
1619
+ listbox = tk.Listbox(
1620
+ frame,
1621
+ bg=t.editor_bg,
1622
+ fg=t.fg,
1623
+ selectbackground=t.sel_bg,
1624
+ selectforeground=t.sel_fg,
1625
+ font=(FONT_MONO, 9),
1626
+ relief="flat",
1627
+ activestyle="none",
1628
+ highlightthickness=0,
1629
+ yscrollcommand=scrollbar.set,
1630
+ )
1631
+ scrollbar.config(command=listbox.yview)
1632
+ scrollbar.pack(side="right", fill="y")
1633
+ listbox.pack(side="left", fill="both", expand=True)
1634
+
1635
+ if not history:
1636
+ listbox.insert("end", f" {_t('ui.paste_history_empty')}")
1637
+ else:
1638
+ for entry in history[:50]:
1639
+ ts = _time.strftime(
1640
+ "%H:%M:%S", _time.localtime(entry.timestamp))
1641
+ icon = "✂" if entry.kind == "cut" else "⎘"
1642
+ preview = entry.text.replace("\n", "↵")[:72]
1643
+ listbox.insert("end", f" {icon} {ts} {preview}")
1644
+
1645
+ def _paste_selected(_ev=None):
1646
+ sel = listbox.curselection()
1647
+ if not sel or not history:
1648
+ return
1649
+ idx = sel[0]
1650
+ if 0 <= idx < len(history) and e:
1651
+ with contextlib.suppress(tk.TclError):
1652
+ if e.text.tag_ranges(tk.SEL):
1653
+ e.text.delete(tk.SEL_FIRST, tk.SEL_LAST)
1654
+ e.text.insert(tk.INSERT, history[idx].text)
1655
+ dlg.destroy()
1656
+
1657
+ def _clear_history(_ev=None):
1658
+ self._copy_history.clear()
1659
+ dlg.destroy()
1660
+
1661
+ btn_row = tk.Frame(dlg, bg=t.floating_bg)
1662
+ btn_row.pack(pady=6)
1663
+ for label, cmd, primary in (
1664
+ (_t("ui.copy_history_paste"), _paste_selected, True),
1665
+ (_t("ui.copy_history_clear"), _clear_history, False),
1666
+ (_t("ui.copy_history_cancel"), dlg.destroy, False),
1667
+ ):
1668
+ btn = tk.Label(
1669
+ btn_row,
1670
+ text=label,
1671
+ bg=t.btn_primary if primary else t.btn_bg,
1672
+ fg="#000" if primary else t.fg,
1673
+ font=(FONT_UI, 9, "bold"),
1674
+ padx=14,
1675
+ pady=4,
1676
+ cursor="hand2",
1677
+ )
1678
+ btn.pack(side="left", padx=4)
1679
+ btn.bind("<Button-1>", lambda _, c=cmd: c())
1680
+ listbox.bind("<Double-Button-1>", _paste_selected)
1681
+ listbox.bind("<Return>", _paste_selected)
1682
+ dlg.bind("<Escape>", lambda _: dlg.destroy())
1683
+ self._center_dialog(dlg)
1684
+
1685
+ def _center_dialog(self, dlg: tk.Toplevel) -> None:
1686
+ """Centraliza um diálogo em relação à janela principal."""
1687
+ dlg.update_idletasks()
1688
+ w, h = dlg.winfo_reqwidth(), dlg.winfo_reqheight()
1689
+ x = self._root.winfo_x() + (self._root.winfo_width() - w) // 2
1690
+ y = self._root.winfo_y() + (self._root.winfo_height() - h) // 2
1691
+ dlg.geometry(f"+{x}+{y}")
1692
+
1693
+ def _save_layout(self) -> None:
1694
+ """Persiste largura da sidebar e altura do painel na configuração."""
1695
+ with contextlib.suppress(tk.TclError, AttributeError):
1696
+ w = self._sidebar.winfo_width()
1697
+ if w > 60 and (self._sidebar_visible or not self._dock.floating):
1698
+ self._cfg.set("sidebar_width", w)
1699
+ with contextlib.suppress(tk.TclError, AttributeError):
1700
+ self._cfg.set("panel_height", self._bottom_frame.winfo_height())
1701
+
1702
+ def _restart_process(self) -> None:
1703
+ """Reinicia o Codis, encerrando antes tudo o que esta instância mantinha vivo.
1704
+
1705
+ Salva layout, sessão e configuração, desliga os serviços (LSP, terminais,
1706
+ depuração, tarefas de Git e IA) e só então inicia a nova instância. No
1707
+ POSIX, ``os.execv`` troca a imagem do processo, então o PID continua o mesmo
1708
+ e não sobra instância antiga. No Windows, que não tem ``exec``, a nova
1709
+ instância é lançada e este processo sai na hora com ``os._exit``.
1710
+ """
1711
+ has_unsaved = any(e.modified for e in self._editors)
1712
+ if not has_unsaved and not messagebox.askyesno(
1713
+ _t("file.restart"),
1714
+ _t("ui.confirm_restart", "Reiniciar o Codis agora?"),
1715
+ parent=self._root,
1716
+ ):
1717
+ return
1718
+ if not self._resolve_unsaved():
1719
+ return
1720
+
1721
+ from src.pyexec import restart_command
1722
+
1723
+ cmd = restart_command()
1724
+ if not os.access(cmd[0], os.X_OK):
1725
+ messagebox.showerror(
1726
+ _t("file.restart"), f"Executável não encontrado: {cmd[0]}", parent=self._root
1727
+ )
1728
+ return
1729
+
1730
+ self._fire_hook("app_exit")
1731
+ with contextlib.suppress(Exception):
1732
+ self._recovery_end(keep=False)
1733
+ self._save_layout()
1734
+ self._save_session()
1735
+ self._cfg.save()
1736
+ self._shutdown_services()
1737
+
1738
+ try:
1739
+ if sys.platform == "win32":
1740
+ flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
1741
+ subprocess.Popen(cmd, creationflags=flags, close_fds=True)
1742
+ with contextlib.suppress(Exception):
1743
+ logging.shutdown()
1744
+ os._exit(0)
1745
+ os.execv(cmd[0], cmd)
1746
+ except OSError as exc:
1747
+ messagebox.showerror(_t("file.restart"), str(exc), parent=self._root)
1748
+
1749
+ @staticmethod
1750
+ def _arm_exit_watchdog(seconds: float = 5.0) -> None:
1751
+ """Garante que o processo termine mesmo se algo segurar o encerramento.
1752
+
1753
+ Uma thread daemon dorme por ``seconds`` e então força a saída com
1754
+ ``os._exit``. Se o interpretador finalizar antes, ela morre junto, sem
1755
+ efeito. Cobre threads de terceiros, pools de workers e subprocessos
1756
+ que impediriam o Python de sair sozinho.
1757
+ """
1758
+
1759
+ def _force_exit() -> None:
1760
+ time.sleep(seconds)
1761
+ logger.warning("Encerramento passou de %.0fs; forçando saída.", seconds)
1762
+ with contextlib.suppress(Exception):
1763
+ logging.shutdown()
1764
+ os._exit(0)
1765
+
1766
+ threading.Thread(target=_force_exit, daemon=True, name="codis-exit-watchdog").start()
1767
+
1768
+ def _shutdown_services(self) -> None:
1769
+ """Para todos os serviços em background antes de encerrar a aplicação."""
1770
+ # O player de mídia vai primeiro: precisa largar a janela de vídeo
1771
+ # antes de o Tk destruí-la.
1772
+ with contextlib.suppress(Exception):
1773
+ if self._zen_media_player is not None:
1774
+ self._zen_media_player.shutdown()
1775
+ with contextlib.suppress(Exception):
1776
+ from src.events import bus as event_bus
1777
+
1778
+ event_bus.shutdown()
1779
+ with contextlib.suppress(Exception):
1780
+ from src.ui.k_ui._perf import shutdown_physics_executor
1781
+
1782
+ shutdown_physics_executor()
1783
+ with contextlib.suppress(Exception):
1784
+ if getattr(self, "_panel_detach", None):
1785
+ self._panel_detach.close_all()
1786
+ with contextlib.suppress(Exception):
1787
+ if self._ext_code is not None:
1788
+ self._ext_code.stop_all()
1789
+ with contextlib.suppress(Exception):
1790
+ if self._lsp_mgr:
1791
+ self._lsp_mgr.stop_all()
1792
+ with contextlib.suppress(Exception):
1793
+ if self._autosave_job:
1794
+ self._root.after_cancel(self._autosave_job)
1795
+ with contextlib.suppress(Exception):
1796
+ self._lint_mgr.cancel()
1797
+
1798
+ with contextlib.suppress(Exception):
1799
+ if self._kui and getattr(self._kui, "_enabled", False):
1800
+ kui = self._kui
1801
+ for attr in ("_topbar", "_tabbar_w", "_stbar", "_engine"):
1802
+ w = getattr(kui, attr, None)
1803
+ if w and hasattr(w, "stop"):
1804
+ with contextlib.suppress(Exception):
1805
+ w.stop()
1806
+
1807
+ with contextlib.suppress(Exception):
1808
+ if hasattr(self, "_terminal") and self._terminal:
1809
+ self._terminal.destroy()
1810
+
1811
+ with contextlib.suppress(Exception):
1812
+ proc = getattr(getattr(self, "_debug_panel", None), "_proc", None)
1813
+ if proc:
1814
+ proc.terminate()
1815
+
1816
+ # Último passo: o que sobrou registrado (Git, IA, build, depuração...) é encerrado
1817
+ # com a árvore de filhos. Janelas abertas por "Nova janela" não entram aqui.
1818
+ with contextlib.suppress(Exception):
1819
+ proc_registry.stop_all(grace=1.5)
1820
+
1821
+ def _resolve_unsaved(self) -> bool:
1822
+ """Aplica ``exit_save_mode`` aos editores com alterações pendentes.
1823
+
1824
+ * ``ask`` - pergunta (Sim = salvar, Não = descartar, Cancelar = ficar);
1825
+ * ``save`` - salva tudo sem perguntar;
1826
+ * ``discard`` - não salva nada e não pergunta.
1827
+
1828
+ Se algum salvamento falhar (ou o diálogo "Salvar como" de um arquivo sem
1829
+ nome for cancelado) pergunta antes de sair, em vez de perder dados em
1830
+ silêncio. Retorna ``True`` quando é seguro prosseguir.
1831
+ """
1832
+ unsaved = [e for e in self._editors if e.modified]
1833
+ if not unsaved:
1834
+ return True
1835
+ mode = self._cfg.get("exit_save_mode", "ask")
1836
+ if mode == "ask":
1837
+ names = ", ".join(e.path.name if e.path else _t("ui.tab_untitled") for e in unsaved)
1838
+ ans = messagebox.askyesnocancel(
1839
+ _t("ui.unsaved_changes_title"),
1840
+ _t("ui.confirm_exit") + f"\n\n{names}",
1841
+ parent=self._root,
1842
+ )
1843
+ if ans is None:
1844
+ return False
1845
+ mode = "save" if ans else "discard"
1846
+ if mode == "discard":
1847
+ return True
1848
+ failed: list[str] = []
1849
+ for e in unsaved:
1850
+ fname = e.path.name if e.path else _t("ui.tab_untitled")
1851
+ try:
1852
+ ok = e.save() is not False
1853
+ except Exception as exc:
1854
+ logger.warning("Falha ao salvar '%s' no encerramento: %s", fname, exc)
1855
+ ok = False
1856
+ if not ok:
1857
+ failed.append(fname)
1858
+ if failed:
1859
+ leave = messagebox.askyesno(
1860
+ _t("ui.unsaved_changes_title"),
1861
+ _t("ui.exit_save_failed", names=", ".join(failed),
1862
+ default="Não foi possível salvar:\n{names}\n\nSair mesmo assim e perder essas alterações?"),
1863
+ icon="warning",
1864
+ parent=self._root,
1865
+ )
1866
+ # Se o usuário sai mesmo assim, as cópias de recuperação são a única cópia do texto.
1867
+ self._keep_recovery_on_exit = bool(leave)
1868
+ return bool(leave)
1869
+ return True
1870
+
1871
+ def _persist_session_on_exit(self) -> None:
1872
+ """Grava (ou apaga) a sessão conforme ``session_save_on_exit``."""
1873
+ if self._cfg.get("session_save_on_exit", True):
1874
+ self._save_session()
1875
+ else:
1876
+ with contextlib.suppress(OSError):
1877
+ SESSIONS_FILE.unlink(missing_ok=True)
1878
+
1879
+ def _on_exit(self) -> None:
1880
+ """Fecha a aplicação respeitando ``exit_save_mode`` e ``session_save_on_exit``."""
1881
+ if not self._resolve_unsaved():
1882
+ return
1883
+ self._fire_hook("app_exit")
1884
+ with contextlib.suppress(Exception):
1885
+ self._recovery_end(keep=getattr(self, "_keep_recovery_on_exit", False))
1886
+
1887
+ if self._dual_mode:
1888
+ with contextlib.suppress(Exception):
1889
+ self._close_dual_mode()
1890
+
1891
+ with contextlib.suppress(Exception):
1892
+ self._save_layout()
1893
+ with contextlib.suppress(Exception):
1894
+ self._persist_session_on_exit()
1895
+ with contextlib.suppress(Exception):
1896
+ self._cfg.save()
1897
+
1898
+ self._arm_exit_watchdog()
1899
+ self._shutdown_services()
1900
+
1901
+ try:
1902
+ self._root.destroy()
1903
+ except Exception as exc:
1904
+ logger.debug("Erro ao destruir root: %s", exc)
1905
+ try:
1906
+ sys.exit(0)
1907
+ except SystemExit: # pylint: disable=try-except-raise
1908
+ raise
1909
+ except Exception:
1910
+ os._exit(0)
1911
+
1912
+ def _open_remote_ssh(self) -> None:
1913
+ """Abre o Explorador de Arquivos Remotos (SSH/SFTP/FTP/HTTP/WebDAV)."""
1914
+ try:
1915
+ from src.ui.remote_browser import RemoteBrowserPanel
1916
+
1917
+ if hasattr(self, "_rbrowser_win") and self._rbrowser_win.winfo_exists():
1918
+ self._rbrowser_win.deiconify()
1919
+ self._rbrowser_win.focus_force()
1920
+ return
1921
+ self._rbrowser_win = tk.Toplevel(self._root)
1922
+ self._rbrowser_win.title(
1923
+ _t("rbrowser.window_title", "Codis - Arquivos Remotos")
1924
+ )
1925
+ from src.ui.remote_browser import fit_toplevel
1926
+
1927
+ fit_toplevel(self._rbrowser_win, 960, 660)
1928
+ self._rbrowser_win.config(bg=self._tmgr.theme.sidebar_bg)
1929
+ self._rbrowser_panel = RemoteBrowserPanel(
1930
+ self._rbrowser_win,
1931
+ self._tmgr,
1932
+ self._cfg,
1933
+ open_file_cb=lambda p: self._open_file(p, adopt_workspace=False),
1934
+ )
1935
+ self._rbrowser_panel.pack(fill="both", expand=True)
1936
+ self._rbrowser_win.focus_force()
1937
+ except Exception as exc:
1938
+ logger.warning("RemoteBrowserPanel não disponível: %s", exc)
1939
+ messagebox.showerror(
1940
+ _t("rbrowser.title", "Arquivos Remotos"),
1941
+ f"Painel não pôde ser aberto:\n{exc}",
1942
+ )
1943
+
1944
+ def _open_chat(self) -> None:
1945
+ """Abre o Painel de Chat Universal (IRC, WebSocket, Codis)."""
1946
+ try:
1947
+ from src.ui.chat_panel import ChatPanel
1948
+
1949
+ if hasattr(self, "_chat_win") and self._chat_win.winfo_exists():
1950
+ self._chat_win.deiconify()
1951
+ self._chat_win.focus_force()
1952
+ return
1953
+ self._chat_win = tk.Toplevel(self._root)
1954
+ self._chat_win.title(_t("chat.window_title", "Codis - Chat"))
1955
+ self._chat_win.geometry("1000x660")
1956
+ self._chat_win.minsize(640, 420)
1957
+ self._chat_win.config(bg=self._tmgr.theme.sidebar_bg)
1958
+ self._chat_panel = ChatPanel(self._chat_win, self._tmgr, self._cfg)
1959
+ self._chat_panel.pack(fill="both", expand=True)
1960
+ self._chat_win.protocol("WM_DELETE_WINDOW", lambda: (self._chat_panel.shutdown(), self._chat_win.destroy()))
1961
+ self._chat_win.focus_force()
1962
+ except Exception as exc:
1963
+ logger.warning("ChatPanel não disponível: %s", exc)
1964
+ messagebox.showerror(
1965
+ _t("chat.title", "Chat"), f"Painel não pôde ser aberto:\n{exc}"
1966
+ )
1967
+
1968
+ def _open_collab(self) -> None:
1969
+ """Abre o Painel de Colaboração em Tempo Real."""
1970
+ try:
1971
+ from src.ui.collab_panel import CollabPanel
1972
+
1973
+ if hasattr(self, "_collab_win") and self._collab_win.winfo_exists():
1974
+ self._collab_win.deiconify()
1975
+ self._collab_win.focus_force()
1976
+ return
1977
+ self._collab_win = tk.Toplevel(self._root)
1978
+ self._collab_win.title(
1979
+ _t("collab.window_title", "Codis - Colaboração"))
1980
+ self._collab_win.geometry("480x760")
1981
+ self._collab_win.config(bg=self._tmgr.theme.sidebar_bg)
1982
+
1983
+ def _get_editor_widget() -> tk.Text | None:
1984
+ """``tk.Text`` da aba ativa (o EditorPane não expõe get/insert)."""
1985
+ pane = self._e()
1986
+ return pane.text if pane is not None else None
1987
+
1988
+ def _new_editor() -> tk.Text | None:
1989
+ """Abre uma aba nova (sem sobrescrever o arquivo aberto) ao entrar numa sala."""
1990
+ pane = self.new_file()
1991
+ return pane.text if pane is not None else None
1992
+
1993
+ def _close_collab() -> None:
1994
+ with contextlib.suppress(Exception):
1995
+ self._collab_panel.disconnect()
1996
+ with contextlib.suppress(tk.TclError):
1997
+ self._collab_win.destroy()
1998
+
1999
+ self._collab_win.protocol("WM_DELETE_WINDOW", _close_collab)
2000
+ self._collab_panel = CollabPanel(
2001
+ self._collab_win,
2002
+ self._tmgr,
2003
+ self._cfg,
2004
+ get_editor_widget=_get_editor_widget,
2005
+ new_editor=_new_editor,
2006
+ )
2007
+ self._collab_panel.pack(fill="both", expand=True)
2008
+ self._collab_win.focus_force()
2009
+ except Exception as exc:
2010
+ logger.warning("CollabPanel não disponível: %s", exc)
2011
+ messagebox.showerror(
2012
+ _t("collab.title",
2013
+ "Colaboração"), f"Painel não pôde ser aberto:\n{exc}"
2014
+ )
2015
+
2016
+ def _open_accessibility(self) -> None:
2017
+ """Abre o painel de configuração de Acessibilidade."""
2018
+ try:
2019
+ from src.ui.accessibility import AccessibilityManager, AccessibilityPanel
2020
+
2021
+ existing = getattr(self, "_a11y_panel", None)
2022
+ if existing is not None:
2023
+ with contextlib.suppress(tk.TclError):
2024
+ if existing.winfo_exists():
2025
+ existing.deiconify()
2026
+ existing.focus_force()
2027
+ return
2028
+
2029
+ if not hasattr(self, "_a11y_mgr"):
2030
+ self._a11y_mgr = AccessibilityManager(
2031
+ self, self._cfg, self._tmgr)
2032
+ panel = AccessibilityPanel(self._root, self._a11y_mgr, self._tmgr)
2033
+ self._a11y_panel = panel
2034
+ panel.focus_force()
2035
+ except Exception as exc:
2036
+ logger.warning("Painel de acessibilidade não disponível: %s", exc)
2037
+
2038
+ def _init_accessibility(self) -> None:
2039
+ """Inicializa AccessibilityManager na startup se configurado."""
2040
+ try:
2041
+ from src.ui.accessibility import AccessibilityManager
2042
+
2043
+ self._a11y_mgr = AccessibilityManager(self, self._cfg, self._tmgr)
2044
+ except Exception as exc:
2045
+ logger.debug("A11y init: %s", exc)
2046
+
2047
+ def _init_performance_monitor(self) -> None:
2048
+ """Monitora travamentos da UI e aplica modo performance automaticamente.
2049
+
2050
+ Usa um thread de background com ping-pong no main thread via after().
2051
+ Se o main thread travar, o ping para de chegar e o monitor detecta o lag.
2052
+
2053
+ - Ping a cada 150ms
2054
+ - Período de graça de 20s na inicialização
2055
+ - Back-off exponencial: após detectar travamento, a espera cresce
2056
+ até 60s antes de aplicar de novo (evita modo perf piscando)
2057
+ - Quando o sistema se recupera, reduz o back-off
2058
+ - Usa threading.Event para parada limpa no shutdown
2059
+ """
2060
+ if not self._cfg.get("perf_auto_mode", True):
2061
+ return
2062
+ threshold_ms = int(self._cfg.get("perf_freeze_threshold_ms", 500))
2063
+
2064
+ _stop_event = threading.Event()
2065
+ if not hasattr(self, "_perf_mon_stop"):
2066
+ self._perf_mon_stop = _stop_event
2067
+
2068
+ def _monitor() -> None:
2069
+ last_ping = time.monotonic()
2070
+ last_apply = 0.0
2071
+ apply_cooldown = 30.0
2072
+ grace_until = time.monotonic() + 20.0
2073
+ ping_interval_ms = 150
2074
+ check_interval = max(threshold_ms / 1000.0, 0.4)
2075
+
2076
+ def _ping() -> None:
2077
+ nonlocal last_ping
2078
+ last_ping = time.monotonic()
2079
+ if not _stop_event.is_set():
2080
+ try:
2081
+ self._root.after(ping_interval_ms, _ping)
2082
+ except Exception:
2083
+ logger.debug(
2084
+ "Falha ao reagendar ping de watchdog.", exc_info=True
2085
+ )
2086
+
2087
+ try:
2088
+ self._root.after(ping_interval_ms, _ping)
2089
+ except Exception:
2090
+ return
2091
+
2092
+ while not _stop_event.wait(timeout=check_interval):
2093
+ now = time.monotonic()
2094
+ if now < grace_until:
2095
+ last_ping = now
2096
+ continue
2097
+ lag = (now - last_ping) * 1000.0
2098
+ if lag > threshold_ms:
2099
+ if now - last_apply > apply_cooldown:
2100
+ logger.warning(
2101
+ "Travamento detectado (%.0fms). Ativando modo performance.",
2102
+ lag,
2103
+ )
2104
+ last_apply = now
2105
+ apply_cooldown = min(apply_cooldown * 2.0, 120.0)
2106
+ with contextlib.suppress(Exception):
2107
+ self._root.after(0, self._apply_perf_mode)
2108
+ last_ping = now
2109
+ else:
2110
+ if apply_cooldown > 30.0:
2111
+ apply_cooldown = max(30.0, apply_cooldown * 0.8)
2112
+
2113
+ t = threading.Thread(target=_monitor, daemon=True,
2114
+ name="Codis-PerfMon")
2115
+ t.start()
2116
+
2117
+ def _apply_perf_mode(self) -> None:
2118
+ """Aplica configurações de performance usando preferências customizadas do usuário."""
2119
+ try:
2120
+ from src.ui.performance_panel import apply_perf_custom
2121
+
2122
+ editors = list(getattr(self, "_editors", []))
2123
+ apply_perf_custom(self._cfg, editors)
2124
+ with contextlib.suppress(Exception):
2125
+ if hasattr(self, "_kui") and self._kui:
2126
+ profile = str(self._cfg.get("perf_kui_fallback", "low"))
2127
+ keep_kui = bool(self._cfg.get("perf_keep_kui_anim", True))
2128
+ if not keep_kui:
2129
+ self._kui.set_perf_profile(profile)
2130
+ except Exception as exc:
2131
+ logger.warning("_apply_perf_mode falhou: %s", exc)
2132
+ logger.info("Modo performance aplicado via configuração customizada.")
2133
+
2134
+ def _open_performance_panel(self) -> None:
2135
+ """Abre o painel de configuração do modo performance customizável."""
2136
+ try:
2137
+ from src.ui.performance_panel import open_performance_panel
2138
+
2139
+ if hasattr(self, "_perf_panel_win"):
2140
+ with contextlib.suppress(Exception):
2141
+ if self._perf_panel_win.winfo_exists():
2142
+ self._perf_panel_win.deiconify()
2143
+ self._perf_panel_win.focus_force()
2144
+ return
2145
+ self._perf_panel_win = open_performance_panel(
2146
+ self._root,
2147
+ self._cfg,
2148
+ self._tmgr,
2149
+ on_apply_now=self._apply_perf_mode,
2150
+ )
2151
+ except Exception as exc:
2152
+ logger.warning("PerformancePanel falhou: %s", exc)
2153
+ messagebox.showerror(_t("err.title", "Erro"),
2154
+ str(exc), parent=self._root)
2155
+
2156
+ def _open_paint_panel(self) -> None:
2157
+ """Abre o editor de imagens (Paint integrado) em janela flutuante."""
2158
+ try:
2159
+ from src.ui.paint_panel import PaintPanel
2160
+
2161
+ existing = getattr(self, "_paint_win", None)
2162
+ if existing is not None:
2163
+ with contextlib.suppress(tk.TclError):
2164
+ if existing.winfo_exists():
2165
+ existing.deiconify()
2166
+ existing.focus_force()
2167
+ return
2168
+
2169
+ win = tk.Toplevel(self._root)
2170
+ win.title(_t("paint.window_title", "Paint - Codis"))
2171
+ win.geometry("1000x700")
2172
+ self._paint_win = win
2173
+ panel = PaintPanel(win, self._tmgr)
2174
+ panel.pack(fill="both", expand=True)
2175
+ win.focus_set()
2176
+ except Exception as exc:
2177
+ logger.warning("PaintPanel falhou: %s", exc)
2178
+ messagebox.showerror(_t("err.title", "Erro"),
2179
+ str(exc), parent=self._root)
2180
+
2181
+ def _open_pip_manager(self) -> None:
2182
+ """Abre o gerenciador de pacotes pip."""
2183
+ try:
2184
+ from src.ui.pip_manager import PipManagerPanel
2185
+
2186
+ if hasattr(self, "_pip_win") and self._pip_win.winfo_exists():
2187
+ self._pip_win.deiconify()
2188
+ self._pip_win.focus_force()
2189
+ return
2190
+ win = tk.Toplevel(self._root)
2191
+ win.title(_t("pip.window_title", "📦 Gerenciador Pip - Codis"))
2192
+ win.geometry("1000x680")
2193
+ win.minsize(760, 500)
2194
+ self._pip_win = win
2195
+ panel = PipManagerPanel(
2196
+ win, self._tmgr, self._cfg, on_restart=self._restart_process
2197
+ )
2198
+ panel.pack(fill="both", expand=True)
2199
+ win.focus_set()
2200
+ except Exception as exc:
2201
+ logger.warning("PipManager falhou: %s", exc)
2202
+ messagebox.showerror(_t("err.title", "Erro"),
2203
+ str(exc), parent=self._root)
2204
+
2205
+ def _open_task_manager(self) -> None:
2206
+ """Abre o gerenciador de tarefas Kanban."""
2207
+ try:
2208
+ from src.ui.task_manager import TaskManagerPanel
2209
+
2210
+ if hasattr(self, "_tasks_win") and self._tasks_win.winfo_exists():
2211
+ self._tasks_win.deiconify()
2212
+ self._tasks_win.focus_force()
2213
+ return
2214
+ win = tk.Toplevel(self._root)
2215
+ win.title(_t("tasks.window_title", "✅ Tarefas - Codis"))
2216
+ win.geometry("1100x700")
2217
+ win.minsize(800, 500)
2218
+ self._tasks_win = win
2219
+ panel = TaskManagerPanel(win, self._tmgr, self._cfg)
2220
+ panel.pack(fill="both", expand=True)
2221
+ win.focus_set()
2222
+ except Exception as exc:
2223
+ logger.warning("TaskManager falhou: %s", exc)
2224
+ messagebox.showerror(_t("err.title", "Erro"),
2225
+ str(exc), parent=self._root)
2226
+
2227
+ def _open_process_manager(self) -> None:
2228
+ """Abre o gerenciador de processos."""
2229
+ try:
2230
+ from src.ui.process_manager import ProcessManagerPanel
2231
+
2232
+ if hasattr(self, "_procmgr_win") and self._procmgr_win.winfo_exists():
2233
+ self._procmgr_win.deiconify()
2234
+ self._procmgr_win.focus_force()
2235
+ return
2236
+ win = tk.Toplevel(self._root)
2237
+ win.title(_t("procmgr.window_title",
2238
+ "Gerenciador de Processos - Codis"))
2239
+ win.geometry("1200x720")
2240
+ win.minsize(800, 500)
2241
+ self._procmgr_win = win
2242
+ panel = ProcessManagerPanel(
2243
+ win, self._tmgr, self._cfg, app_ref=self)
2244
+ panel.pack(fill="both", expand=True)
2245
+ win.focus_set()
2246
+ except Exception as exc:
2247
+ logger.warning("ProcessManager falhou: %s", exc)
2248
+ messagebox.showerror(_t("err.title", "Erro"),
2249
+ str(exc), parent=self._root)
2250
+
2251
+ def _open_diff(self) -> None:
2252
+ """Abre o visualizador de diff."""
2253
+ try:
2254
+ from src.ui.diff_panel import DiffPanel
2255
+
2256
+ if hasattr(self, "_diff_win") and self._diff_win.winfo_exists():
2257
+ self._diff_win.deiconify()
2258
+ self._diff_win.focus_force()
2259
+ return
2260
+ win = tk.Toplevel(self._root)
2261
+ win.title(_t("diff.window_title", "⇄ Diff Viewer - Codis"))
2262
+ win.geometry("1100x680")
2263
+ win.minsize(700, 400)
2264
+ self._diff_win = win
2265
+ panel = DiffPanel(win, self._tmgr, self._cfg)
2266
+ panel.pack(fill="both", expand=True)
2267
+ win.focus_set()
2268
+ except Exception as exc:
2269
+ logger.warning("DiffPanel falhou: %s", exc)
2270
+ messagebox.showerror(_t("err.title", "Erro"),
2271
+ str(exc), parent=self._root)
2272
+
2273
+ def _open_formatter(self) -> None:
2274
+ """Abre o formatador JSON/YAML/TOML/XML."""
2275
+ try:
2276
+ from src.ui.formatter_panel import FormatterPanel
2277
+
2278
+ if hasattr(self, "_fmt_win") and self._fmt_win.winfo_exists():
2279
+ self._fmt_win.deiconify()
2280
+ self._fmt_win.focus_force()
2281
+ return
2282
+ win = tk.Toplevel(self._root)
2283
+ win.title(_t("fmt.window_title", "{ } Formatador - Codis"))
2284
+ win.geometry("1000x660")
2285
+ win.minsize(700, 400)
2286
+ self._fmt_win = win
2287
+ panel = FormatterPanel(win, self._tmgr, self._cfg)
2288
+ panel.pack(fill="both", expand=True)
2289
+ win.focus_set()
2290
+ except Exception as exc:
2291
+ logger.warning("FormatterPanel falhou: %s", exc)
2292
+ messagebox.showerror(_t("err.title", "Erro"),
2293
+ str(exc), parent=self._root)
2294
+
2295
+ def _open_env_manager(self) -> None:
2296
+ """Abre o gerenciador de variáveis de ambiente."""
2297
+ try:
2298
+ from src.ui.env_manager import EnvManagerPanel
2299
+
2300
+ if hasattr(self, "_env_win") and self._env_win.winfo_exists():
2301
+ self._env_win.deiconify()
2302
+ self._env_win.focus_force()
2303
+ return
2304
+ win = tk.Toplevel(self._root)
2305
+ win.title(_t("env.window_title", "⚙ Variáveis de Ambiente - Codis"))
2306
+ win.geometry("900x620")
2307
+ win.minsize(700, 400)
2308
+ self._env_win = win
2309
+ panel = EnvManagerPanel(win, self._tmgr, self._cfg)
2310
+ panel.pack(fill="both", expand=True)
2311
+ win.focus_set()
2312
+ except Exception as exc:
2313
+ logger.warning("EnvManager falhou: %s", exc)
2314
+ messagebox.showerror(_t("err.title", "Erro"),
2315
+ str(exc), parent=self._root)
2316
+
2317
+ def _open_calculator(self) -> None:
2318
+ """Abre a calculadora integrada com histórico."""
2319
+ try:
2320
+ from src.ui.calculator_panel import CalculatorPanel
2321
+
2322
+ existing = getattr(self, "_calc_win", None)
2323
+ if existing is not None:
2324
+ with contextlib.suppress(tk.TclError):
2325
+ if existing.winfo_exists():
2326
+ existing.deiconify()
2327
+ existing.focus_force()
2328
+ return
2329
+
2330
+ win = tk.Toplevel(self._root)
2331
+ win.title(_t("calc.window_title", "Calculadora - Codis"))
2332
+ win.geometry("400x600")
2333
+ win.resizable(True, True)
2334
+ self._calc_win = win
2335
+ panel = CalculatorPanel(win, self._tmgr, self._cfg)
2336
+ panel.pack(fill="both", expand=True)
2337
+ win.focus_set()
2338
+ except Exception as exc:
2339
+ logger.warning("Calculator falhou: %s", exc)
2340
+ messagebox.showerror(_t("err.title", "Erro"),
2341
+ str(exc), parent=self._root)
2342
+
2343
+ def _open_calendar(self) -> None:
2344
+ """Abre o calendário integrado com lembretes e anotações."""
2345
+ try:
2346
+ from src.ui.calendar_panel import CalendarPanel
2347
+
2348
+ existing = getattr(self, "_calendar_win", None)
2349
+ if existing is not None:
2350
+ with contextlib.suppress(tk.TclError):
2351
+ if existing.winfo_exists():
2352
+ existing.deiconify()
2353
+ existing.focus_force()
2354
+ return
2355
+
2356
+ win = tk.Toplevel(self._root)
2357
+ win.title(_t("calendar.window_title", "📅 Calendário - Codis"))
2358
+ win.geometry("900x640")
2359
+ win.resizable(True, True)
2360
+ self._calendar_win = win
2361
+ panel = CalendarPanel(win, self._tmgr, self._cfg)
2362
+ panel.pack(fill="both", expand=True)
2363
+ win.focus_set()
2364
+ except Exception as exc:
2365
+ logger.warning("Calendar falhou: %s", exc)
2366
+ messagebox.showerror(_t("err.title", "Erro"),
2367
+ str(exc), parent=self._root)
2368
+
2369
+ def _open_clock(self) -> None:
2370
+ """Abre o relógio integrado com alarmes e cronômetro."""
2371
+ try:
2372
+ from src.ui.clock_panel import ClockPanel
2373
+
2374
+ if hasattr(self, "_clock_win") and self._clock_win.winfo_exists():
2375
+ self._clock_win.deiconify()
2376
+ self._clock_win.focus_force()
2377
+ return
2378
+ win = tk.Toplevel(self._root)
2379
+ win.title(_t("clock.window_title", "Relogio - Codis"))
2380
+ win.geometry("340x560")
2381
+ win.resizable(False, True)
2382
+ self._clock_win = win
2383
+ panel = ClockPanel(win, self._tmgr, self._cfg)
2384
+ panel.pack(fill="both", expand=True)
2385
+ win.focus_set()
2386
+ except Exception as exc:
2387
+ logger.warning("Clock falhou: %s", exc)
2388
+ messagebox.showerror(_t("err.title", "Erro"),
2389
+ str(exc), parent=self._root)
2390
+
2391
+ def _init_screen_reader_global(self) -> None:
2392
+ """Configura leitura de tela global (tipo TalkBack) para todos os widgets."""
2393
+ try:
2394
+ a11y = getattr(self, "_a11y_mgr", None)
2395
+ if a11y and self._cfg.get("a11y_screen_reader", False):
2396
+ a11y.setup_widget_reading(self._root)
2397
+ logger.debug("Leitor de tela global ativado.")
2398
+ except Exception as exc:
2399
+ logger.debug("Screen reader global setup: %s", exc)
2400
+
2401
+ def _open_time_tracker(self) -> None:
2402
+ """Abre o rastreador de tempo de codificação (offline, privado)."""
2403
+ try:
2404
+ from src.ui.time_tracker import TimeTrackerModel, TimeTrackerPanel
2405
+
2406
+ tw = getattr(self, "_tracker_win", None)
2407
+ if tw is not None and tw.winfo_exists():
2408
+ tw.deiconify()
2409
+ tw.focus_force()
2410
+ return
2411
+ if not hasattr(self, "_tracker_model"):
2412
+ self._tracker_model = TimeTrackerModel()
2413
+ win = tk.Toplevel(self._root)
2414
+ win.title(_t("tracker.window_title",
2415
+ "⏱ Code Time Tracker - Codis"))
2416
+ win.geometry("560x640")
2417
+ win.minsize(440, 480)
2418
+ self._tracker_win = win
2419
+ panel = TimeTrackerPanel(win, self._tmgr, self._tracker_model)
2420
+ panel.pack(fill="both", expand=True)
2421
+ win.focus_set()
2422
+ except Exception as exc:
2423
+ logger.warning("TimeTracker falhou: %s", exc)
2424
+ messagebox.showerror(_t("err.title", "Erro"),
2425
+ str(exc), parent=self._root)
2426
+
2427
+ def _open_dependency_graph(self) -> None:
2428
+ """Abre o visualizador de grafo de dependências Python."""
2429
+ try:
2430
+ from src.ui.dependency_graph import DependencyGraphPanel
2431
+
2432
+ dw = getattr(self, "_depgraph_win", None)
2433
+ if dw is not None and dw.winfo_exists():
2434
+ dw.deiconify()
2435
+ dw.focus_force()
2436
+ return
2437
+ win = tk.Toplevel(self._root)
2438
+ win.title(_t("depgraph.window_title",
2439
+ "Grafo de Dependencias - Codis"))
2440
+ win.geometry("900x680")
2441
+ win.minsize(600, 480)
2442
+ self._depgraph_win = win
2443
+ ws = getattr(self, "_workspace", None)
2444
+ panel = DependencyGraphPanel(
2445
+ win,
2446
+ self._tmgr,
2447
+ workspace=ws,
2448
+ on_open_file=self._open_file,
2449
+ )
2450
+ panel.pack(fill="both", expand=True)
2451
+ win.focus_set()
2452
+ except Exception as exc:
2453
+ logger.warning("DependencyGraph falhou: %s", exc)
2454
+ messagebox.showerror(_t("err.title", "Erro"),
2455
+ str(exc), parent=self._root)
2456
+
2457
+ def set_workspace(self, path: Path) -> None:
2458
+ """API pública - define o workspace. Chamado por main._open_cli_args."""
2459
+ self._set_workspace(path)
2460
+
2461
+ def open_file(self, path: Path) -> None:
2462
+ """API pública - abre um arquivo. Chamado por main._open_cli_args."""
2463
+ self._open_file(path)
2464
+
2465
+ def run(self) -> None:
2466
+ """
2467
+ Inicia o event loop.
2468
+ Chamá-lo quando já há um mainloop ativo é seguro (re-entrância segura
2469
+ no Tk: a chamada interna retorna quando a janela é destruída, não antes).
2470
+ """
2471
+ self._root.mainloop()