codis 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
@@ -0,0 +1,1355 @@
1
+ """Pesquisa global em arquivos do Codis.
2
+
3
+ Implementa ``FindInFilesPanel``, painel com busca por texto ou regex em
4
+ todos os arquivos do projeto, com preview de resultados, substituição
5
+ em lote e filtros por extensão e diretório.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import fnmatch
12
+ import logging
13
+ import os
14
+ import re
15
+ import threading
16
+ import tkinter as tk
17
+ from collections.abc import Callable
18
+ from pathlib import Path
19
+ from tkinter import messagebox, ttk
20
+ from typing import Any
21
+
22
+ from src import fs_ops
23
+ from src.config import ConfigManager
24
+ from src.constants import FONT_MONO, FONT_UI, SKIP_DIRS
25
+ from src.editor.autocomplete import IgnoreRules
26
+ from src.fileio import write_atomic
27
+ from src.i18n import _t
28
+ from src.theme.base import Theme
29
+ from src.theme.manager import ThemeManager
30
+ from src.ui.grab_safe import safe_grab_set
31
+ from src.ui.search_bar import _SearchEngine
32
+
33
+ logger = logging.getLogger("Codis")
34
+
35
+
36
+ class FindInFilesPanel(tk.Frame):
37
+ """
38
+ Busca recursiva em arquivos - high-performance rewrite:
39
+
40
+ Backend:
41
+ - os.scandir recursivo manual (mais rápido que os.walk)
42
+ - Leitura mmap-like: lê arquivo uma vez, busca com regex em texto
43
+ - Worker thread com cancelamento imediato via threading.Event
44
+ - Batch de resultados a cada 50 hits (UI nunca trava)
45
+ - Pré-compilação de pattern antes de iniciar thread
46
+ - Suporte a múltiplos globs separados por vírgula (*.py,*.js)
47
+ - Exclusão de pastas via glob negativo (ex: !node_modules)
48
+ - IgnoreRules (.gitignore) respeitado opcionalmente
49
+ - Replace All multi-arquivo com preview e rollback (undo por arquivo)
50
+ - Contador de arquivos e matches em tempo real
51
+
52
+ UX:
53
+ - Resultado em árvore expansível: arquivo > linha > preview
54
+ - Preview colorido com match em destaque (inline highlight)
55
+ - Clique simples seleciona; Enter/duplo clique abre na linha
56
+ - Atalhos: Ctrl+Enter = buscar, Escape = cancelar, F5 = rerun
57
+ - Botão "Copiar resultados" para clipboard (como grep output)
58
+ - Filtros rápidos: arquivo atual, pasta atual, workspace inteiro
59
+ - Indicador de progresso (arquivos varredos / hits encontrados)
60
+ - Sort dos resultados: por relevância, nome de arquivo, linha
61
+ """
62
+
63
+ _BATCH_SIZE = 50
64
+ _HIST_MAX = 50
65
+ SKIP_DIRS = SKIP_DIRS
66
+
67
+ def __init__(
68
+ self,
69
+ parent: tk.Widget,
70
+ tmgr: ThemeManager,
71
+ cfg: ConfigManager,
72
+ get_root: Callable[[], Path | None],
73
+ get_editor: Callable,
74
+ on_open: Callable[[Path, int], None],
75
+ ) -> None:
76
+ t = tmgr.theme
77
+ super().__init__(parent, bg=t.sidebar_bg)
78
+ self._tmgr = tmgr
79
+ self._cfg = cfg
80
+ self._get_root = get_root
81
+ self._get_editor = get_editor
82
+ self._on_open = on_open
83
+
84
+ self._cancel = threading.Event()
85
+ self._thread: threading.Thread | None = None
86
+ self._result_map: dict[str, tuple[Path, int]] = {}
87
+ self._file_nodes: dict[str, str] = {}
88
+ self._seen: set = set()
89
+ self._total_hits = 0
90
+ self._total_files = 0
91
+
92
+ self._re_var = tk.BooleanVar(value=False)
93
+ self._case_var = tk.BooleanVar(value=False)
94
+ self._word_var = tk.BooleanVar(value=False)
95
+ self._keep_var = tk.BooleanVar(value=False)
96
+ self._scope_var = tk.StringVar(value="workspace")
97
+ self._respect_ignore = tk.BooleanVar(value=True)
98
+
99
+ self._q_history: list[str] = []
100
+ self._r_history: list[str] = []
101
+ self._q_hist_pos = -1
102
+ self._r_hist_pos = -1
103
+
104
+ self._ignore_rules: IgnoreRules | None = None
105
+
106
+ self._replace_undo_stack: list[list[tuple]] = []
107
+
108
+ self._build()
109
+
110
+ def set_root(self, path: Path | None) -> None:
111
+ """Carrega as regras de ignore (.gitignore) da pasta usada nas buscas."""
112
+ if path and path.is_dir():
113
+ with contextlib.suppress(tk.TclError):
114
+ self._ignore_rules = IgnoreRules(path)
115
+ else:
116
+ self._ignore_rules = None
117
+
118
+ def _build(self) -> None:
119
+ t = self._tmgr.theme
120
+
121
+ ekw = {
122
+ "bg": t.input_bg,
123
+ "fg": t.fg,
124
+ "insertbackground": t.cursor,
125
+ "relief": "flat",
126
+ "bd": 0,
127
+ "font": (FONT_UI, 9),
128
+ "highlightthickness": 1,
129
+ "highlightbackground": t.border,
130
+ }
131
+
132
+ hdr = tk.Frame(self, bg=t.sidebar_bg, height=36)
133
+ hdr.pack(fill="x")
134
+ hdr.pack_propagate(False)
135
+ tk.Label(
136
+ hdr,
137
+ text=_t("fif.title"),
138
+ bg=t.sidebar_bg,
139
+ fg=t.fg_muted,
140
+ font=(FONT_UI, 9, "bold"),
141
+ ).pack(side="left", padx=4)
142
+
143
+ exp_btn = tk.Label(
144
+ hdr,
145
+ text="⊞",
146
+ bg=t.sidebar_bg,
147
+ fg=t.fg_muted,
148
+ font=(FONT_UI, 11),
149
+ cursor="hand2",
150
+ padx=6,
151
+ )
152
+ exp_btn.pack(side="right")
153
+ exp_btn.bind("<Button-1>", lambda _: self._toggle_all_nodes(True))
154
+ col_btn = tk.Label(
155
+ hdr,
156
+ text="⊟",
157
+ bg=t.sidebar_bg,
158
+ fg=t.fg_muted,
159
+ font=(FONT_UI, 11),
160
+ cursor="hand2",
161
+ padx=2,
162
+ )
163
+ col_btn.pack(side="right")
164
+ col_btn.bind("<Button-1>", lambda _: self._toggle_all_nodes(False))
165
+
166
+ q_outer = tk.Frame(self, bg=t.sidebar_bg)
167
+ q_outer.pack(fill="x", padx=6, pady=(4, 1))
168
+ tk.Label(
169
+ q_outer,
170
+ text=_t("fif.search_lbl"),
171
+ bg=t.sidebar_bg,
172
+ fg=t.fg_muted,
173
+ font=(FONT_UI, 8),
174
+ ).pack(side="left")
175
+ self._q_var = tk.StringVar()
176
+ self._q_entry = tk.Entry(q_outer, textvariable=self._q_var, **ekw)
177
+ self._q_entry.pack(side="left", fill="x",
178
+ expand=True, padx=(4, 0), ipady=2)
179
+ self._q_entry.bind("<Return>", lambda _: self._start())
180
+ self._q_entry.bind("<F5>", lambda _: self._start())
181
+ self._q_entry.bind("<Escape>", lambda _: self._cancel_search())
182
+ self._q_entry.bind("<Up>", self._hist_q_up)
183
+ self._q_entry.bind("<Down>", self._hist_q_down)
184
+ self._q_entry.bind("<Control-Return>", lambda _: self._start())
185
+
186
+ r_outer = tk.Frame(self, bg=t.sidebar_bg)
187
+ r_outer.pack(fill="x", padx=6, pady=(1, 1))
188
+ tk.Label(
189
+ r_outer,
190
+ text=_t("fif.replace_lbl"),
191
+ bg=t.sidebar_bg,
192
+ fg=t.fg_muted,
193
+ font=(FONT_UI, 8),
194
+ ).pack(side="left")
195
+ self._r_var = tk.StringVar()
196
+ self._r_entry = tk.Entry(r_outer, textvariable=self._r_var, **ekw)
197
+ self._r_entry.pack(side="left", fill="x",
198
+ expand=True, padx=(4, 0), ipady=2)
199
+ self._r_entry.bind("<Up>", self._hist_r_up)
200
+ self._r_entry.bind("<Down>", self._hist_r_down)
201
+
202
+ f_outer = tk.Frame(self, bg=t.sidebar_bg)
203
+ f_outer.pack(fill="x", padx=6, pady=(1, 2))
204
+ tk.Label(
205
+ f_outer,
206
+ text=_t("fif.files_lbl"),
207
+ bg=t.sidebar_bg,
208
+ fg=t.fg_muted,
209
+ font=(FONT_UI, 8),
210
+ ).pack(side="left")
211
+ self._f_var = tk.StringVar()
212
+ self._f_entry = tk.Entry(f_outer, textvariable=self._f_var, **ekw)
213
+ self._f_entry.pack(side="left", fill="x",
214
+ expand=True, padx=(4, 0), ipady=2)
215
+ self._f_entry.insert(0, "*.py,*.js,*.ts,*.html,*.css,*.md")
216
+ self._f_entry.bind("<Return>", lambda _: self._start())
217
+ self._tip(
218
+ self._f_entry,
219
+ "Filtro de arquivos (globs separados por vírgula)\n"
220
+ "Ex: *.py,*.js ou * para todos\n"
221
+ "Prefixe com ! para excluir: !*.pyc,!*.min.js",
222
+ )
223
+
224
+ opts = tk.Frame(self, bg=t.sidebar_bg)
225
+ opts.pack(fill="x", padx=6, pady=2)
226
+
227
+ for var, text, tip in (
228
+ (self._re_var, ".*", "Expressão regular"),
229
+ (self._case_var, "Aa", "Case sensitive"),
230
+ (self._word_var, "\\b", "Palavra inteira"),
231
+ ):
232
+ cb = tk.Label(
233
+ opts,
234
+ text=text,
235
+ bg=t.btn_bg,
236
+ fg=t.fg_muted,
237
+ font=(FONT_MONO, 9),
238
+ padx=6,
239
+ pady=1,
240
+ cursor="hand2",
241
+ relief="flat",
242
+ highlightthickness=1,
243
+ highlightbackground=t.border,
244
+ )
245
+ cb.pack(side="left", padx=2)
246
+ self._tip(cb, tip)
247
+
248
+ def _make_toggle(v=var, w=cb):
249
+ def _toggle(_e=None):
250
+ v.set(not v.get())
251
+ t2 = self._tmgr.theme
252
+ w.config(
253
+ bg=t2.accent if v.get() else t2.btn_bg,
254
+ fg="#ffffff" if v.get() else t2.fg_muted,
255
+ )
256
+
257
+ w.bind("<Button-1>", _toggle)
258
+
259
+ _make_toggle()
260
+
261
+ tk.Frame(opts, bg=t.border, width=1).pack(
262
+ side="left", fill="y", padx=4, pady=2)
263
+
264
+ for label, val in (
265
+ ("🌐 Workspace", "workspace"),
266
+ ("📁 Pasta", "folder"),
267
+ ("📄 Arquivo", "file"),
268
+ ):
269
+ rb = tk.Label(
270
+ opts,
271
+ text=label,
272
+ bg=t.btn_bg,
273
+ fg=t.fg_muted,
274
+ font=(FONT_UI, 7),
275
+ padx=5,
276
+ pady=1,
277
+ cursor="hand2",
278
+ relief="flat",
279
+ )
280
+ rb.pack(side="left", padx=1)
281
+
282
+ def _make_rb(v=val, w=rb):
283
+ def _click(_e=None):
284
+ self._scope_var.set(v)
285
+ self._update_scope_btns()
286
+
287
+ w.bind("<Button-1>", _click)
288
+
289
+ _make_rb()
290
+ [
291
+ c
292
+ for c in opts.winfo_children()
293
+ if isinstance(c, tk.Label) and "scope" not in str(c)
294
+ ]
295
+
296
+ tk.Checkbutton(
297
+ opts,
298
+ text=".gitignore",
299
+ variable=self._respect_ignore,
300
+ bg=t.sidebar_bg,
301
+ fg=t.fg_muted,
302
+ activebackground=t.sidebar_bg,
303
+ selectcolor=t.sel_bg,
304
+ font=(FONT_UI, 7),
305
+ ).pack(side="right", padx=2)
306
+
307
+ actions = tk.Frame(self, bg=t.sidebar_bg)
308
+ actions.pack(fill="x", padx=6, pady=(2, 4))
309
+
310
+ self._search_btn = self._abtn(
311
+ actions,
312
+ "🔍 Buscar",
313
+ self._start,
314
+ t.accent,
315
+ tooltip=_t("hc.find_in_files.iniciar_busca_ctrl_enter"),
316
+ )
317
+ self._cancel_btn = self._abtn(
318
+ actions,
319
+ "✕ Parar",
320
+ self._cancel_search,
321
+ t.err_fg,
322
+ tooltip=_t("hc.find_in_files.cancelar_busca_escape"),
323
+ )
324
+ self._cancel_btn.config(state="disabled")
325
+
326
+ tk.Frame(actions, bg=t.sidebar_bg, width=6).pack(side="left")
327
+
328
+ self._abtn(
329
+ actions,
330
+ "⇄ Subst. Tudo",
331
+ self._replace_all,
332
+ getattr(t, "warn_fg", "#f0a500"),
333
+ tooltip=_t("hc.find_in_files.substituir_em_todos_os_arquivo"),
334
+ )
335
+
336
+ self._abtn(
337
+ actions,
338
+ "↩ Desfazer",
339
+ self._undo_last_replace,
340
+ t.fg,
341
+ tooltip=_t("fif.replace_preview_undo"),
342
+ )
343
+
344
+ self._abtn(
345
+ actions,
346
+ "⎘ Copiar",
347
+ self._copy_results,
348
+ t.fg_muted,
349
+ tooltip=_t("hc.find_in_files.copiar_resultados_como_texto_e"),
350
+ )
351
+
352
+ self._status = tk.Label(
353
+ self, text="", bg=t.sidebar_bg, fg=t.fg_muted, font=(FONT_UI, 8), anchor="w"
354
+ )
355
+ self._status.pack(fill="x", padx=8, pady=(1, 2))
356
+
357
+ self._prog = tk.Canvas(
358
+ self, height=2, bg=t.sidebar_bg, highlightthickness=0)
359
+ self._prog.pack(fill="x", padx=0)
360
+ self._prog_max = 0
361
+
362
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x")
363
+
364
+ tree_outer = tk.Frame(self, bg=t.sidebar_bg)
365
+ tree_outer.pack(fill="both", expand=True)
366
+
367
+ vsb = ttk.Scrollbar(
368
+ tree_outer, orient="vertical", style="Thin.Vertical.TScrollbar"
369
+ )
370
+ vsb.pack(side="right", fill="y")
371
+ hsb = ttk.Scrollbar(
372
+ tree_outer, orient="horizontal", style="Thin.Horizontal.TScrollbar"
373
+ )
374
+ hsb.pack(side="bottom", fill="x")
375
+
376
+ self._tree = ttk.Treeview(
377
+ tree_outer,
378
+ columns=("preview",),
379
+ show="tree headings",
380
+ style="CE.Treeview",
381
+ selectmode="browse",
382
+ )
383
+ self._tree.heading("#0", text=_t("fif.file_line"))
384
+ self._tree.heading("preview", text=_t("fif.preview"))
385
+ self._tree.column("#0", width=140, minwidth=80, stretch=False)
386
+ self._tree.column("preview", width=300, minwidth=120)
387
+ self._tree.config(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
388
+ self._tree.pack(side="left", fill="both", expand=True)
389
+ vsb.config(command=self._tree.yview)
390
+ hsb.config(command=self._tree.xview)
391
+
392
+ self._tree.bind("<Double-Button-1>", self._on_activate)
393
+ self._tree.bind("<Return>", self._on_activate)
394
+ self._tree.bind("<Button-1>", self._on_single_click)
395
+
396
+ self._tree.tag_configure("file_row", font=(
397
+ FONT_UI, 9, "bold"), foreground=t.fg)
398
+ self._tree.tag_configure(
399
+ "hit_row", font=(FONT_MONO, 8), foreground=t.comment_fg
400
+ )
401
+
402
+ def _abtn(
403
+ self, parent: tk.Widget, text: str, cmd: Callable, color: str, tooltip: str = ""
404
+ ) -> tk.Button:
405
+ """Cria e retorna um botão de ação estilizado.
406
+
407
+ Args:
408
+ parent: Widget pai Tkinter.
409
+ text: Dado textual a processar.
410
+ """
411
+ t = self._tmgr.theme
412
+ b = tk.Button(
413
+ parent,
414
+ text=text,
415
+ bg=t.btn_bg,
416
+ fg=color,
417
+ relief="flat",
418
+ padx=8,
419
+ pady=2,
420
+ font=(FONT_UI, 8),
421
+ cursor="hand2",
422
+ highlightthickness=0,
423
+ command=cmd,
424
+ )
425
+ b.pack(side="left", padx=2)
426
+ b.bind("<Enter>", lambda _: b.config(bg=t.btn_hover))
427
+ b.bind("<Leave>", lambda _: b.config(bg=t.btn_bg))
428
+ if tooltip:
429
+ self._tip(b, tooltip)
430
+ return b
431
+
432
+ def _tip(self, widget: tk.Widget, text: str) -> None:
433
+ """Exibe tooltip para o widget indicado.
434
+
435
+ Args:
436
+ text: Dado textual a processar.
437
+ """
438
+ _state: dict = {"win": None, "after_id": None}
439
+
440
+ def _make(x: int, y: int) -> None:
441
+ if _state.get("win") and _state["win"].winfo_exists():
442
+ _state["win"].destroy()
443
+ t = self._tmgr.theme
444
+ tw = tk.Toplevel(widget)
445
+ tw.wm_overrideredirect(True)
446
+ tw.wm_attributes("-topmost", True)
447
+ fr = tk.Frame(tw, bg=t.floating_border, bd=1)
448
+ fr.pack()
449
+ tk.Frame(fr, bg=t.floating_bg, padx=8, pady=4).pack()
450
+ inner = fr.winfo_children()[-1]
451
+ tk.Label(
452
+ inner,
453
+ text=text,
454
+ bg=t.floating_bg,
455
+ fg=t.fg,
456
+ font=(FONT_UI, 8),
457
+ justify="left",
458
+ wraplength=320,
459
+ ).pack()
460
+ tw.geometry(f"+{x + 10}+{y + 12}")
461
+ _state["win"] = tw
462
+
463
+ def _destroy(_e=None):
464
+ if _state.get("after_id"):
465
+ with contextlib.suppress(tk.TclError):
466
+ widget.after_cancel(_state["after_id"])
467
+ _state["after_id"] = None
468
+ if _state.get("win"):
469
+ with contextlib.suppress(tk.TclError):
470
+ _state["win"].destroy()
471
+ _state["win"] = None
472
+
473
+ def _enter(e: tk.Event):
474
+ _state["after_id"] = widget.after(
475
+ 500, lambda: _make(e.x_root, e.y_root))
476
+
477
+ widget.bind("<Enter>", _enter, add="+")
478
+ widget.bind("<Leave>", _destroy, add="+")
479
+
480
+ def _update_scope_btns(self) -> None:
481
+ t = self._tmgr.theme
482
+ scope = self._scope_var.get()
483
+ label_map = {
484
+ "workspace": "🌐 Workspace",
485
+ "folder": "📁 Pasta",
486
+ "file": "📄 Arquivo",
487
+ }
488
+ for child in self.winfo_children():
489
+ self._update_scope_recursive(child, scope, label_map, t)
490
+
491
+ def _update_scope_recursive(self, w, scope, label_map, t) -> None:
492
+ with contextlib.suppress(tk.TclError):
493
+ txt = w.cget("text")
494
+ if txt in label_map.values():
495
+ key = next(k for k, v in label_map.items() if v == txt)
496
+ w.config(
497
+ bg=t.accent if key == scope else t.btn_bg,
498
+ fg="#ffffff" if key == scope else t.fg_muted,
499
+ )
500
+ for c in w.winfo_children():
501
+ self._update_scope_recursive(c, scope, label_map, t)
502
+
503
+ def _compile_pattern(self) -> re.Pattern | None:
504
+ """Compila e retorna o padrão regex com as opções de busca ativas."""
505
+ q = self._q_var.get().strip()
506
+ if not q:
507
+ return None
508
+ flags = 0 if self._case_var.get() else re.IGNORECASE
509
+ try:
510
+ if self._re_var.get():
511
+ return re.compile(q, flags)
512
+ if self._word_var.get():
513
+ return re.compile(r"\b" + re.escape(q) + r"\b", flags)
514
+ return re.compile(re.escape(q), flags)
515
+ except re.error as e:
516
+ self._set_status(f"⚠ Regex inválido: {e}")
517
+ return None
518
+
519
+ def _start(self) -> None:
520
+ """Inicia o processo ou animação."""
521
+ pat = self._compile_pattern()
522
+ if pat is None:
523
+ return
524
+
525
+ if not self._keep_var.get():
526
+ self._clear_results()
527
+
528
+ scope = self._scope_var.get()
529
+ if scope == "file":
530
+ editor = self._get_editor()
531
+ if not editor or not editor.path:
532
+ self._set_status("Nenhum arquivo aberto.")
533
+ return
534
+ self._search_file(editor.path, pat, str(editor.path.name))
535
+ return
536
+ if scope == "folder":
537
+ editor = self._get_editor()
538
+ if editor and editor.path:
539
+ root = editor.path.parent
540
+ else:
541
+ root = self._get_root()
542
+ else:
543
+ root = self._get_root()
544
+
545
+ if not root or not root.is_dir():
546
+ self._set_status("Nenhuma pasta aberta.")
547
+ return
548
+
549
+ self._cancel.set()
550
+ if self._thread and self._thread.is_alive():
551
+ self._thread.join(timeout=0.2)
552
+ self._cancel.clear()
553
+
554
+ raw_filter = self._f_var.get().strip() or "*"
555
+ include_globs, exclude_globs = self._parse_globs(raw_filter)
556
+
557
+ if self._respect_ignore.get():
558
+ with contextlib.suppress(tk.TclError):
559
+ self._ignore_rules = IgnoreRules(root)
560
+
561
+ self._search_btn.config(state="disabled")
562
+ self._cancel_btn.config(state="normal")
563
+ self._set_status("Buscando...")
564
+ self._prog_max = 0
565
+
566
+ self._thread = threading.Thread(
567
+ target=self._search_worker,
568
+ args=(root, pat, include_globs, exclude_globs, self._cancel),
569
+ daemon=True,
570
+ )
571
+ self._thread.start()
572
+
573
+ @staticmethod
574
+ def _parse_globs(raw: str) -> tuple[list[str], list[str]]:
575
+ """Separa globs de inclusão e exclusão (prefixo !)."""
576
+ include, exclude = [], []
577
+ for part in raw.split(","):
578
+ part = part.strip()
579
+ if not part:
580
+ continue
581
+ if part.startswith("!"):
582
+ exclude.append(part[1:])
583
+ else:
584
+ include.append(part)
585
+ if not include:
586
+ include = ["*"]
587
+ return include, exclude
588
+
589
+ @staticmethod
590
+ def _matches_globs(name: str, include: list[str], exclude: list[str]) -> bool:
591
+ for pat in exclude:
592
+ if fnmatch.fnmatch(name, pat):
593
+ return False
594
+ return any(pat == "*" or fnmatch.fnmatch(name, pat) for pat in include)
595
+
596
+ def _search_file(self, fpath: Path, pat: re.Pattern, rel: str = "") -> None:
597
+ """Search a single file synchronously (for scope=file mode)."""
598
+ try:
599
+ content = fpath.read_text(encoding="utf-8", errors="replace")
600
+ except (OSError, PermissionError):
601
+ return
602
+ hits = []
603
+ for lno, line in enumerate(content.split("\n"), 1):
604
+ m = pat.search(line)
605
+ if m:
606
+ preview = self._make_preview(line, m.start(), m.end())
607
+ hits.append((lno, preview))
608
+ if hits:
609
+ self.after(
610
+ 0,
611
+ lambda h=hits, r=rel or fpath.name, p=fpath: self._add_file_hits(
612
+ r, h, p
613
+ ),
614
+ )
615
+ self.after(
616
+ 0,
617
+ lambda: self._set_status(
618
+ f"{len(hits)} ocorrência(s) em {rel or fpath.name}"
619
+ ),
620
+ )
621
+
622
+ def _search_worker(
623
+ self,
624
+ root: Path,
625
+ pat: re.Pattern,
626
+ include: list[str],
627
+ exclude: list[str],
628
+ cancel: threading.Event,
629
+ ) -> None:
630
+ total_hits = 0
631
+ total_files = 0
632
+ buffer: list[tuple[str, int, str, Path]] = []
633
+
634
+ def flush():
635
+ """Envia o buffer de resultados acumulados para a UI em lote."""
636
+ nonlocal buffer
637
+ if not buffer:
638
+ return
639
+ by_file: dict[str, list] = {}
640
+ for rel, lno, preview, fpath in buffer:
641
+ by_file.setdefault(rel, []).append((lno, preview, fpath))
642
+ self.after(0, lambda bf=dict(by_file): self._add_batch(bf))
643
+ buffer = []
644
+
645
+ def scan(dir_path: Path) -> None:
646
+ """Varre ``dir_path`` recursivamente em busca de correspondências."""
647
+ nonlocal total_hits, total_files
648
+ with contextlib.suppress(PermissionError), os.scandir(dir_path) as it:
649
+ for entry in it:
650
+ if cancel.is_set():
651
+ return
652
+ if entry.name.startswith(".") and entry.name not in {
653
+ ".htaccess",
654
+ ".env",
655
+ } and entry.is_dir():
656
+ continue
657
+ if entry.is_dir(follow_symlinks=False):
658
+ if entry.name in self.SKIP_DIRS:
659
+ continue
660
+ scan(Path(entry.path))
661
+ elif entry.is_file(follow_symlinks=False):
662
+ if not self._matches_globs(entry.name, include, exclude):
663
+ continue
664
+ fpath = Path(entry.path)
665
+ if (
666
+ self._ignore_rules
667
+ and self._respect_ignore.get()
668
+ and self._ignore_rules.is_ignored(fpath)
669
+ ):
670
+ continue
671
+ try:
672
+ content = fpath.read_text(
673
+ encoding="utf-8", errors="replace"
674
+ )
675
+ except (OSError, PermissionError):
676
+ continue
677
+ try:
678
+ rel = str(fpath.relative_to(root))
679
+ except ValueError:
680
+ rel = fpath.name
681
+ file_hits = []
682
+ for lno, line in enumerate(content.split("\n"), 1):
683
+ if cancel.is_set():
684
+ return
685
+ m = pat.search(line)
686
+ if m:
687
+ key = (rel, lno)
688
+ if key in self._seen:
689
+ continue
690
+ self._seen.add(key)
691
+ preview = self._make_preview(
692
+ line, m.start(), m.end()
693
+ )
694
+ file_hits.append((lno, preview))
695
+ buffer.append((rel, lno, preview, fpath))
696
+ total_hits += 1
697
+ if file_hits:
698
+ total_files += 1
699
+ self.after(
700
+ 0,
701
+ lambda n=total_hits, f=total_files: self._set_status(
702
+ f"{n} ocorrência(s) em {f} arquivo(s)..."
703
+ ),
704
+ )
705
+ if len(buffer) >= self._BATCH_SIZE:
706
+ flush()
707
+ if total_hits >= _SearchEngine.MAX_MATCHES:
708
+ flush()
709
+ self.after(
710
+ 0,
711
+ lambda: self._set_status(
712
+ f"Limite de {_SearchEngine.MAX_MATCHES:,} atingido. "
713
+ "Busca truncada."
714
+ ),
715
+ )
716
+ return
717
+
718
+ scan(root)
719
+ flush()
720
+
721
+ self.after(
722
+ 0,
723
+ lambda n=total_hits, f=total_files: (
724
+ self._set_status(
725
+ f"{n} ocorrência(s) em {f} arquivo(s)"
726
+ if n
727
+ else "Nenhum resultado encontrado."
728
+ ),
729
+ self._search_btn.config(state="normal"),
730
+ self._cancel_btn.config(state="disabled"),
731
+ self._update_progress_bar(1.0),
732
+ ),
733
+ )
734
+
735
+ @staticmethod
736
+ def _make_preview(line: str, ms: int, me: int) -> str:
737
+ """Retorna preview da linha com o match entre ►◄."""
738
+ line = line.strip()
739
+ MAX = 150
740
+ prefix = line[:ms].lstrip()
741
+ match = line[ms:me]
742
+ suffix = line[me:]
743
+
744
+ result = f"{prefix}►{match}◄{suffix}"
745
+ if len(result) > MAX:
746
+ result = result[:MAX] + "..."
747
+ return result
748
+
749
+ def _clear_results(self) -> None:
750
+ """Limpa todos os resultados de busca exibidos no painel."""
751
+ for iid in self._tree.get_children():
752
+ self._tree.delete(iid)
753
+ self._result_map.clear()
754
+ self._file_nodes.clear()
755
+ self._seen.clear()
756
+ self._total_hits = 0
757
+ self._total_files = 0
758
+
759
+ def _add_file_hits(
760
+ self, rel: str, hits: list[tuple[int, str]], fpath: Path
761
+ ) -> None:
762
+ node = self._get_or_create_file_node(rel)
763
+ for lno, preview in hits:
764
+ iid = self._tree.insert(
765
+ node, "end", text=f" {lno}", values=(preview,), tags=("hit_row",)
766
+ )
767
+ self._result_map[iid] = (fpath, lno)
768
+ count = len(self._tree.get_children(node))
769
+ self._tree.item(node, values=(f"{count} resultado(s)",))
770
+
771
+ def _add_batch(self, by_file: dict[str, list]) -> None:
772
+ for rel, hit_list in by_file.items():
773
+ node = self._get_or_create_file_node(rel)
774
+ for lno, preview, fpath in hit_list:
775
+ iid = self._tree.insert(
776
+ node, "end", text=f" {lno}", values=(preview,), tags=("hit_row",)
777
+ )
778
+ self._result_map[iid] = (fpath, lno)
779
+ count = len(self._tree.get_children(node))
780
+ self._tree.item(node, values=(f"{count} resultado(s)",))
781
+
782
+ def _get_or_create_file_node(self, rel: str) -> str:
783
+ """Obtém e retorna 'or create file node'."""
784
+ if rel in self._file_nodes:
785
+ return self._file_nodes[rel]
786
+
787
+ ext = rel.rsplit(".", 1)[-1].lower() if "." in rel else ""
788
+ icon = {
789
+ "py": "py",
790
+ "js": "js",
791
+ "ts": "ts",
792
+ "html": "htm",
793
+ "css": "css",
794
+ "md": "md",
795
+ "json": "{}",
796
+ "yml": "yml",
797
+ "sh": "🖥",
798
+ "cpp": "yml",
799
+ "c": "yml",
800
+ "java": "java",
801
+ "go": "go",
802
+ "rs": "rs",
803
+ }.get(ext, "txt")
804
+ node = self._tree.insert(
805
+ "",
806
+ "end",
807
+ text=f" {icon} {rel}",
808
+ values=("",),
809
+ open=True,
810
+ tags=("file_row",),
811
+ )
812
+ self._file_nodes[rel] = node
813
+ return node
814
+
815
+ def _on_activate(self, _e: Any = None) -> None:
816
+ sel = self._tree.selection()
817
+ if sel and sel[0] in self._result_map:
818
+ path, lno = self._result_map[sel[0]]
819
+ self._on_open(path, lno)
820
+
821
+ def _on_single_click(self, e: Any) -> None:
822
+ iid = self._tree.identify_row(e.y)
823
+ if iid and iid in self._result_map:
824
+ self._tree.selection_set(iid)
825
+
826
+ def _toggle_all_nodes(self, expand: bool) -> None:
827
+ for iid in self._tree.get_children():
828
+ self._tree.item(iid, open=expand)
829
+
830
+ def _replace_all(self) -> None:
831
+ """Abre o dialog de preview antes de substituir.
832
+
833
+ Mostra um diff interativo por arquivo, permite selecionar quais arquivos
834
+ serão modificados e aplica as substituições de forma atômica com suporte
835
+ a rollback completo via botão de desfazer.
836
+ """
837
+ pat = self._compile_pattern()
838
+ repl = self._r_var.get()
839
+ if not pat:
840
+ return
841
+
842
+ paths: set = {fpath for fpath, _ in self._result_map.values()}
843
+ if not paths:
844
+ self._set_status(_t("fif.replace_preview_none"))
845
+ return
846
+ # No modo texto simples a substituição é literal; só em regex vale o template (\1, \n...).
847
+ template = repl if self._re_var.get() else (lambda _m: repl)
848
+ previews: list[dict] = []
849
+ skipped = 0
850
+ for fpath in sorted(paths):
851
+ try:
852
+ raw = fpath.read_bytes()
853
+ except OSError:
854
+ continue
855
+ decoded = fs_ops.decode_for_edit(raw)
856
+ if decoded is None:
857
+ skipped += 1 # não é UTF-8 válido (ou é binário): regravar corromperia o arquivo
858
+ continue
859
+ original, eol = decoded
860
+ try:
861
+ modified, n = pat.subn(template, original)
862
+ except re.error as exc:
863
+ self._set_status(f"Substituição inválida: {exc}")
864
+ return
865
+ if n and modified != original:
866
+ previews.append(
867
+ {"path": fpath, "original": original, "modified": modified, "count": n,
868
+ "eol": eol, "raw": raw}
869
+ )
870
+ if skipped:
871
+ self._set_status(_t("fif.replace_skipped", n=skipped))
872
+ if not previews:
873
+ if not skipped:
874
+ self._set_status(_t("fif.replace_preview_none"))
875
+ return
876
+
877
+ self._show_replace_preview(previews, pat, repl)
878
+
879
+ @staticmethod
880
+ def _apply_replacements(selected: list[dict]) -> tuple[list[tuple], int, list[str]]:
881
+ """Grava as substituições aprovadas; devolve ``(desfazer, total, erros)``.
882
+
883
+ Cada arquivo é gravado de forma atômica, com o final de linha original, e o desfazer
884
+ guarda os bytes de antes para restaurá-lo exatamente.
885
+ """
886
+ undo_batch: list[tuple] = []
887
+ replaced_total = 0
888
+ errors: list[str] = []
889
+ for item in selected:
890
+ fpath = item["path"]
891
+ try:
892
+ write_atomic(fpath, fs_ops.encode_text(item["modified"], item["eol"]))
893
+ except OSError as exc:
894
+ errors.append(f"{fpath.name}: {exc}")
895
+ continue
896
+ undo_batch.append((fpath, item["raw"]))
897
+ replaced_total += item["count"]
898
+ return undo_batch, replaced_total, errors
899
+
900
+ def _show_replace_preview(
901
+ self, previews: list[dict], _pat: re.Pattern, _repl: str
902
+ ) -> None:
903
+ """Exibe o dialog de preview diff interativo para Replace in Files.
904
+
905
+ O dialog lista cada arquivo afetado com checkboxes de seleção
906
+ individual, exibe o diff linha a linha com colorização de adições
907
+ e remoções, e aplica as substituições de forma atômica apenas nos
908
+ arquivos selecionados pelo usuário.
909
+
910
+ Args:
911
+ previews: Lista de dicts com path, original, modified e count.
912
+ _pat: Pattern regex compilado (usado só para exibição de info).
913
+ _repl: String de substituição.
914
+ """
915
+ import difflib as _difflib
916
+
917
+ t = self._tmgr.theme
918
+
919
+ dlg = tk.Toplevel(self)
920
+ dlg.title(_t("fif.replace_preview_title", n=len(previews)))
921
+ dlg.configure(bg=t.floating_bg)
922
+ dlg.transient(self.winfo_toplevel())
923
+ safe_grab_set(dlg)
924
+ dlg.resizable(True, True)
925
+
926
+ sw, sh = dlg.winfo_screenwidth(), dlg.winfo_screenheight()
927
+ w, h = min(1100, sw - 80), min(700, sh - 100)
928
+ x = (sw - w) // 2
929
+ y = (sh - h) // 2
930
+ dlg.geometry(f"{w}x{h}+{x}+{y}")
931
+ dlg.minsize(700, 400)
932
+
933
+ hdr = tk.Frame(dlg, bg=t.floating_bg)
934
+ hdr.pack(fill="x", padx=10, pady=(10, 0))
935
+ total_occ = sum(p["count"] for p in previews)
936
+ adds = sum(
937
+ sum(
938
+ 1
939
+ for ln in _difflib.unified_diff(
940
+ p["original"].splitlines(), p["modified"].splitlines(), lineterm=""
941
+ )
942
+ if ln.startswith("+") and not ln.startswith("+++")
943
+ )
944
+ for p in previews
945
+ )
946
+ rems = sum(
947
+ sum(
948
+ 1
949
+ for ln in _difflib.unified_diff(
950
+ p["original"].splitlines(), p["modified"].splitlines(), lineterm=""
951
+ )
952
+ if ln.startswith("-") and not ln.startswith("---")
953
+ )
954
+ for p in previews
955
+ )
956
+ tk.Label(
957
+ hdr,
958
+ text=_t(
959
+ "fif.replace_preview_changes",
960
+ a=adds,
961
+ r=rems,
962
+ f=len(previews),
963
+ n=total_occ,
964
+ ),
965
+ bg=t.floating_bg,
966
+ fg=t.fg,
967
+ font=(self._tmgr.theme and "Segoe UI" or "TkDefaultFont", 10),
968
+ ).pack(side="left")
969
+
970
+ paned = tk.PanedWindow(
971
+ dlg, orient="horizontal", bg=t.border, sashwidth=5, sashrelief="flat", bd=0
972
+ )
973
+ paned.pack(fill="both", expand=True, padx=10, pady=6)
974
+
975
+ left = tk.Frame(paned, bg=t.sidebar_bg)
976
+ paned.add(left, minsize=200, width=280)
977
+
978
+ tk.Label(
979
+ left,
980
+ text=_t("fif.preview_diff_col_file"),
981
+ bg=t.sidebar_bg,
982
+ fg=t.gutter_fg,
983
+ font=("Segoe UI", 9),
984
+ ).pack(anchor="w", padx=6, pady=(4, 0))
985
+
986
+ list_frame = tk.Frame(left, bg=t.sidebar_bg)
987
+ list_frame.pack(fill="both", expand=True)
988
+ list_vsb = tk.Scrollbar(list_frame, orient="vertical")
989
+ list_vsb.pack(side="right", fill="y")
990
+ file_lb = tk.Listbox(
991
+ list_frame,
992
+ bg=t.sidebar_bg,
993
+ fg=t.fg,
994
+ selectbackground=t.sel_bg,
995
+ selectforeground=t.sel_fg,
996
+ activestyle="none",
997
+ font=("Consolas", 9),
998
+ yscrollcommand=list_vsb.set,
999
+ borderwidth=0,
1000
+ highlightthickness=0,
1001
+ relief="flat",
1002
+ )
1003
+ file_lb.pack(fill="both", expand=True)
1004
+ list_vsb.config(command=file_lb.yview)
1005
+
1006
+ check_vars: list[tk.BooleanVar] = []
1007
+ for p in previews:
1008
+ var = tk.BooleanVar(value=True)
1009
+ check_vars.append(var)
1010
+ label = f"{p['path'].name} +{p['count']}"
1011
+ file_lb.insert("end", label)
1012
+
1013
+ def _refresh_list():
1014
+ file_lb.delete(0, "end")
1015
+ for i, p in enumerate(previews):
1016
+ mark = "+" if check_vars[i].get() else "-"
1017
+ file_lb.insert(
1018
+ "end", f"{mark} {p['path'].name} +{p['count']}")
1019
+
1020
+ def _toggle_item(_e=None):
1021
+ sel = file_lb.curselection()
1022
+ if not sel:
1023
+ return
1024
+ i = sel[0]
1025
+ check_vars[i].set(not check_vars[i].get())
1026
+ _refresh_list()
1027
+ file_lb.selection_set(i)
1028
+ _show_diff(i)
1029
+
1030
+ file_lb.bind("<space>", _toggle_item)
1031
+ file_lb.bind("<Return>", _toggle_item)
1032
+
1033
+ right = tk.Frame(paned, bg=t.editor_bg)
1034
+ paned.add(right, minsize=300)
1035
+
1036
+ diff_hdr = tk.Frame(right, bg=t.panel_bg, height=24)
1037
+ diff_hdr.pack(fill="x")
1038
+ diff_hdr.pack_propagate(False)
1039
+ diff_lbl = tk.Label(
1040
+ diff_hdr, text="", bg=t.panel_bg, fg=t.fg, font=("Segoe UI", 9), anchor="w"
1041
+ )
1042
+ diff_lbl.pack(side="left", padx=8, fill="x", expand=True)
1043
+
1044
+ diff_frame = tk.Frame(right, bg=t.editor_bg)
1045
+ diff_frame.pack(fill="both", expand=True)
1046
+ diff_vsb = tk.Scrollbar(diff_frame, orient="vertical")
1047
+ diff_vsb.pack(side="right", fill="y")
1048
+ diff_hsb = tk.Scrollbar(diff_frame, orient="horizontal")
1049
+ diff_hsb.pack(side="bottom", fill="x")
1050
+ diff_txt = tk.Text(
1051
+ diff_frame,
1052
+ bg=t.editor_bg,
1053
+ fg=t.fg,
1054
+ font=("Consolas", 10),
1055
+ wrap="none",
1056
+ state="disabled",
1057
+ borderwidth=0,
1058
+ highlightthickness=0,
1059
+ relief="flat",
1060
+ yscrollcommand=diff_vsb.set,
1061
+ xscrollcommand=diff_hsb.set,
1062
+ cursor="arrow",
1063
+ insertwidth=0,
1064
+ )
1065
+ diff_txt.pack(fill="both", expand=True)
1066
+ diff_vsb.config(command=diff_txt.yview)
1067
+ diff_hsb.config(command=diff_txt.xview)
1068
+
1069
+ diff_txt.tag_configure(
1070
+ "add", background="#1a3a1a", foreground="#a8ff87")
1071
+ diff_txt.tag_configure(
1072
+ "rem", background="#3a1a1a", foreground="#ff8787")
1073
+ diff_txt.tag_configure(
1074
+ "hunk", background=t.panel_bg, foreground=t.gutter_fg)
1075
+ diff_txt.tag_configure("ctx", foreground=t.fg)
1076
+ diff_txt.tag_configure(
1077
+ "lnum", foreground=t.gutter_fg, background=t.gutter_bg)
1078
+ diff_txt.tag_configure(
1079
+ "match", foreground="#ffdf87", font=("Consolas", 10, "bold")
1080
+ )
1081
+ diff_txt.tag_configure("skip", foreground=t.gutter_fg)
1082
+
1083
+ def _show_diff(idx: int) -> None:
1084
+ """Renderiza o diff do arquivo idx no painel direito."""
1085
+ p = previews[idx]
1086
+ diff_lbl.config(text=str(p["path"]))
1087
+ diff_txt.config(state="normal")
1088
+ diff_txt.delete("1.0", "end")
1089
+ orig_lines = p["original"].splitlines(keepends=True)
1090
+ mod_lines = p["modified"].splitlines(keepends=True)
1091
+ hunks = list(
1092
+ _difflib.unified_diff(
1093
+ orig_lines,
1094
+ mod_lines,
1095
+ fromfile="original",
1096
+ tofile="modified",
1097
+ n=3,
1098
+ lineterm="",
1099
+ )
1100
+ )
1101
+ if not hunks:
1102
+ diff_txt.insert("end", "(sem diferenças)\n", "skip")
1103
+ else:
1104
+ for line in hunks:
1105
+ if line.startswith("---") or line.startswith("+++"):
1106
+ continue
1107
+ if line.startswith("@@"):
1108
+ diff_txt.insert("end", line + "\n", "hunk")
1109
+ elif line.startswith("+"):
1110
+ diff_txt.insert("end", line + "\n", "add")
1111
+ elif line.startswith("-"):
1112
+ diff_txt.insert("end", line + "\n", "rem")
1113
+ else:
1114
+ diff_txt.insert("end", line + "\n", "ctx")
1115
+ diff_txt.config(state="disabled")
1116
+ diff_txt.see("1.0")
1117
+
1118
+ def _on_select(_e=None):
1119
+ sel = file_lb.curselection()
1120
+ if sel:
1121
+ _show_diff(sel[0])
1122
+
1123
+ file_lb.bind("<<ListboxSelect>>", _on_select)
1124
+
1125
+ if previews:
1126
+ file_lb.selection_set(0)
1127
+ _show_diff(0)
1128
+
1129
+ btn_bar = tk.Frame(dlg, bg=t.floating_bg)
1130
+ btn_bar.pack(fill="x", padx=10, pady=(0, 10))
1131
+
1132
+ def _select_all():
1133
+ for v in check_vars:
1134
+ v.set(True)
1135
+ _refresh_list()
1136
+
1137
+ def _deselect_all():
1138
+ for v in check_vars:
1139
+ v.set(False)
1140
+ _refresh_list()
1141
+
1142
+ def _apply():
1143
+ """Aplica as substituições de forma atômica com rollback disponível."""
1144
+ selected = [previews[i]
1145
+ for i, v in enumerate(check_vars) if v.get()]
1146
+ if not selected:
1147
+ self._set_status(_t("fif.replace_preview_none"))
1148
+ dlg.destroy()
1149
+ return
1150
+
1151
+ undo_batch, replaced_total, errors_list = self._apply_replacements(selected)
1152
+
1153
+ if undo_batch:
1154
+ self._replace_undo_stack.append(undo_batch)
1155
+
1156
+ if len(self._replace_undo_stack) > 10:
1157
+ self._replace_undo_stack.pop(0)
1158
+
1159
+ dlg.destroy()
1160
+
1161
+ if errors_list:
1162
+ msg = _t(
1163
+ "fif.replace_atomic_err",
1164
+ n=len(errors_list),
1165
+ ok=len(selected) - len(errors_list),
1166
+ )
1167
+ messagebox.showerror(
1168
+ _t("fif.replace_title", "Substituir em Arquivos"), msg, parent=self
1169
+ )
1170
+ else:
1171
+ self._set_status(
1172
+ _t("fif.replace_atomic_ok", n=len(
1173
+ selected), c=replaced_total)
1174
+ )
1175
+
1176
+ self.after(100, self._start)
1177
+
1178
+ for txt, cmd in (
1179
+ (_t("fif.replace_preview_select_all"), _select_all),
1180
+ (_t("fif.replace_preview_deselect"), _deselect_all),
1181
+ ):
1182
+ b = tk.Button(
1183
+ btn_bar,
1184
+ text=txt,
1185
+ command=cmd,
1186
+ bg=t.btn_bg,
1187
+ fg=t.btn_fg,
1188
+ activebackground=t.btn_hover,
1189
+ activeforeground=t.btn_fg,
1190
+ relief="flat",
1191
+ bd=0,
1192
+ padx=10,
1193
+ pady=4,
1194
+ cursor="hand2",
1195
+ font=("Segoe UI", 9),
1196
+ )
1197
+ b.pack(side="left", padx=(0, 6))
1198
+
1199
+ tk.Frame(btn_bar, bg=t.floating_bg).pack(side="left", expand=True)
1200
+
1201
+ btn_cancel = tk.Button(
1202
+ btn_bar,
1203
+ text=_t("fif.replace_preview_cancel"),
1204
+ command=dlg.destroy,
1205
+ bg=t.btn_bg,
1206
+ fg=t.btn_fg,
1207
+ activebackground=t.btn_hover,
1208
+ activeforeground=t.btn_fg,
1209
+ relief="flat",
1210
+ bd=0,
1211
+ padx=14,
1212
+ pady=4,
1213
+ cursor="hand2",
1214
+ font=("Segoe UI", 9),
1215
+ )
1216
+ btn_cancel.pack(side="right", padx=(6, 0))
1217
+
1218
+ n_selected = sum(1 for v in check_vars if v.get())
1219
+ btn_apply = tk.Button(
1220
+ btn_bar,
1221
+ text=_t("fif.replace_preview_apply", n=n_selected),
1222
+ command=_apply,
1223
+ bg=t.btn_primary,
1224
+ fg=t.btn_primary_fg,
1225
+ activebackground=t.btn_primary,
1226
+ activeforeground=t.btn_primary_fg,
1227
+ relief="flat",
1228
+ bd=0,
1229
+ padx=14,
1230
+ pady=4,
1231
+ cursor="hand2",
1232
+ font=("Segoe UI", 9, "bold"),
1233
+ )
1234
+ btn_apply.pack(side="right")
1235
+
1236
+ def _update_apply_label(_e=None):
1237
+ n = sum(1 for v in check_vars if v.get())
1238
+ btn_apply.config(text=_t("fif.replace_preview_apply", n=n))
1239
+
1240
+ for v in check_vars:
1241
+ v.trace_add("write", lambda *_: _update_apply_label())
1242
+
1243
+ dlg.bind("<Escape>", lambda _: dlg.destroy())
1244
+ dlg.bind("<Control-Return>", lambda _: _apply())
1245
+ dlg.protocol("WM_DELETE_WINDOW", dlg.destroy)
1246
+
1247
+ def _undo_last_replace(self) -> None:
1248
+ """Reverte a última operação de Replace in Files.
1249
+
1250
+ operações de replace para rollback sequencial.
1251
+ """
1252
+ if not self._replace_undo_stack:
1253
+ self._set_status(_t("fif.replace_undo_none"))
1254
+ return
1255
+ batch = self._replace_undo_stack.pop()
1256
+ errors: list[str] = []
1257
+ restored = 0
1258
+ for fpath, original_bytes in batch:
1259
+ try:
1260
+ write_atomic(fpath, original_bytes) # os bytes de antes, sem reinterpretar nada
1261
+ restored += 1
1262
+ except OSError as exc:
1263
+ errors.append(f"{fpath.name}: {exc}")
1264
+ if errors:
1265
+ messagebox.showerror(
1266
+ "Undo Replace",
1267
+ "\n".join(errors[:10]),
1268
+ parent=self,
1269
+ )
1270
+ self._set_status(_t("fif.replace_undo_ok", n=restored))
1271
+ self.after(100, self._start)
1272
+
1273
+ def _copy_results(self) -> None:
1274
+ """Copia os resultados da busca formatados para a área de transferência."""
1275
+ lines: list[str] = []
1276
+ for file_node in self._tree.get_children():
1277
+ file_label = self._tree.item(file_node, "text").strip()
1278
+ for hit_node in self._tree.get_children(file_node):
1279
+ lno_txt = self._tree.item(hit_node, "text").strip()
1280
+ preview = self._tree.set(hit_node, "preview")
1281
+ lines.append(f"{file_label}:{lno_txt}: {preview}")
1282
+ text = "\n".join(lines)
1283
+ self.clipboard_clear()
1284
+ self.clipboard_append(text)
1285
+ self._set_status(
1286
+ f"{len(lines)} resultado(s) copiado(s) para o clipboard")
1287
+
1288
+ def _hist_q_up(self, _e: Any = None) -> str:
1289
+ if not self._q_history:
1290
+ return "break"
1291
+ self._q_hist_pos = min(len(self._q_history) - 1, self._q_hist_pos + 1)
1292
+ self._q_var.set(self._q_history[-(self._q_hist_pos + 1)])
1293
+ self._q_entry.icursor("end")
1294
+ return "break"
1295
+
1296
+ def _hist_q_down(self, _e: Any = None) -> str:
1297
+ if self._q_hist_pos <= 0:
1298
+ self._q_hist_pos = -1
1299
+ return "break"
1300
+ self._q_hist_pos -= 1
1301
+ self._q_var.set(self._q_history[-(self._q_hist_pos + 1)])
1302
+ self._q_entry.icursor("end")
1303
+ return "break"
1304
+
1305
+ def _hist_r_up(self, _e: Any = None) -> str:
1306
+ if not self._r_history:
1307
+ return "break"
1308
+ self._r_hist_pos = min(len(self._r_history) - 1, self._r_hist_pos + 1)
1309
+ self._r_var.set(self._r_history[-(self._r_hist_pos + 1)])
1310
+ self._r_entry.icursor("end")
1311
+ return "break"
1312
+
1313
+ def _hist_r_down(self, _e: Any = None) -> str:
1314
+ if self._r_hist_pos <= 0:
1315
+ self._r_hist_pos = -1
1316
+ return "break"
1317
+ self._r_hist_pos -= 1
1318
+ self._r_var.set(self._r_history[-(self._r_hist_pos + 1)])
1319
+ self._r_entry.icursor("end")
1320
+ return "break"
1321
+
1322
+ def _set_status(self, msg: str) -> None:
1323
+ with contextlib.suppress(tk.TclError):
1324
+ self._status.config(text=f" {msg}")
1325
+
1326
+ def _update_progress_bar(self, ratio: float) -> None:
1327
+ with contextlib.suppress(tk.TclError):
1328
+ t = self._tmgr.theme
1329
+ w = self._prog.winfo_width() or 200
1330
+ self._prog.delete("all")
1331
+ if ratio > 0:
1332
+ self._prog.create_rectangle(
1333
+ 0, 0, int(w * min(ratio, 1.0)), 2, fill=t.accent, outline=""
1334
+ )
1335
+
1336
+ def _cancel_search(self) -> None:
1337
+ """Cancela a busca em andamento incrementando a geração de controle."""
1338
+ self._cancel.set()
1339
+ self._search_btn.config(state="normal")
1340
+ self._cancel_btn.config(state="disabled")
1341
+ self._set_status("Busca cancelada.")
1342
+
1343
+ def start_with_query(self, query: str) -> None:
1344
+ """Chamado por SearchBar -> abre e inicia com query pré-preenchida."""
1345
+ if query:
1346
+ self._q_var.set(query)
1347
+ if query not in self._q_history:
1348
+ self._q_history.append(query)
1349
+ self._start()
1350
+
1351
+ def apply_theme(self, t: Theme) -> None:
1352
+ self.config(bg=t.sidebar_bg)
1353
+ for w in self.winfo_children():
1354
+ with contextlib.suppress(tk.TclError):
1355
+ w.config(bg=t.sidebar_bg)