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/ui/file_tree.py ADDED
@@ -0,0 +1,1208 @@
1
+ """Árvore de arquivos do projeto no Codis.
2
+
3
+ Provê ``FileTree``, o painel lateral que exibe a estrutura de diretórios
4
+ do workspace com suporte a operações de arquivo (criar, renomear, excluir,
5
+ arrastar), ícones por extensão e integração com o Git.
6
+
7
+ PERFORMANCE: optimized for minimal UI latency.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import logging
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import threading
19
+ import tkinter as tk
20
+ from collections.abc import Callable
21
+ from pathlib import Path
22
+ from tkinter import messagebox, simpledialog, ttk
23
+ from typing import Any
24
+
25
+ from src import fs_ops
26
+ from src.config import ConfigManager
27
+ from src.constants import (
28
+ FONT_UI,
29
+ )
30
+ from src.editor.autocomplete import IgnoreRules
31
+ from src.i18n import _t
32
+ from src.theme.base import Theme
33
+ from src.theme.manager import ThemeManager
34
+ from src.trash_core import CrossDeviceError
35
+ from src.ui.trash_manager import TrashManager
36
+
37
+ logger = logging.getLogger("Codis")
38
+
39
+ _HIDDEN_SET: frozenset[str] = frozenset(
40
+ {
41
+ "__pycache__",
42
+ ".codis_trash",
43
+ ".git",
44
+ "node_modules",
45
+ ".DS_Store",
46
+ ".mypy_cache",
47
+ ".pytest_cache",
48
+ ".tox",
49
+ "dist",
50
+ "build",
51
+ ".venv",
52
+ "venv",
53
+ "env",
54
+ ".idea",
55
+ ".vscode",
56
+ ".eggs",
57
+ }
58
+ )
59
+
60
+ _WATCH_INTERVAL = 2.5
61
+ _GIT_DEBOUNCE = 4.0
62
+
63
+
64
+ class FileTree(tk.Frame):
65
+ """
66
+ Explorador de arquivos avançado com:
67
+ - Ícones por tipo (unicode)
68
+ - Filtro/busca incremental
69
+ - Status do git (M=modified, A=added, ?=untracked, D=deleted)
70
+ - Lazy loading eficiente (sem duplicações)
71
+ - Drag-and-drop (básico) para mover arquivos
72
+ - Menu de contexto completo (novo arquivo, pasta, renomear, deletar, copiar, cortar, colar)
73
+ - Indicadores de erro lint (arquivo com problemas fica vermelho)
74
+ - Seleção múltipla (Ctrl/Cmd + clique)
75
+ - Atalhos de teclado (F2 renomear, Del deletar, Ctrl+C copiar, Ctrl+X cortar, Ctrl+V colar)
76
+ - Watcher de mudanças no sistema de arquivos
77
+ """
78
+
79
+ # Ligado pelo app: itens de menu de contexto vindos de plugins.
80
+ context_provider: Callable[[str, Any], list[tuple[str, Callable[[], None]]]] | None = None
81
+
82
+ ICONS = {
83
+ "folder": "📁",
84
+ "folder_open": "📂",
85
+ ".py": "py",
86
+ ".js": "🟨",
87
+ ".ts": "🔷",
88
+ ".jsx": "⚛ ",
89
+ ".tsx": "⚛ ",
90
+ ".html": "htm",
91
+ ".css": "css",
92
+ ".scss": "css",
93
+ ".json": "{}",
94
+ ".md": "md",
95
+ ".txt": "txt",
96
+ ".rs": "rs",
97
+ ".go": "go",
98
+ ".java": "java",
99
+ ".cpp": "⚙ ",
100
+ ".c": "⚙ ",
101
+ ".h": "⚙ ",
102
+ ".sh": "📜",
103
+ ".yaml": "⚙ ",
104
+ ".yml": "⚙ ",
105
+ ".toml": "⚙ ",
106
+ ".sql": "🗄 ",
107
+ ".xml": "📰",
108
+ ".env": "🔒",
109
+ ".gitignore": "🔒",
110
+ ".lock": "🔒",
111
+ ".png": "🖼 ",
112
+ ".jpg": "🖼 ",
113
+ ".svg": "🖼 ",
114
+ ".ico": "🖼 ",
115
+ ".mp3": "🎵",
116
+ ".mp4": "🎬",
117
+ ".pdf": "📋",
118
+ ".zip": "🗜 ",
119
+ ".tar": "🗜 ",
120
+ ".gz": "🗜 ",
121
+ "default": "txt",
122
+ }
123
+
124
+ GIT_STATUS_COLORS = {
125
+ "M": "#e2b96f",
126
+ "A": "#73c991",
127
+ "?": "#7fb7d4",
128
+ "D": "#f44747",
129
+ "R": "#569cd6",
130
+ "U": "#e2b96f",
131
+ }
132
+
133
+ HIDDEN = {
134
+ "__pycache__",
135
+ ".codis_trash",
136
+ ".git",
137
+ "node_modules",
138
+ ".DS_Store",
139
+ ".mypy_cache",
140
+ ".pytest_cache",
141
+ ".tox",
142
+ "dist",
143
+ "build",
144
+ ".venv",
145
+ "venv",
146
+ "env",
147
+ ".idea",
148
+ ".vscode",
149
+ ".eggs",
150
+ "*.egg-info",
151
+ }
152
+
153
+ def __init__(
154
+ self,
155
+ parent: tk.Widget,
156
+ tmgr: ThemeManager,
157
+ cfg: ConfigManager,
158
+ on_open: Callable[[Path], None],
159
+ on_renamed: Callable[[Path, Path], None] | None = None,
160
+ ) -> None:
161
+ t = tmgr.theme
162
+ super().__init__(parent, bg=t.sidebar_bg)
163
+ self._on_renamed = on_renamed
164
+ self._ignore_rules = None
165
+ self._tmgr = tmgr
166
+ self._cfg = cfg
167
+ self._on_open = on_open
168
+ self._root_path: Path | None = None
169
+ self._root_missing_warned = False
170
+ self._git_status: dict[str, str] = {}
171
+ threading.Lock()
172
+ self._problem_files: set = set()
173
+ self._expanded: set = set()
174
+ self._filter = ""
175
+ self._watch_thread: threading.Thread | None = None
176
+ self._watch_stop = threading.Event()
177
+ self._last_mtime: dict[str, float] = {}
178
+ self._clipboard_data: tuple[str, list[Path]] | None = None
179
+
180
+ self._path_to_iid: dict[str, str] = {}
181
+
182
+ self._refresh_job: str | None = None
183
+
184
+ self._git_last_run: float = 0.0
185
+ self._git_running: bool = False
186
+
187
+ self._filter_job: str | None = None
188
+
189
+ self._build()
190
+ self._bind_shortcuts()
191
+
192
+ self.bind("<<FileTreeRefresh>>", self._on_refresh_event)
193
+
194
+ def _build(self) -> None:
195
+ t = self._tmgr.theme
196
+
197
+ hdr = tk.Frame(self, bg=t.sidebar_bg, height=36)
198
+ hdr.pack(fill="x")
199
+ hdr.pack_propagate(False)
200
+
201
+ tk.Label(
202
+ hdr,
203
+ text=_t("sidebar.explorer"),
204
+ bg=t.sidebar_bg,
205
+ fg=t.sidebar_header_fg,
206
+ font=(FONT_UI, 9, "bold"),
207
+ ).pack(side="left", padx=4)
208
+
209
+ for icon, _, cmd in (
210
+ ("⊕", _t("file.new"), self._new_file),
211
+ ("📁", _t("filetree.new_folder"), self._new_folder),
212
+ ("↻", "Refresh", self.refresh),
213
+ ("⊟", "Collapse", self._collapse_all),
214
+ ):
215
+ btn = tk.Label(
216
+ hdr,
217
+ text=icon,
218
+ bg=t.sidebar_bg,
219
+ fg=t.sidebar_fg,
220
+ font=(FONT_UI, 10),
221
+ cursor="hand2",
222
+ padx=4,
223
+ )
224
+ btn.pack(side="right")
225
+ btn.bind("<Button-1>", lambda _, c=cmd: c())
226
+ btn.bind("<Enter>", lambda _, b=btn: b.config(fg=t.fg))
227
+ btn.bind("<Leave>", lambda _, b=btn: b.config(fg=t.sidebar_fg))
228
+
229
+ self._trash_btn = tk.Label(
230
+ hdr,
231
+ text="🗑",
232
+ bg=t.sidebar_bg,
233
+ fg=t.fg_muted,
234
+ font=(FONT_UI, 10),
235
+ cursor="hand2",
236
+ padx=4,
237
+ )
238
+ self._trash_btn.pack(side="right")
239
+ self._trash_btn.bind("<Button-1>", lambda _: self._open_trash_panel())
240
+ self._trash_btn.bind(
241
+ "<Enter>", lambda _: self._trash_btn.config(fg=t.fg))
242
+ self._trash_btn.bind(
243
+ "<Leave>", lambda _: self._trash_btn.config(fg=t.fg_muted))
244
+ self._update_trash_badge()
245
+
246
+ self._search_var = tk.StringVar()
247
+ self._search_var.trace_add("write", self._on_search_change)
248
+ search_frame = tk.Frame(self, bg=t.sidebar_bg)
249
+ search_frame.pack(fill="x", padx=4, pady=(0, 4))
250
+ tk.Label(
251
+ search_frame, text="🔍", bg=t.sidebar_bg, fg=t.fg_muted, font=(FONT_UI, 9)
252
+ ).pack(side="left")
253
+ tk.Entry(
254
+ search_frame,
255
+ textvariable=self._search_var,
256
+ bg=t.input_bg,
257
+ fg=t.fg,
258
+ insertbackground=t.cursor,
259
+ relief="flat",
260
+ bd=0,
261
+ font=(FONT_UI, 9),
262
+ highlightthickness=1,
263
+ highlightbackground=t.border,
264
+ ).pack(side="left", fill="x", expand=True, padx=2)
265
+
266
+ tree_frame = tk.Frame(self, bg=t.sidebar_bg)
267
+ tree_frame.pack(fill="both", expand=True)
268
+
269
+ style = ttk.Style()
270
+ style.configure(
271
+ "FileTree.Treeview",
272
+ background=t.sidebar_bg,
273
+ foreground=t.sidebar_fg,
274
+ fieldbackground=t.sidebar_bg,
275
+ borderwidth=0,
276
+ rowheight=22,
277
+ font=(FONT_UI, 9),
278
+ )
279
+ style.configure(
280
+ "FileTree.Treeview.Heading",
281
+ background=t.sidebar_bg,
282
+ foreground=t.sidebar_fg,
283
+ )
284
+ style.map(
285
+ "FileTree.Treeview",
286
+ background=[("selected", t.sel_bg)],
287
+ foreground=[("selected", t.sel_fg)],
288
+ )
289
+
290
+ self._tree = ttk.Treeview(
291
+ tree_frame,
292
+ selectmode="extended",
293
+ show="tree",
294
+ style="FileTree.Treeview",
295
+ )
296
+ vsb = ttk.Scrollbar(
297
+ tree_frame,
298
+ orient="vertical",
299
+ command=self._tree.yview,
300
+ style="Thin.Vertical.TScrollbar",
301
+ )
302
+ vsb.pack(side="right", fill="y")
303
+ self._tree.config(yscrollcommand=vsb.set)
304
+ self._tree.pack(fill="both", expand=True)
305
+
306
+ self._tree.bind("<Double-Button-1>", self._on_dbl)
307
+ self._tree.bind("<Return>", self._on_dbl)
308
+ self._tree.bind("<Button-3>", self._ctx_menu)
309
+ self._tree.bind("<<TreeviewOpen>>", self._on_expand)
310
+ self._tree.bind("<<TreeviewClose>>", self._on_collapse)
311
+ self._tree.bind("<Button-1>", self._on_click, add=True)
312
+
313
+ def _bind_shortcuts(self) -> None:
314
+ self._tree.bind("<Delete>", self._delete_selected)
315
+ self._tree.bind("<Shift-Delete>", self._delete_selected_permanent)
316
+ self._tree.bind("<Control-z>", self._undo_delete)
317
+ self.bind("<<TrashChanged>>", lambda _e: self._on_trash_changed(), add="+")
318
+ self._tree.bind("<F2>", self._rename_selected)
319
+ self._tree.bind("<Control-c>", self._copy_selected)
320
+ self._tree.bind("<Control-x>", self._cut_selected)
321
+ self._tree.bind("<Control-v>", self._paste)
322
+
323
+ def set_root(self, path: Path) -> None:
324
+ self._root_path = path
325
+ self._root_missing_warned = False
326
+ TrashManager.set_context(path or None, self._cfg)
327
+ if path:
328
+ TrashManager.purge_expired_async(
329
+ lambda n: n and self._safe_event("<<TrashChanged>>"))
330
+ if path:
331
+ self._ignore_rules = IgnoreRules(path)
332
+ self._ignore_rules.load()
333
+ else:
334
+ self._ignore_rules = None
335
+ self._expanded = set()
336
+ self._path_to_iid.clear()
337
+ self._stop_watcher()
338
+ self.refresh()
339
+ self._start_watcher()
340
+
341
+ def refresh(self) -> None:
342
+ """Debounced refresh - coalece chamadas múltiplas em 80 ms."""
343
+ if self._refresh_job:
344
+ with contextlib.suppress(tk.TclError):
345
+ self.after_cancel(self._refresh_job)
346
+ self._refresh_job = self.after(80, self._do_refresh)
347
+
348
+ def _do_refresh(self) -> None:
349
+ self._refresh_job = None
350
+ if not self._root_path:
351
+ return
352
+ if not self._root_path.exists():
353
+ self._on_root_path_missing()
354
+ return
355
+ self._root_missing_warned = False
356
+ self._rebuild_tree()
357
+ self._update_git_status()
358
+
359
+ def _on_root_path_missing(self) -> None:
360
+ """Trata o caso em que a pasta raiz do workspace some do disco.
361
+
362
+ Pode acontecer se o usuário (ou outro programa) apagar, mover ou
363
+ desmontar a pasta enquanto o Codis está aberto. Evita que
364
+ `_insert_dir` propague `FileNotFoundError`/`OSError` e deixe a árvore
365
+ travada sem explicação.
366
+ """
367
+ if self._tree.get_children():
368
+ self._tree.delete(*self._tree.get_children())
369
+ self._path_to_iid.clear()
370
+ logger.warning(
371
+ "Pasta raiz do workspace não existe mais: %s", self._root_path)
372
+ if not self._root_missing_warned:
373
+ self._root_missing_warned = True
374
+ with contextlib.suppress(tk.TclError):
375
+ messagebox.showwarning(
376
+ _t("filetree.root_missing_title", "Pasta não encontrada"),
377
+ _t(
378
+ "filetree.root_missing_msg",
379
+ "A pasta do workspace '{path}' não foi encontrada. Ela pode "
380
+ "ter sido apagada, movida ou desmontada externamente.",
381
+ path=str(self._root_path),
382
+ ),
383
+ parent=self,
384
+ )
385
+
386
+ def _on_refresh_event(self, _e: Any) -> None:
387
+ self.refresh()
388
+
389
+ def _rebuild_tree(self) -> None:
390
+ """Reconstrói a árvore de forma EFICIENTE usando batch delete."""
391
+ if self._tree.get_children():
392
+ self._tree.delete(*self._tree.get_children())
393
+ self._path_to_iid.clear()
394
+ if not self._root_path or not self._root_path.exists():
395
+ return
396
+ self._insert_dir(self._root_path, "")
397
+
398
+ def _insert_dir(self, path: Path, parent: str) -> None:
399
+ try:
400
+ with os.scandir(path) as it:
401
+ entries = sorted(
402
+ it,
403
+ key=lambda e: (not e.is_dir(
404
+ follow_symlinks=False), e.name.lower()),
405
+ )
406
+ except PermissionError:
407
+ return
408
+ except OSError as exc:
409
+ logger.debug("Não foi possível listar %s: %s", path, exc)
410
+ return
411
+
412
+ show_hidden = self._cfg.get("show_hidden_files", False)
413
+ q = self._filter.lower()
414
+
415
+ for entry in entries:
416
+ p = Path(entry.path)
417
+ if not show_hidden and self._is_hidden_entry(entry):
418
+ continue
419
+ if q and not self._matches_filter_fast(p, q):
420
+ continue
421
+ self._insert_entry_fast(p, entry.is_dir(
422
+ follow_symlinks=False), parent)
423
+
424
+ def _insert_entry_fast(self, path: Path, is_dir: bool, parent: str) -> None:
425
+ """Versão otimizada de _insert_entry - sem lock no hot-path crítico."""
426
+ t = self._tmgr.theme
427
+ icon = (
428
+ self.ICONS["folder"]
429
+ if is_dir
430
+ else self.ICONS.get(path.suffix.lower(), self.ICONS["default"])
431
+ )
432
+
433
+ git_status_snap = self._git_status
434
+ git_st = git_status_snap.get(str(path), "")
435
+ git_col = self.GIT_STATUS_COLORS.get(git_st, "")
436
+ has_prob = str(path) in self._problem_files
437
+
438
+ fg_color = t.err_fg if has_prob else git_col if git_col else t.sidebar_fg
439
+
440
+ label = f"{icon} {path.name}"
441
+ if git_st:
442
+ label += f" {git_st}"
443
+
444
+ item_id = self._tree.insert(
445
+ parent,
446
+ "end",
447
+ text=label,
448
+ tags=(str(path), "dir" if is_dir else "file"),
449
+ open=str(path) in self._expanded,
450
+ )
451
+ if fg_color != t.sidebar_fg:
452
+ self._tree.tag_configure(str(path), foreground=fg_color)
453
+
454
+ self._path_to_iid[str(path)] = item_id
455
+
456
+ if is_dir:
457
+ self._tree.insert(
458
+ item_id, "end", text=_t("ui.loading"), tags=("placeholder",)
459
+ )
460
+
461
+ def _recolor_tree(self) -> None:
462
+ t = self._tmgr.theme
463
+ git_status_snap = self._git_status
464
+ for item in self._tree.get_children():
465
+ self._recolor_item(item, t, git_status_snap)
466
+
467
+ def _recolor_item(self, item: str, t: Theme, git_snap: dict[str, str]) -> None:
468
+ tags = self._tree.item(item, "tags")
469
+ if tags:
470
+ path_str = tags[0]
471
+ git_st = git_snap.get(path_str, "")
472
+ git_col = self.GIT_STATUS_COLORS.get(git_st, "")
473
+ has_prob = path_str in self._problem_files
474
+ fg = t.err_fg if has_prob else git_col if git_col else t.sidebar_fg
475
+ self._tree.tag_configure(path_str, foreground=fg)
476
+ for child in self._tree.get_children(item):
477
+ self._recolor_item(child, t, git_snap)
478
+
479
+ def _is_hidden_entry(self, entry: os.DirEntry[str]) -> bool:
480
+ """Versão rápida usando DirEntry (sem stat extra)."""
481
+ name = entry.name
482
+ if name.startswith(".") and name != ".env":
483
+ return True
484
+ if name in _HIDDEN_SET:
485
+ return True
486
+ if name.endswith(".egg-info"):
487
+ return True
488
+ if self._cfg.get("respect_ignore_files", True) and self._ignore_rules:
489
+ with contextlib.suppress(Exception):
490
+ if self._ignore_rules.is_ignored(Path(entry.path)):
491
+ return True
492
+ return False
493
+
494
+ @staticmethod
495
+ def _matches_filter_fast(path: Path, q: str) -> bool:
496
+ """Versão rápida: verifica nome primeiro, só faz rglob se for diretório."""
497
+ if q in path.name.lower():
498
+ return True
499
+ if path.is_dir():
500
+ with contextlib.suppress(PermissionError, OSError):
501
+ for child in path.rglob("*"):
502
+ if child.is_file() and q in child.name.lower():
503
+ return True
504
+ return False
505
+
506
+ def _on_search_change(self, *_: Any) -> None:
507
+ """Debounce de 200 ms no filtro de busca - evita rebuild por tecla."""
508
+ if self._filter_job:
509
+ with contextlib.suppress(tk.TclError):
510
+ self.after_cancel(self._filter_job)
511
+ self._filter_job = self.after(200, self._apply_filter)
512
+
513
+ def _apply_filter(self) -> None:
514
+ self._filter_job = None
515
+ self._filter = self._search_var.get()
516
+ self._rebuild_tree()
517
+
518
+ def _on_click(self, e: tk.Event) -> None:
519
+ item = self._tree.identify_row(e.y)
520
+ if not item:
521
+ return
522
+ self._tree.focus(item)
523
+
524
+ def _on_dbl(self, _e: Any = None) -> None:
525
+ sel = self._tree.selection()
526
+ if not sel:
527
+ return
528
+ item = sel[0]
529
+ tags = self._tree.item(item, "tags")
530
+ if not tags or "placeholder" in tags:
531
+ return
532
+ path = Path(tags[0])
533
+ if path.is_file():
534
+ self._on_open(path)
535
+ else:
536
+ if self._tree.item(item, "open"):
537
+ self._tree.item(item, open=False)
538
+ else:
539
+ self._tree.item(item, open=True)
540
+
541
+ def _on_expand(self, _e: tk.Event) -> None:
542
+ item = self._tree.focus()
543
+ tags = self._tree.item(item, "tags")
544
+ if not tags:
545
+ return
546
+ path_str = tags[0]
547
+ path = Path(path_str)
548
+ if not path.is_dir():
549
+ return
550
+
551
+ children = self._tree.get_children(item)
552
+ if children:
553
+ if len(children) == 1:
554
+ child_tags = self._tree.item(children[0], "tags")
555
+ if child_tags and "placeholder" in child_tags:
556
+ self._tree.delete(children[0])
557
+ else:
558
+ return
559
+ else:
560
+ return
561
+
562
+ self._expanded.add(path_str)
563
+ self._insert_dir(path, item)
564
+
565
+ def _on_collapse(self, _e: tk.Event) -> None:
566
+ item = self._tree.focus()
567
+ tags = self._tree.item(item, "tags")
568
+ if tags:
569
+ self._expanded.discard(tags[0])
570
+
571
+ def _ctx_menu(self, e: tk.Event) -> None:
572
+ t = self._tmgr.theme
573
+ item = self._tree.identify_row(e.y)
574
+ if item and item not in self._tree.selection():
575
+ self._tree.selection_set(item)
576
+ selected = self._tree.selection()
577
+ paths = []
578
+ for sel in selected:
579
+ tags = self._tree.item(sel, "tags")
580
+ if tags and "placeholder" not in tags:
581
+ paths.append(Path(tags[0]))
582
+
583
+ menu = tk.Menu(
584
+ self,
585
+ tearoff=False,
586
+ bg=t.floating_bg,
587
+ fg=t.fg,
588
+ activebackground=t.sel_bg,
589
+ activeforeground=t.sel_fg,
590
+ relief="flat",
591
+ )
592
+
593
+ if not paths:
594
+ menu.add_command(label=_t("file.new"), command=self._new_file)
595
+ menu.add_command(label=_t("filetree.new_folder"),
596
+ command=self._new_folder)
597
+ menu.add_command(label=_t("filetree.paste"), command=self._paste)
598
+ else:
599
+ first = paths[0]
600
+ is_file = first.is_file()
601
+ menu.add_command(
602
+ label=_t("filetree.open"), command=lambda: self._open_paths(paths)
603
+ )
604
+ if is_file:
605
+ menu.add_command(
606
+ label=_t("filetree.open_with"),
607
+ command=lambda: self._open_with(first),
608
+ )
609
+ _img_exts = {
610
+ ".png",
611
+ ".jpg",
612
+ ".jpeg",
613
+ ".gif",
614
+ ".bmp",
615
+ ".svg",
616
+ ".ico",
617
+ ".webp",
618
+ }
619
+ _txt_exts = {
620
+ ".txt",
621
+ ".md",
622
+ ".json",
623
+ ".yaml",
624
+ ".toml",
625
+ ".cfg",
626
+ ".ini",
627
+ ".env",
628
+ ".csv",
629
+ ".xml",
630
+ ".html",
631
+ ".css",
632
+ ".log",
633
+ }
634
+ if first.suffix.lower() in _img_exts:
635
+ menu.add_command(
636
+ label=_t("filetree.preview_image"),
637
+ command=lambda: self._preview_image(first),
638
+ )
639
+ elif first.suffix.lower() in _txt_exts:
640
+ menu.add_command(
641
+ label=_t("filetree.preview"),
642
+ command=lambda: self._preview_text(first),
643
+ )
644
+ menu.add_separator()
645
+ menu.add_command(
646
+ label=_t("filetree.cut"),
647
+ command=lambda: self._copy_or_cut("cut", paths),
648
+ )
649
+ menu.add_command(
650
+ label=_t("filetree.copy"),
651
+ command=lambda: self._copy_or_cut("copy", paths),
652
+ )
653
+ menu.add_command(label=_t("filetree.paste"), command=self._paste)
654
+ menu.add_separator()
655
+ menu.add_command(
656
+ label=_t("filetree.rename"), command=lambda: self._rename(first)
657
+ )
658
+ menu.add_command(
659
+ label=_t("filetree.delete"), command=lambda: self._delete_paths(paths)
660
+ )
661
+ menu.add_command(
662
+ label=_t("trash.delete_perm"),
663
+ command=lambda: self._delete_paths(paths, permanent=True),
664
+ )
665
+ menu.add_separator()
666
+ menu.add_command(
667
+ label=_t("file.copy_path"),
668
+ command=lambda: self._copy_paths(paths, full=True),
669
+ )
670
+ menu.add_command(
671
+ label=_t("filetree.copy_rel_path"),
672
+ command=lambda: self._copy_paths(paths, full=False),
673
+ )
674
+ menu.add_separator()
675
+ menu.add_command(
676
+ label=_t("filetree.reveal"), command=lambda: self._reveal(first)
677
+ )
678
+ extra = type(self).context_provider("file_tree", first) if type(self).context_provider else []
679
+ if extra:
680
+ menu.add_separator()
681
+ for label, action in extra:
682
+ menu.add_command(label=label, command=action)
683
+
684
+ try:
685
+ menu.tk_popup(e.x_root, e.y_root)
686
+ finally:
687
+ menu.grab_release()
688
+
689
+ def _preview_image(self, path: Path) -> None:
690
+ win = tk.Toplevel(self)
691
+ win.title(path.name)
692
+ win.geometry("600x450")
693
+ win.configure(bg="#1e1e1e")
694
+ try:
695
+ from PIL import Image, ImageTk # type: ignore
696
+
697
+ img = Image.open(path)
698
+ img.thumbnail((580, 420))
699
+ photo = ImageTk.PhotoImage(img)
700
+ lbl = tk.Label(win, image=photo, bg="#1e1e1e")
701
+ lbl.image = photo
702
+ lbl.pack(fill="both", expand=True, padx=4, pady=4)
703
+ except ImportError:
704
+ try:
705
+ photo = tk.PhotoImage(file=str(path))
706
+ lbl = tk.Label(win, image=photo, bg="#1e1e1e")
707
+ lbl.image = photo
708
+ lbl.pack(fill="both", expand=True)
709
+ except tk.TclError:
710
+ tk.Label(
711
+ win,
712
+ text=_t(
713
+ "filetree.pillow_hint",
714
+ "Instale Pillow para pré-visualizar imagens:\npip install Pillow",
715
+ ),
716
+ bg="#1e1e1e",
717
+ fg="#cccccc",
718
+ font=("Segoe UI", 10),
719
+ ).pack(expand=True)
720
+ except Exception as exc:
721
+ tk.Label(
722
+ win,
723
+ text=f"Erro ao carregar imagem:\n{exc}",
724
+ bg="#1e1e1e",
725
+ fg="#ff6b6b",
726
+ font=("Segoe UI", 10),
727
+ ).pack(expand=True)
728
+ tk.Button(
729
+ win,
730
+ text=_t("filetree.close", "Fechar"),
731
+ command=win.destroy,
732
+ bg="#2d2d2d",
733
+ fg="#cccccc",
734
+ relief="flat",
735
+ ).pack(pady=4)
736
+
737
+ def _preview_text(self, path: Path) -> None:
738
+ win = tk.Toplevel(self)
739
+ win.title(path.name)
740
+ win.geometry("700x500")
741
+ win.configure(bg="#1e1e1e")
742
+ frame = tk.Frame(win, bg="#1e1e1e")
743
+ frame.pack(fill="both", expand=True, padx=4, pady=4)
744
+ sb = tk.Scrollbar(frame)
745
+ sb.pack(side="right", fill="y")
746
+ txt = tk.Text(
747
+ frame,
748
+ bg="#1e1e1e",
749
+ fg="#d4d4d4",
750
+ insertbackground="#d4d4d4",
751
+ font=("Consolas", 10),
752
+ relief="flat",
753
+ bd=0,
754
+ yscrollcommand=sb.set,
755
+ state="normal",
756
+ wrap="none",
757
+ )
758
+ txt.pack(fill="both", expand=True)
759
+ sb.config(command=txt.yview)
760
+ try:
761
+ text_content = path.read_text(encoding="utf-8", errors="replace")
762
+ lines = text_content.splitlines()
763
+ preview = "\n".join(lines[:500])
764
+ if len(lines) > 500:
765
+ preview += f"\n\n... ({len(lines) - 500} linhas omitidas)"
766
+ txt.insert("1.0", preview)
767
+ except Exception as exc:
768
+ txt.insert("1.0", f"Erro ao ler arquivo:\n{exc}")
769
+ txt.config(state="disabled")
770
+ tk.Button(
771
+ win,
772
+ text=_t("filetree.open_in_editor", "Abrir no Editor"),
773
+ bg="#2d2d2d",
774
+ fg="#cccccc",
775
+ relief="flat",
776
+ command=lambda: (self._on_open(path), win.destroy()),
777
+ ).pack(side="left", padx=4, pady=4)
778
+ tk.Button(
779
+ win,
780
+ text=_t("filetree.close", "Fechar"),
781
+ command=win.destroy,
782
+ bg="#2d2d2d",
783
+ fg="#cccccc",
784
+ relief="flat",
785
+ ).pack(side="right", padx=4, pady=4)
786
+
787
+ def _open_paths(self, paths: list[Path]) -> None:
788
+ for p in paths:
789
+ if p.is_file():
790
+ self._on_open(p)
791
+ else:
792
+ iid = self._path_to_iid.get(str(p))
793
+ if iid:
794
+ self._tree.item(iid, open=True)
795
+
796
+ def _open_with(self, path: Path) -> None:
797
+ try:
798
+ if sys.platform == "win32":
799
+ os.startfile(path)
800
+ elif sys.platform == "darwin":
801
+ subprocess.Popen(["open", str(path)])
802
+ else:
803
+ subprocess.Popen(["xdg-open", str(path)])
804
+ except OSError as e:
805
+ messagebox.showerror(
806
+ _t("ui.error_title", "Erro"), _t("err.file_open_tree", e=e), parent=self
807
+ )
808
+
809
+ @staticmethod
810
+ def _reveal(path: Path) -> None:
811
+ with contextlib.suppress(OSError):
812
+ if sys.platform == "win32":
813
+ subprocess.Popen(["explorer", "/select,", str(path)])
814
+ elif sys.platform == "darwin":
815
+ subprocess.Popen(["open", "-R", str(path)])
816
+ else:
817
+ subprocess.Popen(["xdg-open", str(path.parent)])
818
+
819
+ def _copy_or_cut(self, mode: str, paths: list[Path]) -> None:
820
+ self._clipboard_data = (mode, paths)
821
+
822
+ def _paste(self) -> None:
823
+ if not self._clipboard_data:
824
+ return
825
+ mode, src_paths = self._clipboard_data
826
+ dest_dir = self._get_target_directory()
827
+ if not dest_dir:
828
+ return
829
+ moved_any = False
830
+ for src in src_paths:
831
+ dest = dest_dir / src.name
832
+ try:
833
+ if mode == "copy":
834
+ self._paste_copy(src, dest)
835
+ elif self._paste_move(src, dest):
836
+ moved_any = True
837
+ except (OSError, shutil.Error) as e:
838
+ messagebox.showerror(
839
+ _t("hc.git_panel.error"), f"Failed to {mode}: {e}", parent=self
840
+ )
841
+ if moved_any:
842
+ self._clipboard_data = None # o que foi movido não existe mais na origem
843
+ self.refresh()
844
+
845
+ def _confirm_replace(self, dest: Path) -> bool:
846
+ """Pergunta antes de sobrescrever; o padrão da resposta é "não"."""
847
+ return messagebox.askyesno(
848
+ _t("filetree.replace_title", "Replace?"),
849
+ _t("filetree.replace_prompt", name=dest.name),
850
+ icon="warning",
851
+ default="no",
852
+ parent=self,
853
+ )
854
+
855
+ def _paste_copy(self, src: Path, dest: Path) -> None:
856
+ if dest == src:
857
+ dest = fs_ops.unique_copy_path(dest) # copiar para a própria pasta cria "nome copy"
858
+ elif dest.exists():
859
+ if src.is_dir() or dest.is_dir():
860
+ self._show_exists_error(dest)
861
+ return
862
+ if not self._confirm_replace(dest):
863
+ return
864
+ if src.is_dir():
865
+ shutil.copytree(src, dest)
866
+ else:
867
+ shutil.copy2(src, dest)
868
+
869
+ def _show_exists_error(self, dest: Path) -> None:
870
+ messagebox.showerror(_t("hc.git_panel.error"), _t("filetree.err_exists", name=dest.name), parent=self)
871
+
872
+ def _paste_move(self, src: Path, dest: Path) -> bool:
873
+ """Move ``src`` para ``dest`` sem sobrescrever em silêncio. Devolve se moveu."""
874
+ if dest == src:
875
+ return False
876
+ if dest.exists():
877
+ if src.is_dir() or dest.is_dir():
878
+ self._show_exists_error(dest)
879
+ return False
880
+ if not self._confirm_replace(dest):
881
+ return False
882
+ os.replace(src, dest)
883
+ else:
884
+ src.rename(dest)
885
+ if self._on_renamed:
886
+ self._on_renamed(src, dest)
887
+ return True
888
+
889
+ def _get_target_directory(self) -> Path | None:
890
+ sel = self._tree.selection()
891
+ if sel:
892
+ tags = self._tree.item(sel[0], "tags")
893
+ if tags:
894
+ p = Path(tags[0])
895
+ if p.is_dir():
896
+ return p
897
+ return p.parent
898
+ return self._root_path
899
+
900
+ def _copy_paths(self, paths: list[Path], full: bool) -> None:
901
+ if full:
902
+ texts = [str(p) for p in paths]
903
+ else:
904
+ if self._root_path:
905
+ texts = [str(p.relative_to(self._root_path)) for p in paths]
906
+ else:
907
+ texts = [p.name for p in paths]
908
+ self.clipboard_clear()
909
+ self.clipboard_append("\n".join(texts))
910
+
911
+ def _find_and_select(self, item_id: str, target: Path) -> bool:
912
+ data = self._tree.item(item_id)
913
+ tags = data.get("tags", ())
914
+ if tags and str(target) in tags:
915
+ self._tree.selection_set(item_id)
916
+ self._tree.see(item_id)
917
+ return True
918
+ for child in self._tree.get_children(item_id):
919
+ if self._find_and_select(child, target):
920
+ return True
921
+ return False
922
+
923
+ def _rename(self, path: Path) -> None:
924
+ new_name = simpledialog.askstring(
925
+ _t("filetree.rename"),
926
+ _t("ui.rename_prompt"),
927
+ initialvalue=path.name,
928
+ parent=self,
929
+ )
930
+ if not new_name or new_name == path.name:
931
+ return
932
+ problem = fs_ops.check_new_name(new_name, path.parent, current=path.name)
933
+ if problem:
934
+ key = "filetree.err_exists" if problem == fs_ops.EXISTS else "filetree.err_invalid"
935
+ messagebox.showerror(_t("hc.git_panel.error"), _t(key, name=new_name), parent=self)
936
+ return
937
+ target = path.parent / new_name
938
+ try:
939
+ path.rename(target)
940
+ except OSError as e:
941
+ messagebox.showerror(_t("hc.git_panel.error"), str(e), parent=self)
942
+ return
943
+ if self._on_renamed:
944
+ self._on_renamed(path, target)
945
+ self.refresh()
946
+
947
+ def _rename_selected(self, _e: tk.Event = None) -> None:
948
+ sel = self._tree.selection()
949
+ if sel:
950
+ tags = self._tree.item(sel[0], "tags")
951
+ if tags:
952
+ self._rename(Path(tags[0]))
953
+
954
+ def _delete_paths(self, paths: list[Path], *, permanent: bool = False) -> None:
955
+ """Move para a lixeira do projeto (ou exclui de vez com ``permanent``)."""
956
+ paths = [p for p in paths if p]
957
+ if not paths:
958
+ return
959
+ if permanent or self._cfg.get("confirm_delete", True):
960
+ key = "trash.delete_perm_confirm" if permanent else "trash.delete_confirm"
961
+ msg = _t(f"{key}_one" if len(paths) == 1 else f"{key}_many",
962
+ name=paths[0].name, n=len(paths))
963
+ if not messagebox.askyesno(
964
+ _t("filetree.delete"), msg, icon="warning" if permanent else "question", parent=self
965
+ ):
966
+ return
967
+ if permanent:
968
+ def _work() -> None:
969
+ for p in paths:
970
+ try:
971
+ TrashManager.delete(p, permanent=True)
972
+ except OSError as exc:
973
+ logger.warning("Exclusão definitiva falhou: %s", exc)
974
+ self._safe_event("<<FileTreeRefresh>>")
975
+ self._safe_event("<<TrashChanged>>")
976
+
977
+ threading.Thread(target=_work, daemon=True, name="codis-perm-delete").start()
978
+ return
979
+ for p in paths:
980
+ try:
981
+ TrashManager.delete(p)
982
+ except CrossDeviceError:
983
+ messagebox.showerror(_t("hc.git_panel.error"), _t("trash.cross_device", name=p.name),
984
+ parent=self)
985
+ except (OSError, shutil.Error) as e:
986
+ messagebox.showerror(
987
+ _t("hc.git_panel.error"),
988
+ _t("trash.delete_failed", name=p.name, err=e),
989
+ parent=self,
990
+ )
991
+ self.refresh()
992
+ self._on_trash_changed()
993
+
994
+ def _selected_paths(self) -> list[Path]:
995
+ out: list[Path] = []
996
+ for item in self._tree.selection():
997
+ tags = self._tree.item(item, "tags")
998
+ if tags and "placeholder" not in tags:
999
+ out.append(Path(tags[0]))
1000
+ return out
1001
+
1002
+ def _delete_selected(self, _e: tk.Event = None) -> None:
1003
+ self._delete_paths(self._selected_paths())
1004
+
1005
+ def _delete_selected_permanent(self, _e: tk.Event = None) -> str:
1006
+ self._delete_paths(self._selected_paths(), permanent=True)
1007
+ return "break"
1008
+
1009
+ def _undo_delete(self, _e: tk.Event = None) -> str:
1010
+ """Ctrl+Z na árvore: restaura a última exclusão desta sessão."""
1011
+ dest = TrashManager.undo_last()
1012
+ if dest is None:
1013
+ return "break"
1014
+ self.refresh()
1015
+ self._on_trash_changed()
1016
+ return "break"
1017
+
1018
+ def _safe_event(self, name: str) -> None:
1019
+ """``event_generate`` tolerante (pode ser chamado de thread / após destroy)."""
1020
+ with contextlib.suppress(tk.TclError, RuntimeError):
1021
+ self.event_generate(name, when="tail")
1022
+
1023
+ def _on_trash_changed(self) -> None:
1024
+ self._update_trash_badge()
1025
+ panel = getattr(self, "_trash_panel_ref", None)
1026
+ if panel is not None:
1027
+ with contextlib.suppress(tk.TclError):
1028
+ if panel.winfo_exists():
1029
+ panel.refresh()
1030
+
1031
+ def _clip_selected(self, mode: str = "copy", _e: tk.Event = None) -> None:
1032
+ """Copia (mode='copy') ou recorta (mode='cut') os itens selecionados."""
1033
+ sel = self._tree.selection()
1034
+ if sel:
1035
+ paths = [Path(self._tree.item(item, "tags")[0]) for item in sel]
1036
+ self._copy_or_cut(mode, paths)
1037
+
1038
+ def _copy_selected(self, _e: tk.Event = None) -> None:
1039
+ self._clip_selected("copy")
1040
+
1041
+ def _cut_selected(self, _e: tk.Event = None) -> None:
1042
+ self._clip_selected("cut")
1043
+
1044
+ def _new_file(self, base: Path | None = None) -> None:
1045
+ folder = (
1046
+ base if base and base.is_dir() else base.parent if base else self._root_path
1047
+ )
1048
+ if not folder:
1049
+ return
1050
+ name = simpledialog.askstring(
1051
+ _t("file.new"), _t("ui.new_file_prompt"), parent=self
1052
+ )
1053
+ if not name:
1054
+ return
1055
+
1056
+ if "." not in name:
1057
+ ans = messagebox.askyesno(
1058
+ "No extension",
1059
+ f"'{name}' has no extension. Create without extension?",
1060
+ parent=self,
1061
+ )
1062
+ if not ans:
1063
+ ext = simpledialog.askstring(
1064
+ "Extension", "Enter extension (e.g., .txt, .py):", parent=self
1065
+ )
1066
+ if ext is None:
1067
+ return
1068
+ if not ext.startswith("."):
1069
+ ext = "." + ext
1070
+ name += ext
1071
+
1072
+ p = folder / name
1073
+ try:
1074
+ p.touch()
1075
+ self.refresh()
1076
+ self._on_open(p)
1077
+ except OSError as e:
1078
+ messagebox.showerror(_t("hc.git_panel.error"), str(e))
1079
+
1080
+ def _new_folder(self, base: Path | None = None) -> None:
1081
+ folder = (
1082
+ base if base and base.is_dir() else base.parent if base else self._root_path
1083
+ )
1084
+ if not folder:
1085
+ return
1086
+ name = simpledialog.askstring(
1087
+ _t("filetree.new_folder"), _t("ui.new_folder_prompt"), parent=self
1088
+ )
1089
+ if name:
1090
+ try:
1091
+ (folder / name).mkdir(parents=True, exist_ok=True)
1092
+ self.refresh()
1093
+ except OSError as e:
1094
+ messagebox.showerror(_t("hc.git_panel.error"), str(e))
1095
+
1096
+ def _collapse_all(self) -> None:
1097
+ self._expanded.clear()
1098
+ for item in self._tree.get_children():
1099
+ self._tree.item(item, open=False)
1100
+
1101
+ def _update_git_status(self) -> None:
1102
+ """Dispara git-status assíncrono com debounce de _GIT_DEBOUNCE segundos."""
1103
+ import time
1104
+
1105
+ if self._git_running:
1106
+ return
1107
+ now = time.monotonic()
1108
+ if now - self._git_last_run < _GIT_DEBOUNCE:
1109
+ return
1110
+ if not self._root_path:
1111
+ return
1112
+ self._git_running = True
1113
+ self._git_last_run = now
1114
+ root = self._root_path
1115
+
1116
+ def _run() -> None:
1117
+ new_status: dict[str, str] = {}
1118
+ with contextlib.suppress(OSError, FileNotFoundError, subprocess.TimeoutExpired):
1119
+ r = subprocess.run(
1120
+ ["git", "status", "--porcelain", "-u",
1121
+ "--ignore-submodules=dirty"],
1122
+ capture_output=True,
1123
+ text=True,
1124
+ encoding="utf-8",
1125
+ errors="replace",
1126
+ cwd=str(root),
1127
+ timeout=5,
1128
+ check=False,
1129
+ )
1130
+ for line in r.stdout.splitlines():
1131
+ if len(line) >= 3:
1132
+ status = line[:2].strip()
1133
+ fname = line[3:].strip()
1134
+ full = str(root / fname)
1135
+ new_status[full] = status[0] if status else "?"
1136
+ with contextlib.suppress(Exception):
1137
+ self.after(0, self._apply_git_status, new_status)
1138
+
1139
+ t = threading.Thread(target=_run, daemon=True, name="codis-git-status")
1140
+ t.start()
1141
+
1142
+ def _apply_git_status(self, new_status: dict[str, str]) -> None:
1143
+ if not self.winfo_exists():
1144
+ self._git_running = False
1145
+ return
1146
+ self._git_status = new_status
1147
+ self._git_running = False
1148
+ with contextlib.suppress(Exception):
1149
+ self._recolor_tree()
1150
+
1151
+ def _start_watcher(self) -> None:
1152
+ if not self._root_path:
1153
+ return
1154
+ self._watch_stop.clear()
1155
+ self._watch_thread = threading.Thread(
1156
+ target=self._watch_loop, daemon=True, name="codis-filetree-watch"
1157
+ )
1158
+ self._watch_thread.start()
1159
+
1160
+ def _stop_watcher(self) -> None:
1161
+ self._watch_stop.set()
1162
+
1163
+ def _watch_loop(self) -> None:
1164
+ """Watcher leve: verifica mtime do diretório raiz a cada _WATCH_INTERVAL s."""
1165
+ while not self._watch_stop.is_set():
1166
+ if self._root_path and self._root_path.exists():
1167
+ with contextlib.suppress(OSError):
1168
+ mtime = self._root_path.stat().st_mtime
1169
+ key = str(self._root_path)
1170
+ if self._last_mtime.get(key) != mtime:
1171
+ self._last_mtime[key] = mtime
1172
+ with contextlib.suppress(tk.TclError):
1173
+ self.event_generate(
1174
+ "<<FileTreeRefresh>>", when="tail")
1175
+ self._watch_stop.wait(_WATCH_INTERVAL)
1176
+
1177
+ def _update_trash_badge(self) -> None:
1178
+ if not hasattr(self, "_trash_btn"):
1179
+ return
1180
+ count = TrashManager.count()
1181
+ t = self._tmgr.theme
1182
+ if count > 0:
1183
+ label = f"🗑{count}" if count < 100 else "🗑99+"
1184
+ accent = getattr(t, "error_fg", "#ff5555")
1185
+ self._trash_btn.config(text=label, fg=accent)
1186
+ else:
1187
+ self._trash_btn.config(text="🗑", fg=t.fg_muted)
1188
+
1189
+ def _open_trash_panel(self) -> None:
1190
+ from src.ui.trash_manager import TrashPanel
1191
+
1192
+ win = tk.Toplevel(self)
1193
+ win.title(_t("trash.title", "Lixeira"))
1194
+ win.geometry("420x480")
1195
+ win.resizable(True, True)
1196
+ t = self._tmgr.theme
1197
+ win.configure(bg=t.sidebar_bg)
1198
+ panel = TrashPanel(win, self._tmgr, self._cfg)
1199
+ panel.pack(fill="both", expand=True)
1200
+ self._trash_panel_ref = panel
1201
+ win.bind("<<TrashChanged>>", lambda _e: self._update_trash_badge(), add="+")
1202
+ win.bind("<Destroy>", lambda e: (setattr(self, "_trash_panel_ref", None),
1203
+ self._update_trash_badge()) if e.widget is win else None)
1204
+
1205
+ def apply_theme(self, t: Theme) -> None:
1206
+ self.config(bg=t.sidebar_bg)
1207
+ self._rebuild_tree()
1208
+ self._update_trash_badge()