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,719 @@
1
+ """Codis - SmartTips: sistema de dicas flutuantes inteligentes para o editor.
2
+
3
+ Exibe dicas contextuais não-intrusivas baseadas em gatilhos automáticos:
4
+
5
+ - **Arquivo grande**: avisa quando o arquivo tem muitas linhas
6
+ - **Complexidade**: detecta funções/classes aninhadas profundamente
7
+ - **Convenção de nome**: detecta variáveis de nome genérico (x, tmp, data...)
8
+ - **Dados especiais**: detecta senhas/tokens em texto literal
9
+ - **Linhas longas**: avisa quando muitas linhas excedem 100 caracteres
10
+ - **Funções grandes**: detecta funções com muitas linhas
11
+ - **Imports duplicados**: detecta imports repetidos no topo do arquivo
12
+ - **TODO acumulado**: avisa quando há muitos comentários TODO/FIXME
13
+ - **Trailing whitespace**: detecta excesso de espaço em branco final
14
+ - **Encoding especial**: avisa sobre caracteres invisíveis no arquivo
15
+
16
+ As dicas aparecem como balões flutuantes no canto inferior direito do editor,
17
+ com animação de fade-in e auto-dismiss após alguns segundos.
18
+ Podem ser dispensadas manualmente ou desabilitadas globalmente nas configurações.
19
+
20
+ Uso::
21
+
22
+ from src.editor.smart_tips import SmartTips
23
+ tips = SmartTips(editor_pane, config_manager, theme_manager)
24
+ tips.analyse() # chamado ao abrir/salvar arquivo
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import ast
30
+ import contextlib
31
+ import logging
32
+ import re
33
+ import time
34
+ import tkinter as tk
35
+ from dataclasses import dataclass, field
36
+ from pathlib import Path
37
+ from typing import TYPE_CHECKING
38
+
39
+ from src.i18n import _t
40
+
41
+ if TYPE_CHECKING:
42
+ from src.config import ConfigManager
43
+ from src.theme.manager import ThemeManager
44
+
45
+ logger = logging.getLogger("Codis")
46
+
47
+ _LARGE_FILE_LINES = 1000
48
+ _HUGE_FILE_LINES = 2000
49
+ # Acima disso só a dica de tamanho roda: os demais detectores leem o texto inteiro (regex, AST).
50
+ _MAX_ANALYSIS_CHARS = 2_000_000
51
+ _LONG_LINE_CHARS = 100
52
+ _LONG_LINE_RATIO = 0.20
53
+ _BIG_FUNCTION_LINES = 60
54
+ _DEEP_NESTING = 5
55
+ _TODO_THRESHOLD = 5
56
+ _GENERIC_VAR_THRESHOLD = 4
57
+ _TIP_DISPLAY_MS = 9_000
58
+ _TIP_FADE_STEPS = 15
59
+ _TIP_FADE_INTERVAL_MS = 40
60
+ _MIN_INTERVAL_MS = 30_000
61
+
62
+ _GENERIC_NAMES: frozenset[str] = frozenset(
63
+ {
64
+ "data",
65
+ "temp",
66
+ "tmp",
67
+ "x",
68
+ "y",
69
+ "z",
70
+ "n",
71
+ "i",
72
+ "j",
73
+ "k",
74
+ "foo",
75
+ "bar",
76
+ "baz",
77
+ "val",
78
+ "value",
79
+ "result",
80
+ "res",
81
+ "item",
82
+ "obj",
83
+ "info",
84
+ "stuff",
85
+ "thing",
86
+ "var",
87
+ "a",
88
+ "b",
89
+ "c",
90
+ }
91
+ )
92
+
93
+ _SECRET_PATTERNS: list[re.Pattern] = [
94
+ re.compile(
95
+ r'(?i)(password|passwd|pwd|secret|api_key|apikey|token|auth_token)\s*=\s*["\'][^"\']{6,}["\']'
96
+ ),
97
+ re.compile(
98
+ r'(?i)(aws_access_key|aws_secret)\s*=\s*["\'][A-Za-z0-9/+=]{10,}["\']'),
99
+ re.compile(r"(?i)bearer\s+[A-Za-z0-9\-._~+/]+=*"),
100
+ ]
101
+
102
+ _CODE_LANGS: frozenset[str] = frozenset(
103
+ {
104
+ "python",
105
+ "javascript",
106
+ "typescript",
107
+ "java",
108
+ "c",
109
+ "cpp",
110
+ "csharp",
111
+ "go",
112
+ "rust",
113
+ "ruby",
114
+ "php",
115
+ "kotlin",
116
+ "swift",
117
+ "scala",
118
+ "r",
119
+ "julia",
120
+ "haskell",
121
+ "elixir",
122
+ "erlang",
123
+ "lua",
124
+ "groovy",
125
+ }
126
+ )
127
+
128
+ _INDENT_LANGS: frozenset[str] = frozenset(
129
+ {
130
+ "python",
131
+ "javascript",
132
+ "typescript",
133
+ "java",
134
+ "c",
135
+ "cpp",
136
+ "csharp",
137
+ "go",
138
+ "rust",
139
+ "ruby",
140
+ "php",
141
+ "kotlin",
142
+ "swift",
143
+ }
144
+ )
145
+
146
+
147
+ @dataclass
148
+ class Tip:
149
+ """Representa uma dica a ser exibida."""
150
+
151
+ key: str
152
+ icon: str
153
+ title_key: str
154
+ body_key: str
155
+ body_kwargs: dict
156
+ priority: int = 0
157
+ lang_filter: frozenset[str] | None = None
158
+
159
+
160
+ @dataclass
161
+ class _TipState:
162
+ """Estado interno do sistema de dicas."""
163
+
164
+ shown_keys: set[str] = field(default_factory=set)
165
+ last_shown_ms: int = 0
166
+ current_win: tk.Toplevel | None = None
167
+ pending_job: str | None = None
168
+ fade_job: str | None = None
169
+ alpha: float = 1.0
170
+
171
+
172
+ class SmartTips:
173
+ """Sistema de dicas flutuantes inteligentes para o editor Codis.
174
+
175
+ Args:
176
+ widget: Widget de referência (normalmente o EditorPane ou seu tk.Text).
177
+ cfg: Instância do ConfigManager.
178
+ tmgr: Instância do ThemeManager.
179
+ """
180
+
181
+ def __init__(
182
+ self,
183
+ widget: tk.Widget,
184
+ cfg: ConfigManager,
185
+ tmgr: ThemeManager,
186
+ ) -> None:
187
+ self._widget = widget
188
+ self._cfg = cfg
189
+ self._tmgr = tmgr
190
+ self._state = _TipState()
191
+ self._analyse_job: str | None = None
192
+ self._min_interval_ms: int = _MIN_INTERVAL_MS
193
+
194
+ def _threshold(self, key: str, default: int) -> int:
195
+ """Lê um limiar de análise do ConfigManager, com fallback para a constante padrão.
196
+
197
+ Todos os valores de gatilho das dicas são configuráveis pelo usuário
198
+ via Settings Editor. Este método garante que o código sempre leia o
199
+ valor mais atualizado sem precisar reiniciar o editor.
200
+ """
201
+ return int(self._cfg.get(key, default))
202
+
203
+ def analyse(
204
+ self,
205
+ content: str,
206
+ lang: str,
207
+ path: Path | None = None,
208
+ delay_ms: int = 1200,
209
+ ) -> None:
210
+ """Agenda análise do conteúdo atual e exibe a dica mais relevante.
211
+
212
+ Chamado após abertura ou salvamento de arquivo. Usa debounce para
213
+ não bloquear o carregamento do arquivo.
214
+
215
+ Args:
216
+ content: Texto completo do arquivo.
217
+ lang: Linguagem detectada (ex: ``"python"``).
218
+ path: Caminho do arquivo (opcional).
219
+ delay_ms: Delay antes de analisar (ms).
220
+ """
221
+ if not self._cfg.get("smart_tips", True):
222
+ return
223
+ if self._analyse_job:
224
+ with contextlib.suppress(ValueError, tk.TclError):
225
+ self._widget.after_cancel(self._analyse_job)
226
+ self._analyse_job = self._widget.after(
227
+ delay_ms,
228
+ lambda: self._run_analysis(content, lang, path),
229
+ )
230
+
231
+ def dismiss(self) -> None:
232
+ """Dispensa a dica atual imediatamente."""
233
+ self._close_tip()
234
+
235
+ def reset_session(self) -> None:
236
+ """Limpa o histórico de dicas já exibidas nesta sessão."""
237
+ self._state.shown_keys.clear()
238
+
239
+ def _run_analysis(self, content: str, lang: str, path: Path | None) -> None:
240
+ """Executa todos os detectores e escolhe a dica mais prioritária."""
241
+ self._analyse_job = None
242
+ if not self._cfg.get("smart_tips", True):
243
+ return
244
+
245
+ now_ms = int(time.monotonic() * 1000)
246
+ interval_s = self._cfg.get(
247
+ "smart_tips_interval", _MIN_INTERVAL_MS // 1000)
248
+ min_ms = max(5000, int(interval_s) * 1000)
249
+ if now_ms - self._state.last_shown_ms < min_ms:
250
+ return
251
+
252
+ candidates: list[Tip] = []
253
+ lines = content.splitlines()
254
+ n_lines = len(lines)
255
+
256
+ self._check_file_size(lines, n_lines, lang, candidates)
257
+ if len(content) <= _MAX_ANALYSIS_CHARS:
258
+ self._check_long_lines(lines, n_lines, lang, candidates)
259
+ self._check_secret_patterns(content, lang, candidates)
260
+ self._check_todos(content, lang, candidates)
261
+ if lang in _INDENT_LANGS:
262
+ self._check_deep_nesting(lines, n_lines, candidates)
263
+ if lang == "python":
264
+ self._check_python_specifics(content, lines, candidates)
265
+ self._check_generic_vars(content, lang, candidates)
266
+ if path:
267
+ self._check_filename(path, candidates)
268
+
269
+ visible = [
270
+ t
271
+ for t in candidates
272
+ if t.key not in self._state.shown_keys
273
+ and (t.lang_filter is None or lang in t.lang_filter)
274
+ ]
275
+ if not visible:
276
+ return
277
+
278
+ best = max(visible, key=lambda t: t.priority)
279
+ self._state.shown_keys.add(best.key)
280
+ self._state.last_shown_ms = now_ms
281
+ self._show_tip(best)
282
+
283
+ def _check_file_size(
284
+ self, lines: list[str], n_lines: int, lang: str, out: list[Tip]
285
+ ) -> None:
286
+ if lang not in _CODE_LANGS:
287
+ return
288
+ large = self._threshold(
289
+ "smart_tips_large_file_lines", _LARGE_FILE_LINES)
290
+ huge = self._threshold("smart_tips_huge_file_lines", _HUGE_FILE_LINES)
291
+ if n_lines >= huge:
292
+ out.append(
293
+ Tip(
294
+ key=f"huge_file_{n_lines // 500}",
295
+ icon="📦",
296
+ title_key="tips.large_file.title",
297
+ body_key="tips.large_file.huge",
298
+ body_kwargs={"lines": n_lines},
299
+ priority=80,
300
+ lang_filter=_CODE_LANGS,
301
+ )
302
+ )
303
+ elif n_lines >= large:
304
+ out.append(
305
+ Tip(
306
+ key=f"large_file_{n_lines // 100}",
307
+ icon="📄",
308
+ title_key="tips.large_file.title",
309
+ body_key="tips.large_file.body",
310
+ body_kwargs={"lines": n_lines},
311
+ priority=50,
312
+ lang_filter=_CODE_LANGS,
313
+ )
314
+ )
315
+
316
+ def _check_long_lines(
317
+ self, lines: list[str], n_lines: int, lang: str, out: list[Tip]
318
+ ) -> None:
319
+ if n_lines < 10:
320
+ return
321
+ limit = self._threshold("smart_tips_long_line_chars", _LONG_LINE_CHARS)
322
+ long = sum(1 for l_ in lines if len(l_) > limit)
323
+ ratio = long / max(n_lines, 1)
324
+ if ratio >= _LONG_LINE_RATIO:
325
+ out.append(
326
+ Tip(
327
+ key=f"long_lines_{long // 5}",
328
+ icon="↔️",
329
+ title_key="tips.long_lines.title",
330
+ body_key="tips.long_lines.body",
331
+ body_kwargs={"count": long, "limit": limit},
332
+ priority=30,
333
+ )
334
+ )
335
+
336
+ def _check_secret_patterns(self, content: str, lang: str, out: list[Tip]) -> None:
337
+ if lang not in _CODE_LANGS:
338
+ return
339
+ for pat in _SECRET_PATTERNS:
340
+ m = pat.search(content)
341
+ if m:
342
+ snippet = m.group(0)[:40].replace("\n", " ")
343
+ out.append(
344
+ Tip(
345
+ key="secret_hardcoded",
346
+ icon="🔑",
347
+ title_key="tips.secret.title",
348
+ body_key="tips.secret.body",
349
+ body_kwargs={"snippet": snippet},
350
+ priority=100,
351
+ lang_filter=_CODE_LANGS,
352
+ )
353
+ )
354
+ break
355
+
356
+ def _check_todos(self, content: str, lang: str, out: list[Tip]) -> None:
357
+ threshold = self._threshold(
358
+ "smart_tips_todo_threshold", _TODO_THRESHOLD)
359
+ todos = re.findall(r"(?i)\b(TODO|FIXME|HACK|XXX)\b", content)
360
+ if len(todos) >= threshold:
361
+ out.append(
362
+ Tip(
363
+ key=f"todos_{len(todos) // 3}",
364
+ icon="📝",
365
+ title_key="tips.todos.title",
366
+ body_key="tips.todos.body",
367
+ body_kwargs={"count": len(todos)},
368
+ priority=25,
369
+ )
370
+ )
371
+
372
+ def _check_deep_nesting(
373
+ self, lines: list[str], n_lines: int, out: list[Tip]
374
+ ) -> None:
375
+ """Detecta linhas com indentação muito profunda (≥ N níveis)."""
376
+ tab_size = 4
377
+ max_level = self._threshold("smart_tips_deep_nesting", _DEEP_NESTING)
378
+ deep_count = 0
379
+ for line in lines:
380
+ stripped = line.lstrip()
381
+ if not stripped or stripped.startswith(("#", "//", "/*", "*")):
382
+ continue
383
+ indent = len(line) - len(stripped)
384
+ level = indent // tab_size
385
+ if level >= max_level:
386
+ deep_count += 1
387
+
388
+ if deep_count >= 3:
389
+ out.append(
390
+ Tip(
391
+ key=f"deep_nesting_{deep_count // 3}",
392
+ icon="🌀",
393
+ title_key="tips.nesting.title",
394
+ body_key="tips.nesting.body",
395
+ body_kwargs={"lines": deep_count, "level": max_level},
396
+ priority=60,
397
+ )
398
+ )
399
+
400
+ def _check_python_specifics(
401
+ self, content: str, lines: list[str], out: list[Tip]
402
+ ) -> None:
403
+ """Análise específica para Python via AST."""
404
+ with contextlib.suppress(SyntaxError):
405
+ tree = ast.parse(content)
406
+ big_fn_lines = self._threshold(
407
+ "smart_tips_big_function_lines", _BIG_FUNCTION_LINES
408
+ )
409
+ big_fns: list[str] = []
410
+ for node in ast.walk(tree):
411
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
412
+ fn_lines = (node.end_lineno or node.lineno) - node.lineno
413
+ if fn_lines >= big_fn_lines:
414
+ big_fns.append(node.name)
415
+ if big_fns:
416
+ out.append(
417
+ Tip(
418
+ key=f"big_functions_{'_'.join(big_fns[:2])}",
419
+ icon="🐘",
420
+ title_key="tips.big_function.title",
421
+ body_key="tips.big_function.body",
422
+ body_kwargs={
423
+ "name": big_fns[0],
424
+ "count": len(big_fns),
425
+ "lines": big_fn_lines,
426
+ },
427
+ priority=55,
428
+ lang_filter=frozenset({"python"}),
429
+ )
430
+ )
431
+
432
+ import_names: list[str] = []
433
+ for line in lines:
434
+ s = line.strip()
435
+ m = re.match(r"^(?:import|from)\s+(\S+)", s)
436
+ if m:
437
+ import_names.append(m.group(1))
438
+ dupes = {n for n in import_names if import_names.count(n) > 1}
439
+ if dupes:
440
+ out.append(
441
+ Tip(
442
+ key=f"dup_imports_{'_'.join(sorted(dupes)[:2])}",
443
+ icon="🔁",
444
+ title_key="tips.dup_imports.title",
445
+ body_key="tips.dup_imports.body",
446
+ body_kwargs={"modules": ", ".join(sorted(dupes)[:3])},
447
+ priority=45,
448
+ lang_filter=frozenset({"python"}),
449
+ )
450
+ )
451
+
452
+ self._check_generic_vars_python(content, out)
453
+
454
+ def _check_generic_vars(self, content: str, lang: str, out: list[Tip]) -> None:
455
+ """Detecta nomes genéricos de variável em qualquer linguagem."""
456
+ if lang == "python":
457
+ return
458
+ threshold = self._threshold(
459
+ "smart_tips_generic_var_threshold", _GENERIC_VAR_THRESHOLD
460
+ )
461
+ found: set[str] = set()
462
+ for name in _GENERIC_NAMES:
463
+ pattern = re.compile(rf"\b{re.escape(name)}\s*[=:]")
464
+ if pattern.search(content):
465
+ found.add(name)
466
+ if len(found) >= threshold:
467
+ out.append(
468
+ Tip(
469
+ key=f"generic_vars_{'_'.join(sorted(found)[:3])}",
470
+ icon="🏷️",
471
+ title_key="tips.generic_vars.title",
472
+ body_key="tips.generic_vars.body",
473
+ body_kwargs={"vars": ", ".join(sorted(found)[:4])},
474
+ priority=20,
475
+ )
476
+ )
477
+
478
+ def _check_generic_vars_python(self, content: str, out: list[Tip]) -> None:
479
+ """Detecta nomes genéricos de variável em Python via AST."""
480
+ threshold = self._threshold(
481
+ "smart_tips_generic_var_threshold", _GENERIC_VAR_THRESHOLD
482
+ )
483
+ with contextlib.suppress(SyntaxError):
484
+ tree = ast.parse(content)
485
+ found: set[str] = set()
486
+ for node in ast.walk(tree):
487
+ if isinstance(node, ast.Assign):
488
+ for target in node.targets:
489
+ if isinstance(target, ast.Name) and target.id in _GENERIC_NAMES:
490
+ found.add(target.id)
491
+ if len(found) >= threshold:
492
+ out.append(
493
+ Tip(
494
+ key=f"generic_vars_py_{'_'.join(sorted(found)[:3])}",
495
+ icon="🏷️",
496
+ title_key="tips.generic_vars.title",
497
+ body_key="tips.generic_vars.body",
498
+ body_kwargs={"vars": ", ".join(sorted(found)[:4])},
499
+ priority=20,
500
+ lang_filter=frozenset({"python"}),
501
+ )
502
+ )
503
+
504
+ def _check_filename(self, path: Path, out: list[Tip]) -> None:
505
+ """Dicas baseadas no nome do arquivo."""
506
+ name = path.name.lower()
507
+ if name in {"config", "settings", "configuration", "setup"}:
508
+ out.append(
509
+ Tip(
510
+ key="bare_config_file",
511
+ icon="⚙️",
512
+ title_key="tips.config_file.title",
513
+ body_key="tips.config_file.body",
514
+ body_kwargs={"name": path.name},
515
+ priority=10,
516
+ )
517
+ )
518
+ generic_names = {"main", "index", "app", "utils", "helpers", "misc"}
519
+ stem = path.stem.lower()
520
+ if stem in generic_names and path.suffix in {".py", ".js", ".ts"}:
521
+ out.append(
522
+ Tip(
523
+ key=f"generic_filename_{stem}",
524
+ icon="📁",
525
+ title_key="tips.generic_filename.title",
526
+ body_key="tips.generic_filename.body",
527
+ body_kwargs={"name": path.name},
528
+ priority=5,
529
+ )
530
+ )
531
+
532
+ def _show_tip(self, tip: Tip) -> None:
533
+ """Cria e exibe o balão flutuante para a dica fornecida."""
534
+ self._close_tip()
535
+
536
+ try:
537
+ root = self._widget.winfo_toplevel()
538
+ t = self._tmgr.theme
539
+
540
+ title_text = f"{tip.icon} {_t(tip.title_key, tip.title_key)}"
541
+ body_text = _t(tip.body_key, tip.body_key, **tip.body_kwargs)
542
+ dismiss_text = _t("tips.dismiss", "Dispensar")
543
+ disable_text = _t("tips.disable_all", "Desativar dicas")
544
+
545
+ win = tk.Toplevel(root)
546
+ win.wm_overrideredirect(True)
547
+ win.wm_attributes("-topmost", True)
548
+ with contextlib.suppress(tk.TclError):
549
+ win.wm_attributes("-alpha", 0.95)
550
+
551
+ outer = tk.Frame(
552
+ win,
553
+ bg=getattr(t, "floating_border", t.border),
554
+ padx=1,
555
+ pady=1,
556
+ )
557
+ outer.pack(fill="both", expand=True)
558
+
559
+ inner = tk.Frame(outer, bg=t.floating_bg, padx=12, pady=10)
560
+ inner.pack(fill="both", expand=True)
561
+
562
+ accent_color = self._accent_color(tip.priority)
563
+ accent_bar = tk.Frame(inner, bg=accent_color, height=3)
564
+ accent_bar.pack(fill="x", pady=(0, 8))
565
+
566
+ tk.Label(
567
+ inner,
568
+ text=title_text,
569
+ bg=t.floating_bg,
570
+ fg=t.fg,
571
+ font=(getattr(t, "font_ui", "Segoe UI"), 9, "bold"),
572
+ anchor="w",
573
+ justify="left",
574
+ ).pack(fill="x")
575
+
576
+ tk.Label(
577
+ inner,
578
+ text=body_text,
579
+ bg=t.floating_bg,
580
+ fg=getattr(t, "fg_muted", t.fg),
581
+ font=(getattr(t, "font_ui", "Segoe UI"), 9),
582
+ anchor="w",
583
+ justify="left",
584
+ wraplength=320,
585
+ ).pack(fill="x", pady=(4, 8))
586
+
587
+ btn_frame = tk.Frame(inner, bg=t.floating_bg)
588
+ btn_frame.pack(fill="x")
589
+
590
+ btn_style = {
591
+ "bg": t.floating_bg,
592
+ "fg": getattr(t, "accent", "#7aa2f7"),
593
+ "font": (getattr(t, "font_ui", "Segoe UI"), 8),
594
+ "cursor": "hand2",
595
+ "relief": "flat",
596
+ "bd": 0,
597
+ }
598
+
599
+ dismiss_btn = tk.Label(btn_frame, text=dismiss_text, **btn_style)
600
+ dismiss_btn.pack(side="right", padx=(6, 0))
601
+ dismiss_btn.bind("<Button-1>", lambda _: self.dismiss())
602
+ dismiss_btn.bind("<Enter>", lambda _: dismiss_btn.config(fg=t.fg))
603
+ dismiss_btn.bind(
604
+ "<Leave>",
605
+ lambda _: dismiss_btn.config(
606
+ fg=getattr(t, "accent", "#7aa2f7")),
607
+ )
608
+
609
+ disable_btn = tk.Label(btn_frame, text=disable_text, **btn_style)
610
+ disable_btn.pack(side="right")
611
+ disable_btn.bind("<Button-1>", lambda _: self._disable_all())
612
+ disable_btn.bind("<Enter>", lambda _: disable_btn.config(fg=t.fg))
613
+ disable_btn.bind(
614
+ "<Leave>",
615
+ lambda _: disable_btn.config(
616
+ fg=getattr(t, "accent", "#7aa2f7")),
617
+ )
618
+
619
+ self._state.current_win = win
620
+ self._widget.after(10, lambda: self._position_tip(win))
621
+
622
+ self._state.pending_job = self._widget.after(
623
+ _TIP_DISPLAY_MS, self._begin_fade
624
+ )
625
+
626
+ except tk.TclError as exc:
627
+ logger.debug("SmartTips: erro ao criar balão: %s", exc)
628
+
629
+ def _accent_color(self, priority: int) -> str:
630
+ """Retorna cor do acento baseada na prioridade da dica."""
631
+ t = self._tmgr.theme
632
+ if priority >= 90:
633
+ return "#f7768e"
634
+ if priority >= 70:
635
+ return "#e0af68"
636
+ if priority >= 50:
637
+ return "#7aa2f7"
638
+ return getattr(t, "fg_muted", "#565f89")
639
+
640
+ def _position_tip(self, win: tk.Toplevel) -> None:
641
+ """Posiciona o balão no canto inferior direito do widget do editor."""
642
+ with contextlib.suppress(tk.TclError):
643
+ win.update_idletasks()
644
+ w = win.winfo_reqwidth()
645
+ h = win.winfo_reqheight()
646
+
647
+ try:
648
+ rx = self._widget.winfo_rootx()
649
+ ry = self._widget.winfo_rooty()
650
+ rw = self._widget.winfo_width()
651
+ rh = self._widget.winfo_height()
652
+ x = rx + rw - w - 16
653
+ y = ry + rh - h - 36
654
+ except tk.TclError:
655
+ sw = win.winfo_screenwidth()
656
+ sh = win.winfo_screenheight()
657
+ x = sw - w - 20
658
+ y = sh - h - 60
659
+
660
+ sw = win.winfo_screenwidth()
661
+ sh = win.winfo_screenheight()
662
+ x = max(8, min(x, sw - w - 8))
663
+ y = max(8, min(y, sh - h - 8))
664
+
665
+ win.geometry(f"+{x}+{y}")
666
+
667
+ def _begin_fade(self) -> None:
668
+ """Inicia animação de fade-out antes de fechar."""
669
+ self._state.pending_job = None
670
+ self._state.alpha = 0.95
671
+ self._fade_step()
672
+
673
+ def _fade_step(self) -> None:
674
+ """Executa um passo do fade-out."""
675
+ win = self._state.current_win
676
+ if not win:
677
+ return
678
+ try:
679
+ if not win.winfo_exists():
680
+ self._state.current_win = None
681
+ return
682
+ except tk.TclError:
683
+ self._state.current_win = None
684
+ return
685
+
686
+ self._state.alpha -= 0.95 / _TIP_FADE_STEPS
687
+ if self._state.alpha <= 0.05:
688
+ self._close_tip()
689
+ return
690
+ try:
691
+ win.wm_attributes("-alpha", max(0.05, self._state.alpha))
692
+ except tk.TclError:
693
+ self._state.current_win = None
694
+ return
695
+ self._state.fade_job = self._widget.after(
696
+ _TIP_FADE_INTERVAL_MS, self._fade_step
697
+ )
698
+
699
+ def _close_tip(self) -> None:
700
+ """Fecha o balão flutuante atual e cancela jobs pendentes."""
701
+ for job_attr in ("pending_job", "fade_job"):
702
+ job = getattr(self._state, job_attr)
703
+ if job:
704
+ with contextlib.suppress(ValueError, tk.TclError):
705
+ self._widget.after_cancel(job)
706
+ setattr(self._state, job_attr, None)
707
+
708
+ win = self._state.current_win
709
+ if win:
710
+ with contextlib.suppress(tk.TclError):
711
+ if win.winfo_exists():
712
+ win.destroy()
713
+ self._state.current_win = None
714
+
715
+ def _disable_all(self) -> None:
716
+ """Desativa todas as dicas inteligentes e fecha o balão atual."""
717
+ self._cfg.set("smart_tips", False)
718
+ self._cfg.save()
719
+ self._close_tip()