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.py ADDED
@@ -0,0 +1,1488 @@
1
+ """Codis - orquestrador principal.
2
+
3
+ Integração com o barramento de eventos (RESA)
4
+ ---------------------------------------------
5
+ O ``CodisApp`` é o ponto de convergência de toda a arquitetura de eventos.
6
+ Ele inicializa o ``EventBus`` global e registra os handlers internos que
7
+
8
+ Eventos emitidos por este módulo
9
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10
+ ``editor.change`` Conteúdo do editor foi modificado.
11
+ ``editor.cursor_move`` Cursor moveu-se; payload: ``{line, col, path}``.
12
+ ``editor.active`` Aba ativa mudou; payload: ``{path, lang, idx}``.
13
+ ``editor.open`` Arquivo aberto numa aba; payload: ``{path}``.
14
+ ``editor.save`` Arquivo salvo; payload: ``{path}``.
15
+ ``editor.close`` Aba fechada; payload: ``{path}``.
16
+ ``file.save`` Emitido junto com ``editor.save``.
17
+ ``workspace.open`` Workspace definido; payload: ``{path}``.
18
+ ``workspace.close`` Workspace fechado; payload: ``{}``.
19
+ ``config.change`` Qualquer chave de configuração mudou; payload: ``{key, value}``.
20
+ ``theme.change`` Tema visual alterado; payload: ``{theme}``.
21
+ ``plugin.hook`` Hook de plugin disparado; payload: ``{event, data}``.
22
+ ``session.save`` Sessão salva; payload: ``{}``.
23
+ ``session.restore`` Sessão restaurada; payload: ``{files}``.
24
+ ``ui.panel_show`` Painel inferior exibido; payload: ``{panel}``.
25
+ ``ui.sidebar_show`` Sidebar exibida; payload: ``{sidebar}``.
26
+ ``perf.metric`` Métrica de desempenho do bus; payload: métricas por tópico.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import contextlib
32
+ import logging
33
+ import sys
34
+ import threading
35
+ import time
36
+ import tkinter as tk
37
+ from collections.abc import Callable
38
+ from dataclasses import dataclass, field
39
+ from pathlib import Path
40
+ from typing import Any
41
+
42
+ from src._app_build import _AppBuildMixin
43
+ from src._app_editor import _AppEditorMixin
44
+ from src._app_kui import _AppKuiMixin
45
+ from src._app_lsp import _AppLspMixin
46
+ from src._app_recovery import _AppRecoveryMixin
47
+ from src._app_settings import _AppSettingsMixin
48
+ from src._app_tools import _AppToolsMixin
49
+ from src._app_webpreview import _AppWebPreviewMixin
50
+ from src.config import ConfigManager
51
+ from src.constants import (
52
+ APP_VERSION,
53
+ FONT_UI,
54
+ LANG_LABEL,
55
+ TAB_SIZE,
56
+ )
57
+ from src.editor.multi_cursor import MultiCursorManager
58
+ from src.editor.pane import EditorPane
59
+ from src.editor.snippets import SnippetEngine
60
+ from src.editor.vim_mode import VimMode
61
+ from src.extcompat import ExtensionRuntime, ExtensionStore
62
+ from src.i18n import I18n, _t
63
+ from src.lint.manager import LintManager
64
+ from src.plugins.api import PluginAPI
65
+ from src.plugins.loader import PluginLoader
66
+ from src.plugins.registry import CommandTable, ExtensionPoints, HookTable
67
+ from src.pyexec import is_frozen
68
+ from src.theme.base import THEME_ORDER, THEMES, Theme, _define_themes
69
+ from src.theme.manager import (
70
+ ThemeManager,
71
+ _apply_statusbar_patches,
72
+ _patch_all_themes,
73
+ _patch_theme,
74
+ )
75
+ from src.ui.bookmarks import BookmarkManager
76
+ from src.ui.code_runner import CodeRunnerStore
77
+ from src.ui.easter_eggs import EasterEggManager
78
+ from src.ui.grab_safe import safe_grab_set
79
+ from src.ui.k_ui import KUI, build_kui_theme
80
+ from src.ui.key_remapper import KeyRemapperManager, KeyRemapperStore
81
+ from src.ui.macro_recorder import MacroRecorder, MacroStore, MacroToolbar
82
+ from src.ui.panel_detach import PanelDetachManager
83
+ from src.ui.project_templates import TemplateStore
84
+ from src.ui.theme_preview_panel import ThemePreviewPanel
85
+ from src.ui.zen_media import ZenMediaPlayer, ZenMiniOrb
86
+ from src.ui.zen_player import ZenPlayerHost
87
+ from src.updater import UpdateManager
88
+ from src.updater.result import UpdateStatus
89
+ from src.workspace_state import is_restricted
90
+
91
+
92
+ @dataclass
93
+ class CopyEntry:
94
+ """Entrada no histórico de cópia/recorte."""
95
+
96
+ text: str
97
+ kind: str
98
+ timestamp: float = field(default_factory=time.time)
99
+
100
+
101
+ try:
102
+ from src.lsp.client import LSPManager
103
+
104
+ _LSP_OK = True
105
+ except ImportError:
106
+ LSPManager = None
107
+ _LSP_OK = False
108
+
109
+ try:
110
+ from src.events import bus as _event_bus
111
+ except Exception:
112
+ _event_bus = None
113
+
114
+ logger = logging.getLogger("Codis")
115
+
116
+
117
+ class CodisApp(
118
+ _AppBuildMixin,
119
+ _AppEditorMixin,
120
+ _AppLspMixin,
121
+ _AppRecoveryMixin,
122
+ _AppSettingsMixin,
123
+ _AppToolsMixin,
124
+ _AppKuiMixin,
125
+ _AppWebPreviewMixin,
126
+ ):
127
+ """
128
+ Orquestrador principal do Codis
129
+
130
+ Responsável por construir toda a interface, gerenciar abas, painéis,
131
+ configurações, plugins e os recursos exclusivos do editor.
132
+ """
133
+
134
+ def __init__(self, root: tk.Tk) -> None:
135
+ """Inicializa a aplicação, carregando configurações, temas, plugins
136
+ e construindo a interface principal.
137
+
138
+ Args:
139
+ root: Janela raiz do Tkinter.
140
+ """
141
+ self._root: tk.Tk = root
142
+
143
+ self._bus = _event_bus
144
+
145
+ if self._bus is not None:
146
+ self._bus.set_tk_root(root)
147
+
148
+ self._hook_to_kind: dict[str, str] = {
149
+ "file_open": "file.open",
150
+ "file_close": "file.close",
151
+ "file_save": "file.save",
152
+ "after_save": "file.save",
153
+ "tab_change": "editor.active",
154
+ "text_change": "editor.change",
155
+ "cursor_move": "editor.cursor_move",
156
+ "lint_complete": "lint.result",
157
+ "before_format": "editor.save",
158
+ "after_format": "editor.save",
159
+ "theme_change": "theme.change",
160
+ "lang_change": "syntax.lang_change",
161
+ }
162
+
163
+ self._cfg = ConfigManager()
164
+ if not THEMES:
165
+ _define_themes()
166
+ _patch_all_themes()
167
+ # Extensões importadas: os temas precisam existir antes de o ThemeManager ler o tema salvo.
168
+ self._ext_store = ExtensionStore()
169
+ self._ext_runtime = ExtensionRuntime(self._ext_store)
170
+ self._ext_code: Any = None # CodeManager, criado sob demanda (execução de código é opt-in)
171
+ try:
172
+ self._ext_runtime.activate_themes()
173
+ except Exception:
174
+ logger.warning("Falha ao carregar temas de extensões importadas", exc_info=True)
175
+ self._tmgr = ThemeManager(self._cfg.get("theme", "fluent_dark"))
176
+ _patch_theme(self._tmgr.theme)
177
+ _apply_statusbar_patches()
178
+ from src.ui.ui_scale import UIScaler
179
+
180
+ self._ui_scaler = UIScaler(self._root, self._cfg)
181
+ self._ui_scaler.start()
182
+ try:
183
+ I18n.get_instance().set_locale(self._cfg.get("language", "pt-BR"))
184
+ except Exception as exc:
185
+ logger.warning(
186
+ "Falha ao definir locale da configuração; usando padrão pt-BR: %s", exc
187
+ )
188
+
189
+ self._snippets = SnippetEngine()
190
+ self._ext_runtime.snippets = self._snippets
191
+ self._lint_mgr = LintManager(self._on_lint_result, self._cfg)
192
+
193
+ self._lsp_mgr: LSPManager | None = None
194
+ if _LSP_OK and self._cfg.get("lsp_enabled", True):
195
+ try:
196
+ self._lsp_mgr = LSPManager(
197
+ tk_root=self._root,
198
+ on_diagnostics=self._on_lsp_diagnostics,
199
+ on_log=self._on_lsp_log,
200
+ on_apply_edit=self._on_lsp_apply_edit,
201
+ )
202
+ logger.info("Gerenciador LSP iniciado")
203
+ except (OSError, ImportError, RuntimeError) as exc:
204
+ logger.warning("LSP indisponível: %s", exc)
205
+
206
+ self._plugin_hooks = HookTable()
207
+ self._commands = CommandTable()
208
+ self._extensions = ExtensionPoints()
209
+ self._plugin_keymap: dict[str, list[tuple[str, Callable[[], bool] | None]]] = {}
210
+ self._plugin_key_bound: set[str] = set()
211
+ self._plugin_api = PluginAPI(self)
212
+ self._plugin_loader = PluginLoader(self._plugin_api)
213
+
214
+ self._editors: list[EditorPane] = []
215
+ self._closed_tabs: list[str] = []
216
+ self._gc_job: str | None = None
217
+ self._active_idx: int = -1
218
+ self._workspace: Path | None = None
219
+
220
+ self._dual_mode: bool = False
221
+ self._dual_paned: tk.PanedWindow | None = None
222
+ self._dual_left_container: tk.Frame | None = None
223
+ self._dual_right_container: tk.Frame | None = None
224
+ self._dual_right_editor_frame: tk.Frame | None = None
225
+ self._dual_right_editors: list[EditorPane] = []
226
+ self._dual_right_idx: int = -1
227
+ self._dual_right_tabbar: object | None = None
228
+ self._dual_right_active: bool = False
229
+ self._autosave_job: str | None = None
230
+ self._zoom_pct: int = 100
231
+ self._sidebar_visible = False
232
+ self._panel_visible = False
233
+ self._current_panel = "problems"
234
+ self._current_sidebar = "explorer"
235
+
236
+ self._active_pane: EditorPane | None = None
237
+ self._smart_tips: object | None = None
238
+
239
+ self._zen_mode = False
240
+ self._focus_mode = False
241
+ self._copy_history: list[CopyEntry] = []
242
+ self._theme_debounce_job: str | None = None
243
+ self._clipboard_poll_last: str = ""
244
+ self._clipboard_poll_job: str | None = None
245
+ self._bookmark_mgr = BookmarkManager()
246
+
247
+ self._zen_media_player: ZenMediaPlayer | None = None
248
+ self._zen_player: ZenPlayerHost | None = None
249
+ self._zen_media_orb: ZenMiniOrb | None = None
250
+ self._vim_mode: VimMode | None = None
251
+ self._vim_enabled: bool = False
252
+ self._kui: KUI | None = None
253
+ self._kui_enabled: bool = False
254
+ self._panel_detach = PanelDetachManager(
255
+ self._root, dark=getattr(self._tmgr.theme, "dark", True)
256
+ )
257
+ self._easter_eggs: EasterEggManager | None = None
258
+
259
+ self._key_store = KeyRemapperStore()
260
+ self._key_mgr: KeyRemapperManager | None = None
261
+ self._runner_store = CodeRunnerStore()
262
+ self._macro_store = MacroStore()
263
+ self._macro_recorder = MacroRecorder(self._macro_store)
264
+ self._macro_toolbar: MacroToolbar | None = None
265
+ self._template_store = TemplateStore()
266
+ self._multi_cursor: MultiCursorManager | None = None
267
+
268
+ try:
269
+ from src.ui.time_tracker import TimeTrackerModel
270
+
271
+ self._tracker_model: TimeTrackerModel = TimeTrackerModel()
272
+ except Exception as _tracker_err:
273
+ logger.warning("TimeTracker init: %s", _tracker_err)
274
+
275
+ self._setup_window()
276
+ self._build_layout()
277
+ with contextlib.suppress(AttributeError, tk.TclError):
278
+ self._panel_detach.set_factories(self._build_panel_factories())
279
+ self._build_menus()
280
+ self._init_cursor_manager()
281
+ self._bind_shortcuts()
282
+ self._setup_key_manager()
283
+
284
+ self._tmgr.on_change(self._on_theme_change)
285
+ I18n.get_instance().on_change(self._on_locale_change)
286
+
287
+ self._cfg.on_change("theme", self._set_theme)
288
+ self._tmgr.apply_ttk()
289
+ self._lint_mgr.set_log_callback(self._output_panel.write)
290
+
291
+ self._lint_mgr.attach(self._root)
292
+ self._load_plugins()
293
+ self._rebuild_theme_menu()
294
+ self._recovery_start()
295
+ self._restore_session_or_welcome()
296
+ self._recovery_offer()
297
+ self._setup_autosave()
298
+ self._setup_tracker_heartbeat()
299
+ self._update_title()
300
+ self._update_status_bar()
301
+ self._init_exclusive_features()
302
+ if self._bus is not None:
303
+ self._root.after(30_000, self._emit_bus_metrics)
304
+
305
+ self._root.after(2000, self._start_clipboard_polling)
306
+
307
+ if self._cfg.get("auto_check_updates", True):
308
+ self._root.after(5000, self._silent_update_check)
309
+
310
+ self._root.bind("<Unmap>", self._dismiss_active_menus, add="+")
311
+
312
+ def _dismiss_active_menus(self, _event: tk.Event | None = None) -> None:
313
+ """Fecha menus flutuantes abertos ao minimizar ou perder foco."""
314
+ if _event is not None and _event.widget is not self._root:
315
+ return
316
+ with contextlib.suppress(tk.TclError):
317
+ self._root.tk.call("tk", "menuSetFocus", "")
318
+ for widget in list(self._root.winfo_children()):
319
+ if isinstance(widget, tk.Menu):
320
+ with contextlib.suppress(tk.TclError):
321
+ widget.unpost()
322
+
323
+ def _on_editor_change(self) -> None:
324
+ """Chamado quando o conteúdo do editor é modificado."""
325
+ self._update_breadcrumb()
326
+ e = self._active_editor()
327
+ if e:
328
+ self._fire_hook("text_change", e)
329
+ self._web_preview_on_edit()
330
+ if self._bus is not None:
331
+ self._bus.emit(
332
+ "editor.change",
333
+ {
334
+ "path": str(e.path) if e.path else "",
335
+ "lang": getattr(e, "lang", ""),
336
+ },
337
+ source="CodisApp",
338
+ )
339
+
340
+ def _on_copy_event(self, text: str, kind: str) -> None:
341
+ """Registra uma entrada no histórico global de cópia/recorte."""
342
+ entry = CopyEntry(text=text, kind=kind)
343
+ self._copy_history.insert(0, entry)
344
+ if len(self._copy_history) > 100:
345
+ self._copy_history.pop()
346
+
347
+ def _start_clipboard_polling(self) -> None:
348
+ """Inicia polling periódico do clipboard do sistema (a cada 500ms).
349
+
350
+ Captura cópias feitas em qualquer aplicativo ou pelo menu de contexto
351
+ do SO - não apenas via Ctrl+C dentro do editor.
352
+ Compara com o último valor registrado; só adiciona ao histórico se
353
+ o conteúdo mudou.
354
+ """
355
+ self._clipboard_poll_last: str = ""
356
+ self._clipboard_poll_job: str | None = None
357
+ self._clipboard_poll_tick()
358
+
359
+ def _clipboard_poll_tick(self) -> None:
360
+ """Tick do polling de clipboard - executa a cada 500ms."""
361
+ try:
362
+ current = self._root.clipboard_get()
363
+ except tk.TclError:
364
+ current = ""
365
+
366
+ if current and current != self._clipboard_poll_last:
367
+ self._clipboard_poll_last = current
368
+ if not self._copy_history or self._copy_history[0].text != current:
369
+ entry = CopyEntry(text=current, kind="copy")
370
+ self._copy_history.insert(0, entry)
371
+ if len(self._copy_history) > 100:
372
+ self._copy_history.pop()
373
+
374
+ if self._root.winfo_exists():
375
+ self._clipboard_poll_job = self._root.after(
376
+ 500, self._clipboard_poll_tick)
377
+
378
+ def _silent_update_check(self) -> None:
379
+ """Verifica atualizações em background e exibe aviso discreto se houver."""
380
+ manager = UpdateManager.from_config(self._cfg, APP_VERSION)
381
+ if is_frozen():
382
+ manager.cleanup_leftovers()
383
+
384
+ def worker() -> None:
385
+ with contextlib.suppress(Exception):
386
+ result = manager.check()
387
+ if result.status == UpdateStatus.UPDATE_AVAILABLE:
388
+ message = _t(
389
+ "update.notify",
390
+ "⬆ Codis {version} disponível - Ajuda › Verificar Atualizações",
391
+ version=result.latest_version,
392
+ )
393
+ self._root.after(0, lambda: self._status.notify(message))
394
+
395
+ threading.Thread(target=worker, daemon=True, name="codis-update-check").start()
396
+
397
+ def _bind_panel_tab_context_menu(self, key: str, lbl: tk.Label) -> None:
398
+ """Vincula menu de contexto (clique direito) à aba de painel.
399
+
400
+ Exibe a opção de desplugagem (detach) tanto no modo clássico quanto
401
+ no modo K-UI, via ``PanelDetachManager`` compartilhado. Painéis
402
+ sem fábrica registrada (ex.: diff, sql) não recebem a opção, pois
403
+ ainda dependem do estado vivo do painel embutido.
404
+
405
+ Args:
406
+ key: Chave do painel.
407
+ lbl: Widget de rótulo da aba.
408
+ """
409
+
410
+ def _show_menu(event: tk.Event) -> None:
411
+ if not self._panel_detach.can_detach(key):
412
+ return
413
+ menu = tk.Menu(lbl, tearoff=False)
414
+ t = self._tmgr.theme
415
+ menu.configure(bg=t.panel_bg, fg=t.fg, activebackground=t.sel_bg)
416
+ menu.add_command(
417
+ label=_t("kui.detach", key=key),
418
+ command=lambda: self._panel_detach.detach(key),
419
+ )
420
+ if self._panel_detach.is_detached(key):
421
+ menu.add_command(
422
+ label=_t("kui.reattach", key=key),
423
+ command=lambda: self._panel_detach.reattach(key),
424
+ )
425
+ with contextlib.suppress(tk.TclError):
426
+ menu.tk_popup(event.x_root, event.y_root)
427
+
428
+ lbl.bind("<Button-3>", _show_menu)
429
+
430
+ def _make_theme_callbacks(self) -> tuple:
431
+ """Cria e retorna os callbacks (on_full, on_fast, on_cancel) para o painel de temas.
432
+
433
+ Centraliza a lógica compartilhada entre ``_open_theme_panel`` e
434
+ ``_apply_theme_from_menu``, eliminando duplicação de código.
435
+ """
436
+
437
+ def _do_full(name: str) -> None:
438
+ self._theme_panel_open = False
439
+ self._tmgr.set(name)
440
+ self._cfg.set("theme", name)
441
+ self._cfg.save()
442
+ self._restart_ui()
443
+
444
+ def _do_fast(name: str) -> None:
445
+ self._theme_panel_open = False
446
+ self._tmgr.set(name)
447
+ self._cfg.set("theme", name)
448
+ self._cfg.save()
449
+ self._on_theme_change(self._tmgr.theme)
450
+
451
+ def _do_cancel() -> None:
452
+ self._theme_panel_open = False
453
+
454
+ return _do_full, _do_fast, _do_cancel
455
+
456
+ def _open_theme_panel(self) -> None:
457
+ """Abre o painel wizard de seleção de temas com preview ao vivo."""
458
+ if getattr(self, "_theme_panel_open", False):
459
+ return
460
+ self._theme_panel_open = True
461
+ _do_full, _do_fast, _do_cancel = self._make_theme_callbacks()
462
+ try:
463
+ ThemePreviewPanel(
464
+ self._root,
465
+ current_theme=self._tmgr.theme,
466
+ on_full=_do_full,
467
+ on_fast=_do_fast,
468
+ on_cancel=_do_cancel,
469
+ )
470
+ except Exception:
471
+ logger.warning(
472
+ "Falha ao criar ThemePreviewPanel, aplicando fallback direto",
473
+ exc_info=True,
474
+ )
475
+ self._theme_panel_open = False
476
+ self._root.after(80, self._restart_ui)
477
+
478
+ def _apply_theme_from_menu(self, name: str) -> None:
479
+ """Chamado ao clicar diretamente no nome de um tema no menu.
480
+
481
+ Abre o seletor de temas com o tema pré-selecionado, dando ao usuário
482
+ a opção de aplicar completo (com restart da UI) ou rápido - evitando
483
+ o bug de cores corrompidas que ocorre na aplicação direta pelo menu.
484
+ """
485
+ if getattr(self, "_theme_panel_open", False):
486
+ return
487
+ self._theme_panel_open = True
488
+ _do_full, _do_fast, _do_cancel = self._make_theme_callbacks()
489
+ try:
490
+ ThemePreviewPanel(
491
+ self._root,
492
+ current_theme=self._tmgr.theme,
493
+ on_full=_do_full,
494
+ on_fast=_do_fast,
495
+ on_cancel=_do_cancel,
496
+ )
497
+ except Exception:
498
+ self._theme_panel_open = False
499
+ self._set_theme(name)
500
+
501
+ def _set_theme(self, name: str) -> None:
502
+ """Aplica tema direto (chamado pelo config watcher) sem abrir o painel.
503
+
504
+ Usa debounce de 300ms para evitar aplicações parciais quando o tema
505
+ é trocado rapidamente (ex: clicar várias vezes no menu de temas),
506
+ o que causava cores corrompidas e misturadas na UI.
507
+ """
508
+ if getattr(self, "_theme_debounce_job", None):
509
+ with contextlib.suppress(tk.TclError):
510
+ self._root.after_cancel(self._theme_debounce_job)
511
+
512
+ def _apply() -> None:
513
+ self._theme_debounce_job = None
514
+ self._tmgr.set(name)
515
+ self._cfg.set("theme", name)
516
+ self._cfg.save()
517
+ self._on_theme_change(self._tmgr.theme)
518
+
519
+ self._theme_debounce_job = self._root.after(300, _apply)
520
+
521
+ def _restart_ui(self) -> None:
522
+ """
523
+ Destrói e recria toda a interface mantendo estado (workspace, arquivos).
524
+ Garante que NENHUM widget fique com cores do tema anterior.
525
+ Restaura o estado do painel de temas ao terminar.
526
+ """
527
+ workspace = self._workspace
528
+ active_idx = self._active_idx
529
+ open_files: list = []
530
+ for e in self._editors:
531
+ try:
532
+ content_str = e.text.get("1.0", "end-1c")
533
+ lang = getattr(e, "lang", "text")
534
+ open_files.append(
535
+ (getattr(e, "path", None), content_str, lang))
536
+ except Exception as exc:
537
+ logger.debug(
538
+ "Não foi possível salvar estado do editor no restart: %s", exc
539
+ )
540
+
541
+ try:
542
+ if self._autosave_job:
543
+ self._root.after_cancel(self._autosave_job)
544
+ except Exception as exc:
545
+ logger.debug("Erro ao cancelar autosave no restart: %s", exc)
546
+ try:
547
+ self._lint_mgr.cancel()
548
+ except Exception as exc:
549
+ logger.debug("Erro ao cancelar lint no restart: %s", exc)
550
+ try:
551
+ if self._lsp_mgr:
552
+ self._lsp_mgr.stop_all()
553
+ except Exception as exc:
554
+ logger.debug("Erro ao parar LSP no restart: %s", exc)
555
+ try:
556
+ from src.ui.k_ui._perf import shutdown_physics_executor
557
+
558
+ shutdown_physics_executor()
559
+ except Exception as exc:
560
+ logger.debug(
561
+ "Erro ao encerrar physics executor no restart: %s", exc)
562
+
563
+ for child in list(self._root.winfo_children()):
564
+ with contextlib.suppress(tk.TclError):
565
+ child.destroy()
566
+
567
+ t = self._tmgr.theme
568
+ _patch_theme(t)
569
+ self._tmgr.apply_ttk()
570
+ self._root.config(bg=t.bg)
571
+
572
+ self._editors = []
573
+ self._active_idx = -1
574
+ self._workspace = None
575
+ self._autosave_job = None
576
+ self._zoom_pct = 100
577
+ self._sidebar_visible = False
578
+ self._panel_visible = False
579
+ self._current_panel = "problems"
580
+ self._current_sidebar = "explorer"
581
+ self._active_pane = None
582
+
583
+ self._cfg._change_callbacks["theme"] = []
584
+ self._tmgr._change_callbacks.clear()
585
+
586
+ self._setup_window()
587
+ self._build_layout()
588
+ with contextlib.suppress(AttributeError, tk.TclError):
589
+ self._panel_detach.set_factories(self._build_panel_factories())
590
+ self._panel_detach.set_dark(getattr(t, "dark", True))
591
+ self._build_menus()
592
+ self._bind_shortcuts()
593
+ self._setup_key_manager()
594
+
595
+ self._tmgr.on_change(self._on_theme_change)
596
+ I18n.get_instance().on_change(self._on_locale_change)
597
+ self._cfg.on_change("theme", self._set_theme)
598
+ self._tmgr.apply_ttk()
599
+ self._lint_mgr.set_log_callback(
600
+ lambda msg, channel="Codis", level="info": self._output_panel.write(
601
+ msg, channel, level
602
+ )
603
+ )
604
+ self._lint_mgr.attach(self._root)
605
+ self._load_plugins()
606
+ self._rebuild_theme_menu()
607
+
608
+ if workspace:
609
+ with contextlib.suppress(tk.TclError):
610
+ self._set_workspace(workspace)
611
+
612
+ for path, content, lang in open_files:
613
+ with contextlib.suppress(tk.TclError, AttributeError):
614
+ if path and path.exists():
615
+ self._open_file(path)
616
+ else:
617
+ self.new_file()
618
+ if self._editors:
619
+ e = self._editors[-1]
620
+ e.text.delete("1.0", "end")
621
+ e.text.insert("1.0", content)
622
+ e.language = lang
623
+
624
+ if 0 <= active_idx < len(self._editors):
625
+ with contextlib.suppress(tk.TclError):
626
+ self._select_tab(active_idx)
627
+ elif self._editors:
628
+ with contextlib.suppress(tk.TclError):
629
+ self._select_tab(0)
630
+
631
+ self._setup_autosave()
632
+ self._update_title()
633
+ self._update_status_bar()
634
+
635
+ if self._cfg.get("kui_enabled", False):
636
+ self._kui_enabled = False
637
+ self._kui = None
638
+ self._root.after(300, self._enable_kui)
639
+ if self._cfg.get("vim_mode", False):
640
+ self._vim_enabled = False
641
+ self._vim_mode = None
642
+ self._root.after(450, self._enable_vim_mode)
643
+
644
+ self._theme_panel_open = False
645
+
646
+ def _on_theme_change(self, t: Theme) -> None:
647
+ """Aplica o tema a todos os componentes da janela principal."""
648
+ from src.theme.utils import cfg, recolor
649
+
650
+ _patch_theme(t)
651
+ self._root.config(bg=t.bg)
652
+ self._tmgr.apply_ttk()
653
+ with contextlib.suppress(AttributeError, tk.TclError):
654
+ self._ui_scaler.reapply_styles()
655
+
656
+ with contextlib.suppress(AttributeError, tk.TclError):
657
+ self._panel_detach.set_dark(getattr(t, "dark", True))
658
+
659
+ with contextlib.suppress(Exception):
660
+ self._menubar.apply_theme(t)
661
+
662
+ for e in self._editors:
663
+ with contextlib.suppress(tk.TclError):
664
+ e.apply_theme(t)
665
+
666
+ for widget in (
667
+ self._status,
668
+ self._breadcrumb,
669
+ self._tabbar,
670
+ self._file_tree,
671
+ self._find_files,
672
+ self._git_sidebar,
673
+ self._plugin_panel,
674
+ self._settings_editor,
675
+ self._problems_panel,
676
+ self._terminal,
677
+ self._output_panel,
678
+ self._git_bottom,
679
+ self._diff_pane,
680
+ self._debug_panel,
681
+ self._code_outline,
682
+ self._snippets_panel,
683
+ self._scratchpad_pane,
684
+ self._bookmarks_panel,
685
+ self._regex_panel,
686
+ self._sidebar_problems,
687
+ self._search_bar,
688
+ ):
689
+ with contextlib.suppress(AttributeError, tk.TclError):
690
+ widget.apply_theme(t)
691
+
692
+ for widget in (
693
+ self._actbar,
694
+ self._code_stats_panel,
695
+ self._todo_panel,
696
+ self._rest_client_panel,
697
+ self._render_panel,
698
+ self._pomodoro_panel,
699
+ self._flowchart_panel,
700
+ self._docs_panel,
701
+ getattr(self, "_sql_studio_panel", None),
702
+ getattr(self, "_sql_bottom", None),
703
+ ):
704
+ with contextlib.suppress(AttributeError, tk.TclError):
705
+ widget.apply_theme(self._tmgr)
706
+
707
+ recolor(
708
+ {
709
+ **{
710
+ getattr(self, a): {"bg": bg}
711
+ for a, bg in {
712
+ "_sidebar": t.sidebar_bg,
713
+ "_sidebar_stack": t.sidebar_bg,
714
+ "_content_frame": t.bg,
715
+ "_panel_content": t.panel_bg,
716
+ "_bottom_frame": t.panel_bg,
717
+ }.items()
718
+ if getattr(self, a, None) is not None
719
+ },
720
+ }
721
+ )
722
+
723
+ for pw_attr in ("_h_paned", "_v_paned"):
724
+ with contextlib.suppress(AttributeError, tk.TclError):
725
+ getattr(self, pw_attr).config(bg=t.border)
726
+
727
+ cfg(
728
+ getattr(self, "_sidebar_toggle_btn", None) or tk.Frame(),
729
+ bg=t.tabbar_bg,
730
+ fg=t.fg,
731
+ )
732
+ cfg(
733
+ getattr(self, "_panel_toggle_btn", None) or tk.Frame(),
734
+ bg=t.tabbar_bg,
735
+ fg=t.fg,
736
+ )
737
+ cfg(getattr(self, "_panel_tabbar", None) or tk.Frame(), bg=t.tabbar_bg)
738
+
739
+ for k, lbl in self._panel_tabs.items():
740
+ active = k == self._current_panel
741
+ cfg(
742
+ lbl,
743
+ bg=t.tab_act_bg if active else t.tabbar_bg,
744
+ fg=t.tab_act_fg if active else t.tab_in_fg,
745
+ )
746
+
747
+ try:
748
+ self._apply_titlebar_color()
749
+ except Exception as exc:
750
+ logger.debug(
751
+ "Não foi possível aplicar cor na barra de título: %s", exc)
752
+
753
+ if self._kui:
754
+ with contextlib.suppress(tk.TclError):
755
+ self._kui.apply_theme(t)
756
+
757
+ with contextlib.suppress(tk.TclError):
758
+ self._apply_kui_colors()
759
+
760
+ self._fire_hook("theme_change", t)
761
+
762
+ _CONSTANTS_KEY_MAP: dict[str, str | None] = {
763
+ "autocomplete_delay": "AUTOCOMPLETE_DELAY",
764
+ "autocomplete_min_chars": "AUTOCOMPLETE_MIN_CHARS",
765
+ "autocomplete_max_items": "AUTOCOMPLETE_MAX_ITEMS",
766
+ "lint_delay": "LINT_DELAY",
767
+ "hl_idle_ms": "HL_IDLE_MS",
768
+ "large_file_mb": None,
769
+ "search_max_results": "SEARCH_MAX_RESULTS",
770
+ "font_min": "FONT_MIN",
771
+ "font_max": "FONT_MAX",
772
+ "minimap_width": "MINIMAP_WIDTH",
773
+ "minimap_scale": "MINIMAP_SCALE",
774
+ "max_recent": "MAX_RECENT",
775
+ "autosave_default": "AUTOSAVE_DEFAULT",
776
+ }
777
+
778
+ def _patch_constant(self, key: str, value: Any) -> None:
779
+ """Atualiza a constante correspondente em ``src.constants`` em tempo real."""
780
+ with contextlib.suppress(ValueError, AttributeError):
781
+ mod = sys.modules.get("src.constants")
782
+ if not mod:
783
+ return
784
+ const = self._CONSTANTS_KEY_MAP.get(key)
785
+ if const:
786
+ setattr(mod, const, int(value))
787
+ elif key == "large_file_mb":
788
+ mod.LARGE_FILE_BYTES = int(value) * 1024 * 1024
789
+
790
+ def _apply_a11y_setting(self, key: str, value: Any) -> None:
791
+ """Aplica configuração de acessibilidade ao módulo _a11y em tempo real."""
792
+ a11y = getattr(self, "_a11y_mgr", None)
793
+ if not a11y:
794
+ return
795
+ if key == "a11y_high_contrast":
796
+ if value:
797
+ a11y.enable_high_contrast(save=False)
798
+ else:
799
+ a11y.disable_high_contrast(save=False)
800
+ elif key == "a11y_colorblind_mode":
801
+ if value:
802
+ a11y.enable_colorblind_mode(str(value), save=False)
803
+ else:
804
+ a11y.disable_colorblind_mode(save=False)
805
+ elif key == "a11y_screen_reader":
806
+ a11y._screen_reader_enabled = bool(value)
807
+ elif key == "a11y_large_ui_font":
808
+ a11y._large_ui_font = bool(value)
809
+ elif key == "a11y_reduce_motion":
810
+ a11y._reduce_motion = bool(value)
811
+
812
+ def _on_setting_change(self, key: str, value: Any) -> None:
813
+ """Aplica mudanças de configuração em tempo real sem reiniciar a aplicação."""
814
+ if key == "theme":
815
+ self._set_theme(value)
816
+ elif key == "language":
817
+ I18n.get_instance().set_locale(value)
818
+ self._cfg.set("language", value)
819
+ elif key == "ui_scale":
820
+ if getattr(self, "_ui_scale_job", None):
821
+ with contextlib.suppress(tk.TclError):
822
+ self._root.after_cancel(self._ui_scale_job)
823
+
824
+ def _apply_scale(v: Any = value) -> None:
825
+ self._ui_scale_job = None
826
+ self._ui_scaler.on_config_change(v)
827
+
828
+ self._ui_scale_job = self._root.after(80, _apply_scale)
829
+ elif key == "kui_perf":
830
+ if self._kui:
831
+ self._kui.set_perf_profile(str(value))
832
+ elif key in ("font_family", "font_size", "tab_size"):
833
+ for e in self._editors:
834
+ e.apply_config(self._cfg)
835
+ if key == "tab_size":
836
+ self._status.set_indent(
837
+ value, not self._cfg.get("use_spaces", True))
838
+ elif key == "word_wrap":
839
+ for e in self._editors:
840
+ e.set_word_wrap(bool(value))
841
+ elif key == "minimap":
842
+ for e in self._editors:
843
+ e.set_minimap(bool(value))
844
+ elif key in ("autosave", "autosave_delay"):
845
+ self._setup_autosave()
846
+ elif key == "lsp_enabled":
847
+ if self._lsp_mgr:
848
+ self._lsp_mgr.set_enabled(bool(value) and not is_restricted())
849
+ elif key in self._CONSTANTS_KEY_MAP:
850
+ self._patch_constant(key, value)
851
+ elif key == "_open_json":
852
+ self._open_file(Path(value))
853
+ elif key == "ui_cursor":
854
+ try:
855
+ from src.theme.manager import apply_custom_cursor
856
+
857
+ apply_custom_cursor(self._root, str(value))
858
+ except Exception as exc:
859
+ logger.debug("Custom cursor: %s", exc)
860
+ elif key.startswith("a11y_"):
861
+ self._apply_a11y_setting(key, value)
862
+ elif key == "custom_keywords":
863
+ for e in self._editors:
864
+ with contextlib.suppress(Exception):
865
+ e.refresh_custom_keywords()
866
+ self._cfg.save()
867
+
868
+ def _on_locale_change(self) -> None:
869
+ """Reconstrói os menus quando o idioma muda."""
870
+ with contextlib.suppress(tk.TclError):
871
+ self._menubar.destroy()
872
+ self._build_menus()
873
+
874
+ def _pick_language(self) -> None:
875
+ """Abre diálogo para selecionar o modo de linguagem do arquivo."""
876
+ t = self._tmgr.theme
877
+ dlg = tk.Toplevel(self._root)
878
+ dlg.title("Select Language")
879
+ dlg.configure(bg=t.floating_bg)
880
+ dlg.transient(self._root)
881
+ safe_grab_set(dlg)
882
+ dlg.resizable(False, False)
883
+
884
+ tk.Label(
885
+ dlg,
886
+ text=_t("hc.app.select_language_mode"),
887
+ bg=t.floating_bg,
888
+ fg=t.fg,
889
+ font=(FONT_UI, 11, "bold"),
890
+ ).pack(padx=16, pady=(12, 4))
891
+
892
+ search_var = tk.StringVar()
893
+ sf = tk.Frame(dlg, bg=t.floating_bg)
894
+ sf.pack(fill="x", padx=12, pady=(0, 4))
895
+ tk.Label(
896
+ sf, text="🔍", bg=t.floating_bg, fg=t.fg_muted, font=(FONT_UI, 10)
897
+ ).pack(side="left")
898
+ search_entry = tk.Entry(
899
+ sf,
900
+ textvariable=search_var,
901
+ bg=t.input_bg,
902
+ fg=t.fg,
903
+ insertbackground=t.cursor,
904
+ relief="flat",
905
+ bd=0,
906
+ font=(FONT_UI, 10),
907
+ highlightthickness=1,
908
+ highlightbackground=t.border,
909
+ )
910
+ search_entry.pack(side="left", fill="x", expand=True, padx=4, pady=2)
911
+
912
+ lf = tk.Frame(dlg, bg=t.floating_bg)
913
+ lf.pack(fill="both", expand=True, padx=12, pady=4)
914
+ lb = tk.Listbox(
915
+ lf,
916
+ bg=t.sidebar_bg,
917
+ fg=t.fg,
918
+ selectbackground=t.sel_bg,
919
+ selectforeground=t.sel_fg,
920
+ relief="flat",
921
+ bd=0,
922
+ font=(FONT_UI, 10),
923
+ activestyle="none",
924
+ highlightthickness=1,
925
+ highlightbackground=t.border,
926
+ width=40,
927
+ height=16,
928
+ )
929
+ vsb = tk.Scrollbar(
930
+ lf,
931
+ command=lb.yview,
932
+ bg=t.scroll_thumb,
933
+ troughcolor=t.scroll_bg,
934
+ relief="flat",
935
+ bd=0,
936
+ width=6,
937
+ )
938
+ vsb.pack(side="right", fill="y")
939
+ lb.config(yscrollcommand=vsb.set)
940
+ lb.pack(fill="both", expand=True)
941
+
942
+ all_langs = sorted(LANG_LABEL.items(), key=lambda x: x[1])
943
+
944
+ def _populate(filter_str: str = "") -> None:
945
+ lb.delete(0, "end")
946
+ q = filter_str.lower()
947
+ for lang_id, lang_name in all_langs:
948
+ if not q or q in lang_name.lower() or q in lang_id:
949
+ lb.insert("end", f" {lang_name}")
950
+ if lb.size() > 0:
951
+ lb.selection_set(0)
952
+
953
+ _populate()
954
+
955
+ def _on_search(*_):
956
+ _populate(search_var.get())
957
+
958
+ search_var.trace_add("write", _on_search)
959
+
960
+ def _apply(lang_id: str) -> None:
961
+ e = self._e()
962
+ if e:
963
+ old_lang = e.lang
964
+ e.lang = lang_id
965
+ e.hl.set_lang(lang_id)
966
+ e.hl.highlight()
967
+ e.autocomplete.set_lang(lang_id)
968
+ self._status.set_lang(lang_id)
969
+ self._status.notify(
970
+ _t("msg.lang_changed", lang=LANG_LABEL.get(lang_id, lang_id))
971
+ )
972
+ self._fire_hook("lang_change", lang_id)
973
+ with contextlib.suppress(tk.TclError):
974
+ self._snippets_panel.notify_active_lang(lang_id)
975
+
976
+ with contextlib.suppress(Exception):
977
+ if e.path:
978
+ content = e.text.get("1.0", "end-1c")
979
+ self._lint_mgr.schedule(e.path, content, lang_id)
980
+
981
+ if self._lsp_mgr and e.path:
982
+ with contextlib.suppress(Exception):
983
+ if old_lang != lang_id:
984
+ self._lsp_mgr.did_close(e.path, old_lang)
985
+
986
+ content = e.text.get("1.0", "end-1c")
987
+ self._lsp_mgr.did_open(e.path, lang_id, content)
988
+ e.autocomplete.set_lsp_manager(self._lsp_mgr, e.path)
989
+
990
+ if lang_id not in (
991
+ "text",
992
+ "plaintext",
993
+ "",
994
+ ) and not self._lsp_mgr.available_for(lang_id):
995
+ hint = self._lsp_mgr.install_hint(lang_id)
996
+ if hint:
997
+ self._output_panel.write(
998
+ f"LSP [{lang_id}]: sem servidor. Instale: {hint}",
999
+ "LSP",
1000
+ "info",
1001
+ timestamp=False,
1002
+ )
1003
+ dlg.destroy()
1004
+
1005
+ def _on_ok(*_):
1006
+ sel = lb.curselection()
1007
+ if not sel:
1008
+ return
1009
+ q = search_var.get().lower()
1010
+ matches = [
1011
+ (lid, ln)
1012
+ for lid, ln in all_langs
1013
+ if not q or q in ln.lower() or q in lid
1014
+ ]
1015
+ if sel[0] < len(matches):
1016
+ _apply(matches[sel[0]][0])
1017
+
1018
+ lb.bind("<Double-Button-1>", _on_ok)
1019
+ lb.bind("<Return>", _on_ok)
1020
+
1021
+ btn_frame = tk.Frame(dlg, bg=t.floating_bg)
1022
+ btn_frame.pack(fill="x", padx=12, pady=(4, 12))
1023
+ for text, cmd in (("OK", _on_ok), ("Cancel", dlg.destroy)):
1024
+ b = tk.Label(
1025
+ btn_frame,
1026
+ text=text,
1027
+ bg=t.btn_bg,
1028
+ fg=t.fg,
1029
+ font=(FONT_UI, 9),
1030
+ cursor="hand2",
1031
+ padx=14,
1032
+ pady=4,
1033
+ relief="flat",
1034
+ )
1035
+ b.pack(side="right", padx=4)
1036
+ b.bind("<Button-1>", lambda _, c=cmd: c())
1037
+ b.bind("<Enter>", lambda _, w=b: w.config(bg=t.btn_hover))
1038
+ b.bind("<Leave>", lambda _, w=b: w.config(bg=t.btn_bg))
1039
+
1040
+ search_entry.focus_set()
1041
+
1042
+ dlg.update_idletasks()
1043
+ dlg.lift()
1044
+ dlg.focus_force()
1045
+
1046
+ x = (
1047
+ self._root.winfo_rootx()
1048
+ + (self._root.winfo_width() - dlg.winfo_width()) // 2
1049
+ )
1050
+ y = (
1051
+ self._root.winfo_rooty()
1052
+ + (self._root.winfo_height() - dlg.winfo_height()) // 2
1053
+ )
1054
+ dlg.geometry(f"+{x}+{y}")
1055
+
1056
+ def _pick_eol(self) -> None:
1057
+ """Abre diálogo para escolher o tipo de fim de linha."""
1058
+ t = self._tmgr.theme
1059
+ dlg = tk.Toplevel(self._root)
1060
+ dlg.title("Select End of Line")
1061
+ dlg.configure(bg=t.floating_bg)
1062
+ dlg.transient(self._root)
1063
+ safe_grab_set(dlg)
1064
+ dlg.resizable(False, False)
1065
+
1066
+ tk.Label(
1067
+ dlg,
1068
+ text=_t("hc.app.end_of_line_sequence"),
1069
+ bg=t.floating_bg,
1070
+ fg=t.fg,
1071
+ font=(FONT_UI, 11, "bold"),
1072
+ ).pack(padx=20, pady=(14, 6))
1073
+
1074
+ eol_options = [
1075
+ ("LF", "\n", "Unix/macOS (\\n)"),
1076
+ ("CRLF", "\r\n", "Windows (\\r\\n)"),
1077
+ ("CR", "\r", "Legacy Mac (\\r)"),
1078
+ ]
1079
+
1080
+ var = tk.StringVar(value="LF")
1081
+ for code, _, desc in eol_options:
1082
+ fr = tk.Frame(dlg, bg=t.floating_bg, cursor="hand2")
1083
+ fr.pack(fill="x", padx=20, pady=2)
1084
+ rb = tk.Radiobutton(
1085
+ fr,
1086
+ text=f"{code} - {desc}",
1087
+ variable=var,
1088
+ value=code,
1089
+ bg=t.floating_bg,
1090
+ fg=t.fg,
1091
+ activebackground=t.floating_bg,
1092
+ selectcolor=t.input_bg,
1093
+ font=(FONT_UI, 10),
1094
+ )
1095
+ rb.pack(anchor="w")
1096
+
1097
+ def _apply(*_):
1098
+ eol_map = {"LF": "\n", "CRLF": "\r\n", "CR": "\r"}
1099
+ eol = eol_map.get(var.get())
1100
+ if eol:
1101
+ e = self._e()
1102
+ if e:
1103
+ e.eol = eol
1104
+ self._status.set_eol(eol)
1105
+ dlg.destroy()
1106
+
1107
+ btn_frame = tk.Frame(dlg, bg=t.floating_bg)
1108
+ btn_frame.pack(fill="x", padx=16, pady=(8, 14))
1109
+ for text, cmd in (("OK", _apply), ("Cancel", dlg.destroy)):
1110
+ b = tk.Label(
1111
+ btn_frame,
1112
+ text=text,
1113
+ bg=t.btn_bg,
1114
+ fg=t.fg,
1115
+ font=(FONT_UI, 9),
1116
+ cursor="hand2",
1117
+ padx=14,
1118
+ pady=4,
1119
+ relief="flat",
1120
+ )
1121
+ b.pack(side="right", padx=4)
1122
+ b.bind("<Button-1>", lambda _, c=cmd: c())
1123
+ b.bind("<Enter>", lambda _, w=b: w.config(bg=t.btn_hover))
1124
+ b.bind("<Leave>", lambda _, w=b: w.config(bg=t.btn_bg))
1125
+
1126
+ dlg.update_idletasks()
1127
+ x = (
1128
+ self._root.winfo_rootx()
1129
+ + (self._root.winfo_width() - dlg.winfo_width()) // 2
1130
+ )
1131
+ y = (
1132
+ self._root.winfo_rooty()
1133
+ + (self._root.winfo_height() - dlg.winfo_height()) // 2
1134
+ )
1135
+ dlg.geometry(f"+{x}+{y}")
1136
+
1137
+ def _pick_encoding(self) -> None:
1138
+ """Abre diálogo para escolher a codificação do arquivo."""
1139
+ t = self._tmgr.theme
1140
+ dlg = tk.Toplevel(self._root)
1141
+ dlg.title("Select Encoding")
1142
+ dlg.configure(bg=t.floating_bg)
1143
+ dlg.transient(self._root)
1144
+ safe_grab_set(dlg)
1145
+ dlg.resizable(False, False)
1146
+
1147
+ tk.Label(
1148
+ dlg,
1149
+ text=_t("hc.app.file_encoding"),
1150
+ bg=t.floating_bg,
1151
+ fg=t.fg,
1152
+ font=(FONT_UI, 11, "bold"),
1153
+ ).pack(padx=20, pady=(14, 6))
1154
+
1155
+ encodings = [
1156
+ ("UTF-8", "Unicode, all languages (recommended)"),
1157
+ ("UTF-8-BOM", "UTF-8 with BOM (Windows compatibility)"),
1158
+ ("UTF-16", "16-bit Unicode"),
1159
+ ("UTF-16-LE", "UTF-16 Little Endian"),
1160
+ ("UTF-16-BE", "UTF-16 Big Endian"),
1161
+ ("LATIN-1", "ISO-8859-1, Western European"),
1162
+ ("CP1252", "Windows Western European"),
1163
+ ("CP1251", "Windows Cyrillic"),
1164
+ ("GB2312", "Simplified Chinese"),
1165
+ ("BIG5", "Traditional Chinese"),
1166
+ ("SHIFT-JIS", "Japanese"),
1167
+ ("EUC-KR", "Korean"),
1168
+ ]
1169
+
1170
+ cur_enc = (
1171
+ self._e().encoding
1172
+ if self._e() and hasattr(self._e(), "encoding")
1173
+ else "UTF-8"
1174
+ ).upper()
1175
+
1176
+ _ = tk.StringVar(value=cur_enc)
1177
+
1178
+ lf = tk.Frame(dlg, bg=t.floating_bg)
1179
+ lf.pack(fill="both", expand=True, padx=12, pady=4)
1180
+ lb = tk.Listbox(
1181
+ lf,
1182
+ bg=t.sidebar_bg,
1183
+ fg=t.fg,
1184
+ selectbackground=t.sel_bg,
1185
+ selectforeground=t.sel_fg,
1186
+ relief="flat",
1187
+ bd=0,
1188
+ font=(FONT_UI, 10),
1189
+ activestyle="none",
1190
+ highlightthickness=1,
1191
+ highlightbackground=t.border,
1192
+ width=48,
1193
+ height=12,
1194
+ )
1195
+ vsb = tk.Scrollbar(
1196
+ lf,
1197
+ command=lb.yview,
1198
+ bg=t.scroll_thumb,
1199
+ troughcolor=t.scroll_bg,
1200
+ relief="flat",
1201
+ bd=0,
1202
+ width=6,
1203
+ )
1204
+ vsb.pack(side="right", fill="y")
1205
+ lb.config(yscrollcommand=vsb.set)
1206
+ lb.pack(fill="both", expand=True)
1207
+
1208
+ for enc, desc in encodings:
1209
+ lb.insert("end", f" {enc:<14} {desc}")
1210
+
1211
+ for i, (enc, _) in enumerate(encodings):
1212
+ if enc == cur_enc:
1213
+ lb.selection_set(i)
1214
+ lb.see(i)
1215
+ break
1216
+
1217
+ def _apply(*_):
1218
+ sel = lb.curselection()
1219
+ if sel:
1220
+ enc = encodings[sel[0]][0]
1221
+ e = self._e()
1222
+ if e and e.set_save_encoding(enc):
1223
+ self._status.set_encoding(e.encoding)
1224
+ dlg.destroy()
1225
+
1226
+ lb.bind("<Double-Button-1>", _apply)
1227
+ lb.bind("<Return>", _apply)
1228
+
1229
+ bf = tk.Frame(dlg, bg=t.floating_bg)
1230
+ bf.pack(fill="x", padx=12, pady=(4, 14))
1231
+ for text, cmd in (("OK", _apply), ("Cancel", dlg.destroy)):
1232
+ b = tk.Label(
1233
+ bf,
1234
+ text=text,
1235
+ bg=t.btn_bg,
1236
+ fg=t.fg,
1237
+ font=(FONT_UI, 9),
1238
+ cursor="hand2",
1239
+ padx=14,
1240
+ pady=4,
1241
+ relief="flat",
1242
+ )
1243
+ b.pack(side="right", padx=3)
1244
+ b.bind("<Button-1>", lambda _, c=cmd: c())
1245
+ b.bind("<Enter>", lambda _, w=b: w.config(bg=t.btn_hover))
1246
+ b.bind("<Leave>", lambda _, w=b: w.config(bg=t.btn_bg))
1247
+
1248
+ dlg.update_idletasks()
1249
+ x = (
1250
+ self._root.winfo_rootx()
1251
+ + (self._root.winfo_width() - dlg.winfo_width()) // 2
1252
+ )
1253
+ y = (
1254
+ self._root.winfo_rooty()
1255
+ + (self._root.winfo_height() - dlg.winfo_height()) // 2
1256
+ )
1257
+ dlg.geometry(f"+{x}+{y}")
1258
+
1259
+ def _pick_indent(self) -> None:
1260
+ """Abre diálogo para configurar indentação (tabs vs espaços, tamanho)."""
1261
+ t = self._tmgr.theme
1262
+ dlg = tk.Toplevel(self._root)
1263
+ dlg.title("Indentation")
1264
+ dlg.configure(bg=t.floating_bg)
1265
+ dlg.transient(self._root)
1266
+ safe_grab_set(dlg)
1267
+ dlg.resizable(False, False)
1268
+
1269
+ tk.Label(
1270
+ dlg,
1271
+ text=_t("hc.app.indentation_settings"),
1272
+ bg=t.floating_bg,
1273
+ fg=t.fg,
1274
+ font=(FONT_UI, 11, "bold"),
1275
+ ).pack(padx=20, pady=(14, 6))
1276
+
1277
+ use_spaces = self._cfg.get("use_spaces", True)
1278
+ indent_var = tk.StringVar(value="spaces" if use_spaces else "tabs")
1279
+ for val, lbl in (("spaces", "Spaces"), ("tabs", "Tabs")):
1280
+ tk.Radiobutton(
1281
+ dlg,
1282
+ text=lbl,
1283
+ variable=indent_var,
1284
+ value=val,
1285
+ bg=t.floating_bg,
1286
+ fg=t.fg,
1287
+ activebackground=t.floating_bg,
1288
+ selectcolor=t.input_bg,
1289
+ font=(FONT_UI, 10),
1290
+ ).pack(anchor="w", padx=20, pady=2)
1291
+
1292
+ tk.Label(
1293
+ dlg,
1294
+ text=_t("hc.app.tab_size"),
1295
+ bg=t.floating_bg,
1296
+ fg=t.fg,
1297
+ font=(FONT_UI, 10),
1298
+ ).pack(anchor="w", padx=20, pady=(8, 2))
1299
+ size_var = tk.IntVar(value=self._cfg.get("tab_size", TAB_SIZE))
1300
+ sf = tk.Frame(dlg, bg=t.floating_bg)
1301
+ sf.pack(padx=20, pady=2)
1302
+ for sz in (2, 4, 8):
1303
+ tk.Radiobutton(
1304
+ sf,
1305
+ text=str(sz),
1306
+ variable=size_var,
1307
+ value=sz,
1308
+ bg=t.floating_bg,
1309
+ fg=t.fg,
1310
+ activebackground=t.floating_bg,
1311
+ selectcolor=t.input_bg,
1312
+ font=(FONT_UI, 10),
1313
+ ).pack(side="left", padx=8)
1314
+
1315
+ def _apply(*_):
1316
+ use_sp = indent_var.get() == "spaces"
1317
+ size = size_var.get()
1318
+ self._cfg.set("use_spaces", use_sp)
1319
+ self._cfg.set("tab_size", size)
1320
+ for e in self._editors:
1321
+ e.apply_config(self._cfg)
1322
+ self._status.set_indent(size, not use_sp)
1323
+ dlg.destroy()
1324
+
1325
+ btn_frame = tk.Frame(dlg, bg=t.floating_bg)
1326
+ btn_frame.pack(fill="x", padx=16, pady=(10, 14))
1327
+ for text, cmd in (("OK", _apply), ("Cancel", dlg.destroy)):
1328
+ b = tk.Label(
1329
+ btn_frame,
1330
+ text=text,
1331
+ bg=t.btn_bg,
1332
+ fg=t.fg,
1333
+ font=(FONT_UI, 9),
1334
+ cursor="hand2",
1335
+ padx=14,
1336
+ pady=4,
1337
+ )
1338
+ b.pack(side="right", padx=4)
1339
+ b.bind("<Button-1>", lambda _, c=cmd: c())
1340
+ b.bind("<Enter>", lambda _, w=b: w.config(bg=t.btn_hover))
1341
+ b.bind("<Leave>", lambda _, w=b: w.config(bg=t.btn_bg))
1342
+
1343
+ dlg.update_idletasks()
1344
+ x = (
1345
+ self._root.winfo_rootx()
1346
+ + (self._root.winfo_width() - dlg.winfo_width()) // 2
1347
+ )
1348
+ y = (
1349
+ self._root.winfo_rooty()
1350
+ + (self._root.winfo_height() - dlg.winfo_height()) // 2
1351
+ )
1352
+ dlg.geometry(f"+{x}+{y}")
1353
+
1354
+ def _reset_zoom(self) -> None:
1355
+ """Abre diálogo para escolher o nível de zoom."""
1356
+ t = self._tmgr.theme
1357
+ dlg = tk.Toplevel(self._root)
1358
+ dlg.title("Zoom")
1359
+ dlg.configure(bg=t.floating_bg)
1360
+ dlg.transient(self._root)
1361
+ safe_grab_set(dlg)
1362
+ dlg.resizable(False, False)
1363
+
1364
+ tk.Label(
1365
+ dlg,
1366
+ text=_t("hc.app.editor_zoom"),
1367
+ bg=t.floating_bg,
1368
+ fg=t.fg,
1369
+ font=(FONT_UI, 11, "bold"),
1370
+ ).pack(padx=20, pady=(14, 6))
1371
+
1372
+ cur = self._zoom_pct
1373
+ var = tk.IntVar(value=cur)
1374
+ levels = [50, 75, 90, 100, 110, 125, 150, 175, 200]
1375
+
1376
+ for pct in levels:
1377
+ row = tk.Frame(dlg, bg=t.floating_bg, cursor="hand2")
1378
+ row.pack(fill="x", padx=20, pady=1)
1379
+ rb = tk.Radiobutton(
1380
+ row,
1381
+ text=f"{pct}%",
1382
+ variable=var,
1383
+ value=pct,
1384
+ bg=t.floating_bg,
1385
+ fg=t.fg,
1386
+ activebackground=t.floating_bg,
1387
+ selectcolor=t.input_bg,
1388
+ font=(FONT_UI, 10),
1389
+ )
1390
+ rb.pack(anchor="w")
1391
+ if pct == cur:
1392
+ rb.config(fg=t.accent)
1393
+
1394
+ def _apply(*_):
1395
+ target = var.get()
1396
+
1397
+ self._zoom_pct = 100
1398
+ for e in self._editors:
1399
+ e.zoom(0)
1400
+ steps = (target - 100) // 10
1401
+ for e in self._editors:
1402
+ for _ in range(abs(steps)):
1403
+ e.zoom(1 if steps > 0 else -1)
1404
+ self._zoom_pct = target
1405
+ self._status.set_zoom(self._zoom_pct)
1406
+ dlg.destroy()
1407
+
1408
+ bf = tk.Frame(dlg, bg=t.floating_bg)
1409
+ bf.pack(fill="x", padx=16, pady=(8, 14))
1410
+ for text, cmd in (
1411
+ ("Reset (100%)", lambda: (var.set(100), _apply())),
1412
+ ("OK", _apply),
1413
+ ("Cancel", dlg.destroy),
1414
+ ):
1415
+ b = tk.Label(
1416
+ bf,
1417
+ text=text,
1418
+ bg=t.btn_bg,
1419
+ fg=t.fg,
1420
+ font=(FONT_UI, 9),
1421
+ cursor="hand2",
1422
+ padx=12,
1423
+ pady=4,
1424
+ relief="flat",
1425
+ )
1426
+ b.pack(side="right", padx=3)
1427
+ b.bind("<Button-1>", lambda _, c=cmd: c())
1428
+ b.bind("<Enter>", lambda _, w=b: w.config(bg=t.btn_hover))
1429
+ b.bind("<Leave>", lambda _, w=b: w.config(bg=t.btn_bg))
1430
+
1431
+ dlg.update_idletasks()
1432
+ x = (
1433
+ self._root.winfo_rootx()
1434
+ + (self._root.winfo_width() - dlg.winfo_width()) // 2
1435
+ )
1436
+ y = (
1437
+ self._root.winfo_rooty()
1438
+ + (self._root.winfo_height() - dlg.winfo_height()) // 2
1439
+ )
1440
+ dlg.geometry(f"+{x}+{y}")
1441
+
1442
+ def _init_exclusive_features(self) -> None:
1443
+ """Inicializa funcionalidades exclusivas que dependem de janela e bus prontos."""
1444
+ self._zen_media_player = ZenMediaPlayer(tk_root=self._root)
1445
+
1446
+ _playlist_salva = self._cfg.get("zen_media_playlist", [])
1447
+ if _playlist_salva:
1448
+ self._zen_media_player.set_playlist(_playlist_salva)
1449
+
1450
+ if "kui" not in THEMES:
1451
+ ng_theme = build_kui_theme()
1452
+ _patch_theme(ng_theme)
1453
+ THEMES["kui"] = ng_theme
1454
+ if "kui" not in THEME_ORDER:
1455
+ THEME_ORDER.append("kui")
1456
+
1457
+ if self._cfg.get("kui_enabled", False):
1458
+ self._root.after(400, self._enable_kui)
1459
+
1460
+ if self._cfg.get("vim_mode", False):
1461
+ self._root.after(500, self._enable_vim_mode)
1462
+
1463
+ self._easter_eggs = EasterEggManager(
1464
+ self._root,
1465
+ self._tmgr,
1466
+ self._e,
1467
+ self._status.notify,
1468
+ editor_container_getter=lambda: getattr(
1469
+ self, "_editor_container", None),
1470
+ cfg=getattr(self, "_cfg", None),
1471
+ )
1472
+
1473
+ self._root.after(100, self._connect_terminal_easter_eggs)
1474
+
1475
+ self._root.bind("<Control-Alt-v>",
1476
+ lambda _: self._toggle_vim_mode(), add=True)
1477
+ self._root.bind("<Control-Alt-V>",
1478
+ lambda _: self._toggle_vim_mode(), add=True)
1479
+ self._root.bind(
1480
+ "<Control-Alt-n>", lambda _: self._toggle_kui(), add=True
1481
+ )
1482
+ self._root.bind(
1483
+ "<Control-Alt-N>", lambda _: self._toggle_kui(), add=True
1484
+ )
1485
+
1486
+ self._root.after(800, self._init_accessibility)
1487
+ self._root.after(1500, self._init_screen_reader_global)
1488
+ self._root.after(1200, self._init_performance_monitor)